source: frontend/node_modules/rollup/dist/es/shared/rollup.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 874.4 KB
Line 
1/*
2 @license
3 Rollup.js v2.80.0
4 Sun, 22 Feb 2026 06:16:40 GMT - commit d17ae15336a45c3c59b2a4aacac2b14186035d28
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10import require$$0, { resolve, basename, extname, dirname, relative as relative$1, win32, posix, isAbsolute as isAbsolute$1, join } from 'path';
11import process$1 from 'process';
12import { performance } from 'perf_hooks';
13import { createHash as createHash$1 } from 'crypto';
14import { promises } from 'fs';
15import { EventEmitter } from 'events';
16
17var version$1 = "2.80.0";
18
19var charToInteger = {};
20var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
21for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
22 charToInteger[chars$1.charCodeAt(i$1)] = i$1;
23}
24function decode(mappings) {
25 var decoded = [];
26 var line = [];
27 var segment = [
28 0,
29 0,
30 0,
31 0,
32 0,
33 ];
34 var j = 0;
35 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
36 var c = mappings.charCodeAt(i);
37 if (c === 44) { // ","
38 segmentify(line, segment, j);
39 j = 0;
40 }
41 else if (c === 59) { // ";"
42 segmentify(line, segment, j);
43 j = 0;
44 decoded.push(line);
45 line = [];
46 segment[0] = 0;
47 }
48 else {
49 var integer = charToInteger[c];
50 if (integer === undefined) {
51 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
52 }
53 var hasContinuationBit = integer & 32;
54 integer &= 31;
55 value += integer << shift;
56 if (hasContinuationBit) {
57 shift += 5;
58 }
59 else {
60 var shouldNegate = value & 1;
61 value >>>= 1;
62 if (shouldNegate) {
63 value = value === 0 ? -0x80000000 : -value;
64 }
65 segment[j] += value;
66 j++;
67 value = shift = 0; // reset
68 }
69 }
70 }
71 segmentify(line, segment, j);
72 decoded.push(line);
73 return decoded;
74}
75function segmentify(line, segment, j) {
76 // This looks ugly, but we're creating specialized arrays with a specific
77 // length. This is much faster than creating a new array (which v8 expands to
78 // a capacity of 17 after pushing the first item), or slicing out a subarray
79 // (which is slow). Length 4 is assumed to be the most frequent, followed by
80 // length 5 (since not everything will have an associated name), followed by
81 // length 1 (it's probably rare for a source substring to not have an
82 // associated segment data).
83 if (j === 4)
84 line.push([segment[0], segment[1], segment[2], segment[3]]);
85 else if (j === 5)
86 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
87 else if (j === 1)
88 line.push([segment[0]]);
89}
90function encode(decoded) {
91 var sourceFileIndex = 0; // second field
92 var sourceCodeLine = 0; // third field
93 var sourceCodeColumn = 0; // fourth field
94 var nameIndex = 0; // fifth field
95 var mappings = '';
96 for (var i = 0; i < decoded.length; i++) {
97 var line = decoded[i];
98 if (i > 0)
99 mappings += ';';
100 if (line.length === 0)
101 continue;
102 var generatedCodeColumn = 0; // first field
103 var lineMappings = [];
104 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
105 var segment = line_1[_i];
106 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
107 generatedCodeColumn = segment[0];
108 if (segment.length > 1) {
109 segmentMappings +=
110 encodeInteger(segment[1] - sourceFileIndex) +
111 encodeInteger(segment[2] - sourceCodeLine) +
112 encodeInteger(segment[3] - sourceCodeColumn);
113 sourceFileIndex = segment[1];
114 sourceCodeLine = segment[2];
115 sourceCodeColumn = segment[3];
116 }
117 if (segment.length === 5) {
118 segmentMappings += encodeInteger(segment[4] - nameIndex);
119 nameIndex = segment[4];
120 }
121 lineMappings.push(segmentMappings);
122 }
123 mappings += lineMappings.join(',');
124 }
125 return mappings;
126}
127function encodeInteger(num) {
128 var result = '';
129 num = num < 0 ? (-num << 1) | 1 : num << 1;
130 do {
131 var clamped = num & 31;
132 num >>>= 5;
133 if (num > 0) {
134 clamped |= 32;
135 }
136 result += chars$1[clamped];
137 } while (num > 0);
138 return result;
139}
140
141class BitSet {
142 constructor(arg) {
143 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
144 }
145
146 add(n) {
147 this.bits[n >> 5] |= 1 << (n & 31);
148 }
149
150 has(n) {
151 return !!(this.bits[n >> 5] & (1 << (n & 31)));
152 }
153}
154
155class Chunk$1 {
156 constructor(start, end, content) {
157 this.start = start;
158 this.end = end;
159 this.original = content;
160
161 this.intro = '';
162 this.outro = '';
163
164 this.content = content;
165 this.storeName = false;
166 this.edited = false;
167
168 // we make these non-enumerable, for sanity while debugging
169 Object.defineProperties(this, {
170 previous: { writable: true, value: null },
171 next: { writable: true, value: null },
172 });
173 }
174
175 appendLeft(content) {
176 this.outro += content;
177 }
178
179 appendRight(content) {
180 this.intro = this.intro + content;
181 }
182
183 clone() {
184 const chunk = new Chunk$1(this.start, this.end, this.original);
185
186 chunk.intro = this.intro;
187 chunk.outro = this.outro;
188 chunk.content = this.content;
189 chunk.storeName = this.storeName;
190 chunk.edited = this.edited;
191
192 return chunk;
193 }
194
195 contains(index) {
196 return this.start < index && index < this.end;
197 }
198
199 eachNext(fn) {
200 let chunk = this;
201 while (chunk) {
202 fn(chunk);
203 chunk = chunk.next;
204 }
205 }
206
207 eachPrevious(fn) {
208 let chunk = this;
209 while (chunk) {
210 fn(chunk);
211 chunk = chunk.previous;
212 }
213 }
214
215 edit(content, storeName, contentOnly) {
216 this.content = content;
217 if (!contentOnly) {
218 this.intro = '';
219 this.outro = '';
220 }
221 this.storeName = storeName;
222
223 this.edited = true;
224
225 return this;
226 }
227
228 prependLeft(content) {
229 this.outro = content + this.outro;
230 }
231
232 prependRight(content) {
233 this.intro = content + this.intro;
234 }
235
236 split(index) {
237 const sliceIndex = index - this.start;
238
239 const originalBefore = this.original.slice(0, sliceIndex);
240 const originalAfter = this.original.slice(sliceIndex);
241
242 this.original = originalBefore;
243
244 const newChunk = new Chunk$1(index, this.end, originalAfter);
245 newChunk.outro = this.outro;
246 this.outro = '';
247
248 this.end = index;
249
250 if (this.edited) {
251 // TODO is this block necessary?...
252 newChunk.edit('', false);
253 this.content = '';
254 } else {
255 this.content = originalBefore;
256 }
257
258 newChunk.next = this.next;
259 if (newChunk.next) newChunk.next.previous = newChunk;
260 newChunk.previous = this;
261 this.next = newChunk;
262
263 return newChunk;
264 }
265
266 toString() {
267 return this.intro + this.content + this.outro;
268 }
269
270 trimEnd(rx) {
271 this.outro = this.outro.replace(rx, '');
272 if (this.outro.length) return true;
273
274 const trimmed = this.content.replace(rx, '');
275
276 if (trimmed.length) {
277 if (trimmed !== this.content) {
278 this.split(this.start + trimmed.length).edit('', undefined, true);
279 }
280 return true;
281 } else {
282 this.edit('', undefined, true);
283
284 this.intro = this.intro.replace(rx, '');
285 if (this.intro.length) return true;
286 }
287 }
288
289 trimStart(rx) {
290 this.intro = this.intro.replace(rx, '');
291 if (this.intro.length) return true;
292
293 const trimmed = this.content.replace(rx, '');
294
295 if (trimmed.length) {
296 if (trimmed !== this.content) {
297 this.split(this.end - trimmed.length);
298 this.edit('', undefined, true);
299 }
300 return true;
301 } else {
302 this.edit('', undefined, true);
303
304 this.outro = this.outro.replace(rx, '');
305 if (this.outro.length) return true;
306 }
307 }
308}
309
310let btoa = () => {
311 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
312};
313if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
314 btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
315} else if (typeof Buffer === 'function') {
316 btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
317}
318
319class SourceMap {
320 constructor(properties) {
321 this.version = 3;
322 this.file = properties.file;
323 this.sources = properties.sources;
324 this.sourcesContent = properties.sourcesContent;
325 this.names = properties.names;
326 this.mappings = encode(properties.mappings);
327 }
328
329 toString() {
330 return JSON.stringify(this);
331 }
332
333 toUrl() {
334 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
335 }
336}
337
338function guessIndent(code) {
339 const lines = code.split('\n');
340
341 const tabbed = lines.filter((line) => /^\t+/.test(line));
342 const spaced = lines.filter((line) => /^ {2,}/.test(line));
343
344 if (tabbed.length === 0 && spaced.length === 0) {
345 return null;
346 }
347
348 // More lines tabbed than spaced? Assume tabs, and
349 // default to tabs in the case of a tie (or nothing
350 // to go on)
351 if (tabbed.length >= spaced.length) {
352 return '\t';
353 }
354
355 // Otherwise, we need to guess the multiple
356 const min = spaced.reduce((previous, current) => {
357 const numSpaces = /^ +/.exec(current)[0].length;
358 return Math.min(numSpaces, previous);
359 }, Infinity);
360
361 return new Array(min + 1).join(' ');
362}
363
364function getRelativePath(from, to) {
365 const fromParts = from.split(/[/\\]/);
366 const toParts = to.split(/[/\\]/);
367
368 fromParts.pop(); // get dirname
369
370 while (fromParts[0] === toParts[0]) {
371 fromParts.shift();
372 toParts.shift();
373 }
374
375 if (fromParts.length) {
376 let i = fromParts.length;
377 while (i--) fromParts[i] = '..';
378 }
379
380 return fromParts.concat(toParts).join('/');
381}
382
383const toString$1 = Object.prototype.toString;
384
385function isObject$1(thing) {
386 return toString$1.call(thing) === '[object Object]';
387}
388
389function getLocator$1(source) {
390 const originalLines = source.split('\n');
391 const lineOffsets = [];
392
393 for (let i = 0, pos = 0; i < originalLines.length; i++) {
394 lineOffsets.push(pos);
395 pos += originalLines[i].length + 1;
396 }
397
398 return function locate(index) {
399 let i = 0;
400 let j = lineOffsets.length;
401 while (i < j) {
402 const m = (i + j) >> 1;
403 if (index < lineOffsets[m]) {
404 j = m;
405 } else {
406 i = m + 1;
407 }
408 }
409 const line = i - 1;
410 const column = index - lineOffsets[line];
411 return { line, column };
412 };
413}
414
415class Mappings {
416 constructor(hires) {
417 this.hires = hires;
418 this.generatedCodeLine = 0;
419 this.generatedCodeColumn = 0;
420 this.raw = [];
421 this.rawSegments = this.raw[this.generatedCodeLine] = [];
422 this.pending = null;
423 }
424
425 addEdit(sourceIndex, content, loc, nameIndex) {
426 if (content.length) {
427 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
428 if (nameIndex >= 0) {
429 segment.push(nameIndex);
430 }
431 this.rawSegments.push(segment);
432 } else if (this.pending) {
433 this.rawSegments.push(this.pending);
434 }
435
436 this.advance(content);
437 this.pending = null;
438 }
439
440 addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
441 let originalCharIndex = chunk.start;
442 let first = true;
443
444 while (originalCharIndex < chunk.end) {
445 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
446 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
447 }
448
449 if (original[originalCharIndex] === '\n') {
450 loc.line += 1;
451 loc.column = 0;
452 this.generatedCodeLine += 1;
453 this.raw[this.generatedCodeLine] = this.rawSegments = [];
454 this.generatedCodeColumn = 0;
455 first = true;
456 } else {
457 loc.column += 1;
458 this.generatedCodeColumn += 1;
459 first = false;
460 }
461
462 originalCharIndex += 1;
463 }
464
465 this.pending = null;
466 }
467
468 advance(str) {
469 if (!str) return;
470
471 const lines = str.split('\n');
472
473 if (lines.length > 1) {
474 for (let i = 0; i < lines.length - 1; i++) {
475 this.generatedCodeLine++;
476 this.raw[this.generatedCodeLine] = this.rawSegments = [];
477 }
478 this.generatedCodeColumn = 0;
479 }
480
481 this.generatedCodeColumn += lines[lines.length - 1].length;
482 }
483}
484
485const n = '\n';
486
487const warned = {
488 insertLeft: false,
489 insertRight: false,
490 storeName: false,
491};
492
493class MagicString {
494 constructor(string, options = {}) {
495 const chunk = new Chunk$1(0, string.length, string);
496
497 Object.defineProperties(this, {
498 original: { writable: true, value: string },
499 outro: { writable: true, value: '' },
500 intro: { writable: true, value: '' },
501 firstChunk: { writable: true, value: chunk },
502 lastChunk: { writable: true, value: chunk },
503 lastSearchedChunk: { writable: true, value: chunk },
504 byStart: { writable: true, value: {} },
505 byEnd: { writable: true, value: {} },
506 filename: { writable: true, value: options.filename },
507 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
508 sourcemapLocations: { writable: true, value: new BitSet() },
509 storedNames: { writable: true, value: {} },
510 indentStr: { writable: true, value: guessIndent(string) },
511 });
512
513 this.byStart[0] = chunk;
514 this.byEnd[string.length] = chunk;
515 }
516
517 addSourcemapLocation(char) {
518 this.sourcemapLocations.add(char);
519 }
520
521 append(content) {
522 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
523
524 this.outro += content;
525 return this;
526 }
527
528 appendLeft(index, content) {
529 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
530
531 this._split(index);
532
533 const chunk = this.byEnd[index];
534
535 if (chunk) {
536 chunk.appendLeft(content);
537 } else {
538 this.intro += content;
539 }
540 return this;
541 }
542
543 appendRight(index, content) {
544 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
545
546 this._split(index);
547
548 const chunk = this.byStart[index];
549
550 if (chunk) {
551 chunk.appendRight(content);
552 } else {
553 this.outro += content;
554 }
555 return this;
556 }
557
558 clone() {
559 const cloned = new MagicString(this.original, { filename: this.filename });
560
561 let originalChunk = this.firstChunk;
562 let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
563
564 while (originalChunk) {
565 cloned.byStart[clonedChunk.start] = clonedChunk;
566 cloned.byEnd[clonedChunk.end] = clonedChunk;
567
568 const nextOriginalChunk = originalChunk.next;
569 const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
570
571 if (nextClonedChunk) {
572 clonedChunk.next = nextClonedChunk;
573 nextClonedChunk.previous = clonedChunk;
574
575 clonedChunk = nextClonedChunk;
576 }
577
578 originalChunk = nextOriginalChunk;
579 }
580
581 cloned.lastChunk = clonedChunk;
582
583 if (this.indentExclusionRanges) {
584 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
585 }
586
587 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
588
589 cloned.intro = this.intro;
590 cloned.outro = this.outro;
591
592 return cloned;
593 }
594
595 generateDecodedMap(options) {
596 options = options || {};
597
598 const sourceIndex = 0;
599 const names = Object.keys(this.storedNames);
600 const mappings = new Mappings(options.hires);
601
602 const locate = getLocator$1(this.original);
603
604 if (this.intro) {
605 mappings.advance(this.intro);
606 }
607
608 this.firstChunk.eachNext((chunk) => {
609 const loc = locate(chunk.start);
610
611 if (chunk.intro.length) mappings.advance(chunk.intro);
612
613 if (chunk.edited) {
614 mappings.addEdit(
615 sourceIndex,
616 chunk.content,
617 loc,
618 chunk.storeName ? names.indexOf(chunk.original) : -1
619 );
620 } else {
621 mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
622 }
623
624 if (chunk.outro.length) mappings.advance(chunk.outro);
625 });
626
627 return {
628 file: options.file ? options.file.split(/[/\\]/).pop() : null,
629 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
630 sourcesContent: options.includeContent ? [this.original] : [null],
631 names,
632 mappings: mappings.raw,
633 };
634 }
635
636 generateMap(options) {
637 return new SourceMap(this.generateDecodedMap(options));
638 }
639
640 getIndentString() {
641 return this.indentStr === null ? '\t' : this.indentStr;
642 }
643
644 indent(indentStr, options) {
645 const pattern = /^[^\r\n]/gm;
646
647 if (isObject$1(indentStr)) {
648 options = indentStr;
649 indentStr = undefined;
650 }
651
652 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
653
654 if (indentStr === '') return this; // noop
655
656 options = options || {};
657
658 // Process exclusion ranges
659 const isExcluded = {};
660
661 if (options.exclude) {
662 const exclusions =
663 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
664 exclusions.forEach((exclusion) => {
665 for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
666 isExcluded[i] = true;
667 }
668 });
669 }
670
671 let shouldIndentNextCharacter = options.indentStart !== false;
672 const replacer = (match) => {
673 if (shouldIndentNextCharacter) return `${indentStr}${match}`;
674 shouldIndentNextCharacter = true;
675 return match;
676 };
677
678 this.intro = this.intro.replace(pattern, replacer);
679
680 let charIndex = 0;
681 let chunk = this.firstChunk;
682
683 while (chunk) {
684 const end = chunk.end;
685
686 if (chunk.edited) {
687 if (!isExcluded[charIndex]) {
688 chunk.content = chunk.content.replace(pattern, replacer);
689
690 if (chunk.content.length) {
691 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
692 }
693 }
694 } else {
695 charIndex = chunk.start;
696
697 while (charIndex < end) {
698 if (!isExcluded[charIndex]) {
699 const char = this.original[charIndex];
700
701 if (char === '\n') {
702 shouldIndentNextCharacter = true;
703 } else if (char !== '\r' && shouldIndentNextCharacter) {
704 shouldIndentNextCharacter = false;
705
706 if (charIndex === chunk.start) {
707 chunk.prependRight(indentStr);
708 } else {
709 this._splitChunk(chunk, charIndex);
710 chunk = chunk.next;
711 chunk.prependRight(indentStr);
712 }
713 }
714 }
715
716 charIndex += 1;
717 }
718 }
719
720 charIndex = chunk.end;
721 chunk = chunk.next;
722 }
723
724 this.outro = this.outro.replace(pattern, replacer);
725
726 return this;
727 }
728
729 insert() {
730 throw new Error(
731 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
732 );
733 }
734
735 insertLeft(index, content) {
736 if (!warned.insertLeft) {
737 console.warn(
738 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
739 ); // eslint-disable-line no-console
740 warned.insertLeft = true;
741 }
742
743 return this.appendLeft(index, content);
744 }
745
746 insertRight(index, content) {
747 if (!warned.insertRight) {
748 console.warn(
749 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
750 ); // eslint-disable-line no-console
751 warned.insertRight = true;
752 }
753
754 return this.prependRight(index, content);
755 }
756
757 move(start, end, index) {
758 if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
759
760 this._split(start);
761 this._split(end);
762 this._split(index);
763
764 const first = this.byStart[start];
765 const last = this.byEnd[end];
766
767 const oldLeft = first.previous;
768 const oldRight = last.next;
769
770 const newRight = this.byStart[index];
771 if (!newRight && last === this.lastChunk) return this;
772 const newLeft = newRight ? newRight.previous : this.lastChunk;
773
774 if (oldLeft) oldLeft.next = oldRight;
775 if (oldRight) oldRight.previous = oldLeft;
776
777 if (newLeft) newLeft.next = first;
778 if (newRight) newRight.previous = last;
779
780 if (!first.previous) this.firstChunk = last.next;
781 if (!last.next) {
782 this.lastChunk = first.previous;
783 this.lastChunk.next = null;
784 }
785
786 first.previous = newLeft;
787 last.next = newRight || null;
788
789 if (!newLeft) this.firstChunk = first;
790 if (!newRight) this.lastChunk = last;
791 return this;
792 }
793
794 overwrite(start, end, content, options) {
795 if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
796
797 while (start < 0) start += this.original.length;
798 while (end < 0) end += this.original.length;
799
800 if (end > this.original.length) throw new Error('end is out of bounds');
801 if (start === end)
802 throw new Error(
803 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
804 );
805
806 this._split(start);
807 this._split(end);
808
809 if (options === true) {
810 if (!warned.storeName) {
811 console.warn(
812 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
813 ); // eslint-disable-line no-console
814 warned.storeName = true;
815 }
816
817 options = { storeName: true };
818 }
819 const storeName = options !== undefined ? options.storeName : false;
820 const contentOnly = options !== undefined ? options.contentOnly : false;
821
822 if (storeName) {
823 const original = this.original.slice(start, end);
824 Object.defineProperty(this.storedNames, original, {
825 writable: true,
826 value: true,
827 enumerable: true,
828 });
829 }
830
831 const first = this.byStart[start];
832 const last = this.byEnd[end];
833
834 if (first) {
835 let chunk = first;
836 while (chunk !== last) {
837 if (chunk.next !== this.byStart[chunk.end]) {
838 throw new Error('Cannot overwrite across a split point');
839 }
840 chunk = chunk.next;
841 chunk.edit('', false);
842 }
843
844 first.edit(content, storeName, contentOnly);
845 } else {
846 // must be inserting at the end
847 const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
848
849 // TODO last chunk in the array may not be the last chunk, if it's moved...
850 last.next = newChunk;
851 newChunk.previous = last;
852 }
853 return this;
854 }
855
856 prepend(content) {
857 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
858
859 this.intro = content + this.intro;
860 return this;
861 }
862
863 prependLeft(index, content) {
864 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
865
866 this._split(index);
867
868 const chunk = this.byEnd[index];
869
870 if (chunk) {
871 chunk.prependLeft(content);
872 } else {
873 this.intro = content + this.intro;
874 }
875 return this;
876 }
877
878 prependRight(index, content) {
879 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
880
881 this._split(index);
882
883 const chunk = this.byStart[index];
884
885 if (chunk) {
886 chunk.prependRight(content);
887 } else {
888 this.outro = content + this.outro;
889 }
890 return this;
891 }
892
893 remove(start, end) {
894 while (start < 0) start += this.original.length;
895 while (end < 0) end += this.original.length;
896
897 if (start === end) return this;
898
899 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
900 if (start > end) throw new Error('end must be greater than start');
901
902 this._split(start);
903 this._split(end);
904
905 let chunk = this.byStart[start];
906
907 while (chunk) {
908 chunk.intro = '';
909 chunk.outro = '';
910 chunk.edit('');
911
912 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
913 }
914 return this;
915 }
916
917 lastChar() {
918 if (this.outro.length) return this.outro[this.outro.length - 1];
919 let chunk = this.lastChunk;
920 do {
921 if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
922 if (chunk.content.length) return chunk.content[chunk.content.length - 1];
923 if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
924 } while ((chunk = chunk.previous));
925 if (this.intro.length) return this.intro[this.intro.length - 1];
926 return '';
927 }
928
929 lastLine() {
930 let lineIndex = this.outro.lastIndexOf(n);
931 if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
932 let lineStr = this.outro;
933 let chunk = this.lastChunk;
934 do {
935 if (chunk.outro.length > 0) {
936 lineIndex = chunk.outro.lastIndexOf(n);
937 if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
938 lineStr = chunk.outro + lineStr;
939 }
940
941 if (chunk.content.length > 0) {
942 lineIndex = chunk.content.lastIndexOf(n);
943 if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
944 lineStr = chunk.content + lineStr;
945 }
946
947 if (chunk.intro.length > 0) {
948 lineIndex = chunk.intro.lastIndexOf(n);
949 if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
950 lineStr = chunk.intro + lineStr;
951 }
952 } while ((chunk = chunk.previous));
953 lineIndex = this.intro.lastIndexOf(n);
954 if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
955 return this.intro + lineStr;
956 }
957
958 slice(start = 0, end = this.original.length) {
959 while (start < 0) start += this.original.length;
960 while (end < 0) end += this.original.length;
961
962 let result = '';
963
964 // find start chunk
965 let chunk = this.firstChunk;
966 while (chunk && (chunk.start > start || chunk.end <= start)) {
967 // found end chunk before start
968 if (chunk.start < end && chunk.end >= end) {
969 return result;
970 }
971
972 chunk = chunk.next;
973 }
974
975 if (chunk && chunk.edited && chunk.start !== start)
976 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
977
978 const startChunk = chunk;
979 while (chunk) {
980 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
981 result += chunk.intro;
982 }
983
984 const containsEnd = chunk.start < end && chunk.end >= end;
985 if (containsEnd && chunk.edited && chunk.end !== end)
986 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
987
988 const sliceStart = startChunk === chunk ? start - chunk.start : 0;
989 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
990
991 result += chunk.content.slice(sliceStart, sliceEnd);
992
993 if (chunk.outro && (!containsEnd || chunk.end === end)) {
994 result += chunk.outro;
995 }
996
997 if (containsEnd) {
998 break;
999 }
1000
1001 chunk = chunk.next;
1002 }
1003
1004 return result;
1005 }
1006
1007 // TODO deprecate this? not really very useful
1008 snip(start, end) {
1009 const clone = this.clone();
1010 clone.remove(0, start);
1011 clone.remove(end, clone.original.length);
1012
1013 return clone;
1014 }
1015
1016 _split(index) {
1017 if (this.byStart[index] || this.byEnd[index]) return;
1018
1019 let chunk = this.lastSearchedChunk;
1020 const searchForward = index > chunk.end;
1021
1022 while (chunk) {
1023 if (chunk.contains(index)) return this._splitChunk(chunk, index);
1024
1025 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1026 }
1027 }
1028
1029 _splitChunk(chunk, index) {
1030 if (chunk.edited && chunk.content.length) {
1031 // zero-length edited chunks are a special case (overlapping replacements)
1032 const loc = getLocator$1(this.original)(index);
1033 throw new Error(
1034 `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
1035 );
1036 }
1037
1038 const newChunk = chunk.split(index);
1039
1040 this.byEnd[index] = chunk;
1041 this.byStart[index] = newChunk;
1042 this.byEnd[newChunk.end] = newChunk;
1043
1044 if (chunk === this.lastChunk) this.lastChunk = newChunk;
1045
1046 this.lastSearchedChunk = chunk;
1047 return true;
1048 }
1049
1050 toString() {
1051 let str = this.intro;
1052
1053 let chunk = this.firstChunk;
1054 while (chunk) {
1055 str += chunk.toString();
1056 chunk = chunk.next;
1057 }
1058
1059 return str + this.outro;
1060 }
1061
1062 isEmpty() {
1063 let chunk = this.firstChunk;
1064 do {
1065 if (
1066 (chunk.intro.length && chunk.intro.trim()) ||
1067 (chunk.content.length && chunk.content.trim()) ||
1068 (chunk.outro.length && chunk.outro.trim())
1069 )
1070 return false;
1071 } while ((chunk = chunk.next));
1072 return true;
1073 }
1074
1075 length() {
1076 let chunk = this.firstChunk;
1077 let length = 0;
1078 do {
1079 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1080 } while ((chunk = chunk.next));
1081 return length;
1082 }
1083
1084 trimLines() {
1085 return this.trim('[\\r\\n]');
1086 }
1087
1088 trim(charType) {
1089 return this.trimStart(charType).trimEnd(charType);
1090 }
1091
1092 trimEndAborted(charType) {
1093 const rx = new RegExp((charType || '\\s') + '+$');
1094
1095 this.outro = this.outro.replace(rx, '');
1096 if (this.outro.length) return true;
1097
1098 let chunk = this.lastChunk;
1099
1100 do {
1101 const end = chunk.end;
1102 const aborted = chunk.trimEnd(rx);
1103
1104 // if chunk was trimmed, we have a new lastChunk
1105 if (chunk.end !== end) {
1106 if (this.lastChunk === chunk) {
1107 this.lastChunk = chunk.next;
1108 }
1109
1110 this.byEnd[chunk.end] = chunk;
1111 this.byStart[chunk.next.start] = chunk.next;
1112 this.byEnd[chunk.next.end] = chunk.next;
1113 }
1114
1115 if (aborted) return true;
1116 chunk = chunk.previous;
1117 } while (chunk);
1118
1119 return false;
1120 }
1121
1122 trimEnd(charType) {
1123 this.trimEndAborted(charType);
1124 return this;
1125 }
1126 trimStartAborted(charType) {
1127 const rx = new RegExp('^' + (charType || '\\s') + '+');
1128
1129 this.intro = this.intro.replace(rx, '');
1130 if (this.intro.length) return true;
1131
1132 let chunk = this.firstChunk;
1133
1134 do {
1135 const end = chunk.end;
1136 const aborted = chunk.trimStart(rx);
1137
1138 if (chunk.end !== end) {
1139 // special case...
1140 if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1141
1142 this.byEnd[chunk.end] = chunk;
1143 this.byStart[chunk.next.start] = chunk.next;
1144 this.byEnd[chunk.next.end] = chunk.next;
1145 }
1146
1147 if (aborted) return true;
1148 chunk = chunk.next;
1149 } while (chunk);
1150
1151 return false;
1152 }
1153
1154 trimStart(charType) {
1155 this.trimStartAborted(charType);
1156 return this;
1157 }
1158
1159 hasChanged() {
1160 return this.original !== this.toString();
1161 }
1162
1163 replace(searchValue, replacement) {
1164 function getReplacement(match, str) {
1165 if (typeof replacement === 'string') {
1166 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1167 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1168 if (i === '$') return '$';
1169 if (i === '&') return match[0];
1170 const num = +i;
1171 if (num < match.length) return match[+i];
1172 return `$${i}`;
1173 });
1174 } else {
1175 return replacement(...match, match.index, str, match.groups);
1176 }
1177 }
1178 function matchAll(re, str) {
1179 let match;
1180 const matches = [];
1181 while ((match = re.exec(str))) {
1182 matches.push(match);
1183 }
1184 return matches;
1185 }
1186 if (typeof searchValue !== 'string' && searchValue.global) {
1187 const matches = matchAll(searchValue, this.original);
1188 matches.forEach((match) => {
1189 if (match.index != null)
1190 this.overwrite(
1191 match.index,
1192 match.index + match[0].length,
1193 getReplacement(match, this.original)
1194 );
1195 });
1196 } else {
1197 const match = this.original.match(searchValue);
1198 if (match && match.index != null)
1199 this.overwrite(
1200 match.index,
1201 match.index + match[0].length,
1202 getReplacement(match, this.original)
1203 );
1204 }
1205 return this;
1206 }
1207}
1208
1209const hasOwnProp = Object.prototype.hasOwnProperty;
1210
1211class Bundle$1 {
1212 constructor(options = {}) {
1213 this.intro = options.intro || '';
1214 this.separator = options.separator !== undefined ? options.separator : '\n';
1215 this.sources = [];
1216 this.uniqueSources = [];
1217 this.uniqueSourceIndexByFilename = {};
1218 }
1219
1220 addSource(source) {
1221 if (source instanceof MagicString) {
1222 return this.addSource({
1223 content: source,
1224 filename: source.filename,
1225 separator: this.separator,
1226 });
1227 }
1228
1229 if (!isObject$1(source) || !source.content) {
1230 throw new Error(
1231 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
1232 );
1233 }
1234
1235 ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
1236 if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
1237 });
1238
1239 if (source.separator === undefined) {
1240 // TODO there's a bunch of this sort of thing, needs cleaning up
1241 source.separator = this.separator;
1242 }
1243
1244 if (source.filename) {
1245 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1246 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1247 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1248 } else {
1249 const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1250 if (source.content.original !== uniqueSource.content) {
1251 throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
1252 }
1253 }
1254 }
1255
1256 this.sources.push(source);
1257 return this;
1258 }
1259
1260 append(str, options) {
1261 this.addSource({
1262 content: new MagicString(str),
1263 separator: (options && options.separator) || '',
1264 });
1265
1266 return this;
1267 }
1268
1269 clone() {
1270 const bundle = new Bundle$1({
1271 intro: this.intro,
1272 separator: this.separator,
1273 });
1274
1275 this.sources.forEach((source) => {
1276 bundle.addSource({
1277 filename: source.filename,
1278 content: source.content.clone(),
1279 separator: source.separator,
1280 });
1281 });
1282
1283 return bundle;
1284 }
1285
1286 generateDecodedMap(options = {}) {
1287 const names = [];
1288 this.sources.forEach((source) => {
1289 Object.keys(source.content.storedNames).forEach((name) => {
1290 if (!~names.indexOf(name)) names.push(name);
1291 });
1292 });
1293
1294 const mappings = new Mappings(options.hires);
1295
1296 if (this.intro) {
1297 mappings.advance(this.intro);
1298 }
1299
1300 this.sources.forEach((source, i) => {
1301 if (i > 0) {
1302 mappings.advance(this.separator);
1303 }
1304
1305 const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
1306 const magicString = source.content;
1307 const locate = getLocator$1(magicString.original);
1308
1309 if (magicString.intro) {
1310 mappings.advance(magicString.intro);
1311 }
1312
1313 magicString.firstChunk.eachNext((chunk) => {
1314 const loc = locate(chunk.start);
1315
1316 if (chunk.intro.length) mappings.advance(chunk.intro);
1317
1318 if (source.filename) {
1319 if (chunk.edited) {
1320 mappings.addEdit(
1321 sourceIndex,
1322 chunk.content,
1323 loc,
1324 chunk.storeName ? names.indexOf(chunk.original) : -1
1325 );
1326 } else {
1327 mappings.addUneditedChunk(
1328 sourceIndex,
1329 chunk,
1330 magicString.original,
1331 loc,
1332 magicString.sourcemapLocations
1333 );
1334 }
1335 } else {
1336 mappings.advance(chunk.content);
1337 }
1338
1339 if (chunk.outro.length) mappings.advance(chunk.outro);
1340 });
1341
1342 if (magicString.outro) {
1343 mappings.advance(magicString.outro);
1344 }
1345 });
1346
1347 return {
1348 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1349 sources: this.uniqueSources.map((source) => {
1350 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1351 }),
1352 sourcesContent: this.uniqueSources.map((source) => {
1353 return options.includeContent ? source.content : null;
1354 }),
1355 names,
1356 mappings: mappings.raw,
1357 };
1358 }
1359
1360 generateMap(options) {
1361 return new SourceMap(this.generateDecodedMap(options));
1362 }
1363
1364 getIndentString() {
1365 const indentStringCounts = {};
1366
1367 this.sources.forEach((source) => {
1368 const indentStr = source.content.indentStr;
1369
1370 if (indentStr === null) return;
1371
1372 if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
1373 indentStringCounts[indentStr] += 1;
1374 });
1375
1376 return (
1377 Object.keys(indentStringCounts).sort((a, b) => {
1378 return indentStringCounts[a] - indentStringCounts[b];
1379 })[0] || '\t'
1380 );
1381 }
1382
1383 indent(indentStr) {
1384 if (!arguments.length) {
1385 indentStr = this.getIndentString();
1386 }
1387
1388 if (indentStr === '') return this; // noop
1389
1390 let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1391
1392 this.sources.forEach((source, i) => {
1393 const separator = source.separator !== undefined ? source.separator : this.separator;
1394 const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1395
1396 source.content.indent(indentStr, {
1397 exclude: source.indentExclusionRanges,
1398 indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1399 });
1400
1401 trailingNewline = source.content.lastChar() === '\n';
1402 });
1403
1404 if (this.intro) {
1405 this.intro =
1406 indentStr +
1407 this.intro.replace(/^[^\n]/gm, (match, index) => {
1408 return index > 0 ? indentStr + match : match;
1409 });
1410 }
1411
1412 return this;
1413 }
1414
1415 prepend(str) {
1416 this.intro = str + this.intro;
1417 return this;
1418 }
1419
1420 toString() {
1421 const body = this.sources
1422 .map((source, i) => {
1423 const separator = source.separator !== undefined ? source.separator : this.separator;
1424 const str = (i > 0 ? separator : '') + source.content.toString();
1425
1426 return str;
1427 })
1428 .join('');
1429
1430 return this.intro + body;
1431 }
1432
1433 isEmpty() {
1434 if (this.intro.length && this.intro.trim()) return false;
1435 if (this.sources.some((source) => !source.content.isEmpty())) return false;
1436 return true;
1437 }
1438
1439 length() {
1440 return this.sources.reduce(
1441 (length, source) => length + source.content.length(),
1442 this.intro.length
1443 );
1444 }
1445
1446 trimLines() {
1447 return this.trim('[\\r\\n]');
1448 }
1449
1450 trim(charType) {
1451 return this.trimStart(charType).trimEnd(charType);
1452 }
1453
1454 trimStart(charType) {
1455 const rx = new RegExp('^' + (charType || '\\s') + '+');
1456 this.intro = this.intro.replace(rx, '');
1457
1458 if (!this.intro) {
1459 let source;
1460 let i = 0;
1461
1462 do {
1463 source = this.sources[i++];
1464 if (!source) {
1465 break;
1466 }
1467 } while (!source.content.trimStartAborted(charType));
1468 }
1469
1470 return this;
1471 }
1472
1473 trimEnd(charType) {
1474 const rx = new RegExp((charType || '\\s') + '+$');
1475
1476 let source;
1477 let i = this.sources.length - 1;
1478
1479 do {
1480 source = this.sources[i--];
1481 if (!source) {
1482 this.intro = this.intro.replace(rx, '');
1483 break;
1484 }
1485 } while (!source.content.trimEndAborted(charType));
1486
1487 return this;
1488 }
1489}
1490
1491const ANY_SLASH_REGEX = /[/\\]/;
1492function relative(from, to) {
1493 const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
1494 const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
1495 if (fromParts[0] === '.')
1496 fromParts.shift();
1497 if (toParts[0] === '.')
1498 toParts.shift();
1499 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1500 fromParts.shift();
1501 toParts.shift();
1502 }
1503 while (toParts[0] === '..' && fromParts.length > 0) {
1504 toParts.shift();
1505 fromParts.pop();
1506 }
1507 while (fromParts.pop()) {
1508 toParts.unshift('..');
1509 }
1510 return toParts.join('/');
1511}
1512
1513function getOrCreate(map, key, init) {
1514 const existing = map.get(key);
1515 if (existing) {
1516 return existing;
1517 }
1518 const value = init();
1519 map.set(key, value);
1520 return value;
1521}
1522
1523const UnknownKey = Symbol('Unknown Key');
1524const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
1525const UnknownInteger = Symbol('Unknown Integer');
1526const EMPTY_PATH = [];
1527const UNKNOWN_PATH = [UnknownKey];
1528// For deoptimizations, this means we are modifying an unknown property but did
1529// not lose track of the object or are creating a setter/getter;
1530// For assignment effects it means we do not check for setter/getter effects
1531// but only if something is mutated that is included, which is relevant for
1532// Object.defineProperty
1533const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
1534const UNKNOWN_INTEGER_PATH = [UnknownInteger];
1535const EntitiesKey = Symbol('Entities');
1536class PathTracker {
1537 constructor() {
1538 this.entityPaths = Object.create(null, {
1539 [EntitiesKey]: { value: new Set() }
1540 });
1541 }
1542 trackEntityAtPathAndGetIfTracked(path, entity) {
1543 const trackedEntities = this.getEntities(path);
1544 if (trackedEntities.has(entity))
1545 return true;
1546 trackedEntities.add(entity);
1547 return false;
1548 }
1549 withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
1550 const trackedEntities = this.getEntities(path);
1551 if (trackedEntities.has(entity))
1552 return returnIfTracked;
1553 trackedEntities.add(entity);
1554 const result = onUntracked();
1555 trackedEntities.delete(entity);
1556 return result;
1557 }
1558 getEntities(path) {
1559 let currentPaths = this.entityPaths;
1560 for (const pathSegment of path) {
1561 currentPaths = currentPaths[pathSegment] =
1562 currentPaths[pathSegment] ||
1563 Object.create(null, { [EntitiesKey]: { value: new Set() } });
1564 }
1565 return currentPaths[EntitiesKey];
1566 }
1567}
1568const SHARED_RECURSION_TRACKER = new PathTracker();
1569class DiscriminatedPathTracker {
1570 constructor() {
1571 this.entityPaths = Object.create(null, {
1572 [EntitiesKey]: { value: new Map() }
1573 });
1574 }
1575 trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
1576 let currentPaths = this.entityPaths;
1577 for (const pathSegment of path) {
1578 currentPaths = currentPaths[pathSegment] =
1579 currentPaths[pathSegment] ||
1580 Object.create(null, { [EntitiesKey]: { value: new Map() } });
1581 }
1582 const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
1583 if (trackedEntities.has(entity))
1584 return true;
1585 trackedEntities.add(entity);
1586 return false;
1587 }
1588}
1589
1590const UnknownValue = Symbol('Unknown Value');
1591const UnknownTruthyValue = Symbol('Unknown Truthy Value');
1592class ExpressionEntity {
1593 constructor() {
1594 this.included = false;
1595 }
1596 deoptimizePath(_path) { }
1597 deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
1598 thisArg.deoptimizePath(UNKNOWN_PATH);
1599 }
1600 /**
1601 * If possible it returns a stringifyable literal value for this node that can be used
1602 * for inlining or comparing values.
1603 * Otherwise it should return UnknownValue.
1604 */
1605 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
1606 return UnknownValue;
1607 }
1608 getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
1609 return UNKNOWN_EXPRESSION;
1610 }
1611 hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
1612 return true;
1613 }
1614 include(_context, _includeChildrenRecursively, _options) {
1615 this.included = true;
1616 }
1617 includeCallArguments(context, args) {
1618 for (const arg of args) {
1619 arg.include(context, false);
1620 }
1621 }
1622 shouldBeIncluded(_context) {
1623 return true;
1624 }
1625}
1626const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
1627})();
1628
1629const INTERACTION_ACCESSED = 0;
1630const INTERACTION_ASSIGNED = 1;
1631const INTERACTION_CALLED = 2;
1632const NODE_INTERACTION_UNKNOWN_ACCESS = {
1633 thisArg: null,
1634 type: INTERACTION_ACCESSED
1635};
1636const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
1637const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
1638 args: UNKNOWN_ARG,
1639 thisArg: null,
1640 type: INTERACTION_ASSIGNED
1641};
1642const NO_ARGS = [];
1643// While this is technically a call without arguments, we can compare against
1644// this reference in places where precise values or thisArg would make a
1645// difference
1646const NODE_INTERACTION_UNKNOWN_CALL = {
1647 args: NO_ARGS,
1648 thisArg: null,
1649 type: INTERACTION_CALLED,
1650 withNew: false
1651};
1652
1653class Variable extends ExpressionEntity {
1654 constructor(name) {
1655 super();
1656 this.name = name;
1657 this.alwaysRendered = false;
1658 this.initReached = false;
1659 this.isId = false;
1660 this.isReassigned = false;
1661 this.kind = null;
1662 this.renderBaseName = null;
1663 this.renderName = null;
1664 }
1665 /**
1666 * Binds identifiers that reference this variable to this variable.
1667 * Necessary to be able to change variable names.
1668 */
1669 addReference(_identifier) { }
1670 getBaseVariableName() {
1671 return this.renderBaseName || this.renderName || this.name;
1672 }
1673 getName(getPropertyAccess) {
1674 const name = this.renderName || this.name;
1675 return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
1676 }
1677 hasEffectsOnInteractionAtPath(path, { type }, _context) {
1678 return type !== INTERACTION_ACCESSED || path.length > 0;
1679 }
1680 /**
1681 * Marks this variable as being part of the bundle, which is usually the case when one of
1682 * its identifiers becomes part of the bundle. Returns true if it has not been included
1683 * previously.
1684 * Once a variable is included, it should take care all its declarations are included.
1685 */
1686 include() {
1687 this.included = true;
1688 }
1689 markCalledFromTryStatement() { }
1690 setRenderNames(baseName, name) {
1691 this.renderBaseName = baseName;
1692 this.renderName = name;
1693 }
1694}
1695
1696class ExternalVariable extends Variable {
1697 constructor(module, name) {
1698 super(name);
1699 this.referenced = false;
1700 this.module = module;
1701 this.isNamespace = name === '*';
1702 }
1703 addReference(identifier) {
1704 this.referenced = true;
1705 if (this.name === 'default' || this.name === '*') {
1706 this.module.suggestName(identifier.name);
1707 }
1708 }
1709 hasEffectsOnInteractionAtPath(path, { type }) {
1710 return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
1711 }
1712 include() {
1713 if (!this.included) {
1714 this.included = true;
1715 this.module.used = true;
1716 }
1717 }
1718}
1719
1720const BLANK = Object.freeze(Object.create(null));
1721const EMPTY_OBJECT = Object.freeze({});
1722const EMPTY_ARRAY = Object.freeze([]);
1723
1724function getLocator(source, options) {
1725 if (options === void 0) { options = {}; }
1726 var offsetLine = options.offsetLine || 0;
1727 var offsetColumn = options.offsetColumn || 0;
1728 var originalLines = source.split('\n');
1729 var start = 0;
1730 var lineRanges = originalLines.map(function (line, i) {
1731 var end = start + line.length + 1;
1732 var range = { start: start, end: end, line: i };
1733 start = end;
1734 return range;
1735 });
1736 var i = 0;
1737 function rangeContains(range, index) {
1738 return range.start <= index && index < range.end;
1739 }
1740 function getLocation(range, index) {
1741 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
1742 }
1743 function locate(search, startIndex) {
1744 if (typeof search === 'string') {
1745 search = source.indexOf(search, startIndex || 0);
1746 }
1747 var range = lineRanges[i];
1748 var d = search >= range.end ? 1 : -1;
1749 while (range) {
1750 if (rangeContains(range, search))
1751 return getLocation(range, search);
1752 i += d;
1753 range = lineRanges[i];
1754 }
1755 }
1756 return locate;
1757}
1758function locate(source, search, options) {
1759 if (typeof options === 'number') {
1760 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
1761 }
1762 return getLocator(source, options)(search, options && options.startIndex);
1763}
1764
1765function spaces(i) {
1766 let result = '';
1767 while (i--)
1768 result += ' ';
1769 return result;
1770}
1771function tabsToSpaces(str) {
1772 return str.replace(/^\t+/, match => match.split('\t').join(' '));
1773}
1774function getCodeFrame(source, line, column) {
1775 let lines = source.split('\n');
1776 const frameStart = Math.max(0, line - 3);
1777 let frameEnd = Math.min(line + 2, lines.length);
1778 lines = lines.slice(frameStart, frameEnd);
1779 while (!/\S/.test(lines[lines.length - 1])) {
1780 lines.pop();
1781 frameEnd -= 1;
1782 }
1783 const digits = String(frameEnd).length;
1784 return lines
1785 .map((str, i) => {
1786 const isErrorLine = frameStart + i + 1 === line;
1787 let lineNum = String(i + frameStart + 1);
1788 while (lineNum.length < digits)
1789 lineNum = ` ${lineNum}`;
1790 if (isErrorLine) {
1791 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
1792 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
1793 }
1794 return `${lineNum}: ${tabsToSpaces(str)}`;
1795 })
1796 .join('\n');
1797}
1798
1799function printQuotedStringList(list, verbs) {
1800 const isSingleItem = list.length <= 1;
1801 const quotedList = list.map(item => `"${item}"`);
1802 let output = isSingleItem
1803 ? quotedList[0]
1804 : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
1805 if (verbs) {
1806 output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
1807 }
1808 return output;
1809}
1810
1811const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
1812const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
1813function isAbsolute(path) {
1814 return ABSOLUTE_PATH_REGEX.test(path);
1815}
1816function isRelative(path) {
1817 return RELATIVE_PATH_REGEX.test(path);
1818}
1819const BACKSLASH_REGEX = /\\/g;
1820function normalize(path) {
1821 return path.replace(BACKSLASH_REGEX, '/');
1822}
1823
1824function getAliasName(id) {
1825 const base = basename(id);
1826 return base.substring(0, base.length - extname(id).length);
1827}
1828function relativeId(id) {
1829 if (!isAbsolute(id))
1830 return id;
1831 return relative(resolve(), id);
1832}
1833function isPathFragment(name) {
1834 // starting with "/", "./", "../", "C:/"
1835 return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
1836}
1837const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
1838function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
1839 let relativePath = normalize(relative(dirname(importerId), targetPath));
1840 if (stripJsExtension && relativePath.endsWith('.js')) {
1841 relativePath = relativePath.slice(0, -3);
1842 }
1843 if (ensureFileName) {
1844 if (relativePath === '')
1845 return '../' + basename(targetPath);
1846 if (UPPER_DIR_REGEX.test(relativePath)) {
1847 return relativePath
1848 .split('/')
1849 .concat(['..', basename(targetPath)])
1850 .join('/');
1851 }
1852 }
1853 return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
1854}
1855
1856function error(base) {
1857 if (!(base instanceof Error))
1858 base = Object.assign(new Error(base.message), base);
1859 throw base;
1860}
1861function augmentCodeLocation(props, pos, source, id) {
1862 if (typeof pos === 'object') {
1863 const { line, column } = pos;
1864 props.loc = { column, file: id, line };
1865 }
1866 else {
1867 props.pos = pos;
1868 const { line, column } = locate(source, pos, { offsetLine: 1 });
1869 props.loc = { column, file: id, line };
1870 }
1871 if (props.frame === undefined) {
1872 const { line, column } = props.loc;
1873 props.frame = getCodeFrame(source, line, column);
1874 }
1875}
1876var Errors;
1877(function (Errors) {
1878 Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
1879 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
1880 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
1881 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
1882 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
1883 Errors["BAD_LOADER"] = "BAD_LOADER";
1884 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
1885 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
1886 Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
1887 Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
1888 Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
1889 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
1890 Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
1891 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
1892 Errors["FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY"] = "FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY";
1893 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
1894 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
1895 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
1896 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
1897 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
1898 Errors["INVALID_OPTION"] = "INVALID_OPTION";
1899 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
1900 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
1901 Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
1902 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
1903 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
1904 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
1905 Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
1906 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
1907 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
1908 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
1909 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
1910 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
1911 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
1912 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
1913 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
1914})(Errors || (Errors = {}));
1915function errAssetNotFinalisedForFileName(name) {
1916 return {
1917 code: Errors.ASSET_NOT_FINALISED,
1918 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
1919 };
1920}
1921function errCannotEmitFromOptionsHook() {
1922 return {
1923 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
1924 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
1925 };
1926}
1927function errChunkNotGeneratedForFileName(name) {
1928 return {
1929 code: Errors.CHUNK_NOT_GENERATED,
1930 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
1931 };
1932}
1933function errChunkInvalid({ fileName, code }, exception) {
1934 const errorProps = {
1935 code: Errors.CHUNK_INVALID,
1936 message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
1937 };
1938 augmentCodeLocation(errorProps, exception.loc, code, fileName);
1939 return errorProps;
1940}
1941function errCircularReexport(exportName, importedModule) {
1942 return {
1943 code: Errors.CIRCULAR_REEXPORT,
1944 id: importedModule,
1945 message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
1946 };
1947}
1948function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
1949 return {
1950 code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
1951 exporter,
1952 importer,
1953 message: `Export "${exportName}" of module ${relativeId(exporter)} was reexported through module ${relativeId(reexporter)} while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in ${relativeId(importer)} to point directly to the exporting module or do not use "preserveModules" to ensure these modules end up in the same chunk.`,
1954 reexporter
1955 };
1956}
1957function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
1958 return {
1959 code: Errors.ASSET_NOT_FOUND,
1960 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
1961 };
1962}
1963function errAssetSourceAlreadySet(name) {
1964 return {
1965 code: Errors.ASSET_SOURCE_ALREADY_SET,
1966 message: `Unable to set the source for asset "${name}", source already set.`
1967 };
1968}
1969function errNoAssetSourceSet(assetName) {
1970 return {
1971 code: Errors.ASSET_SOURCE_MISSING,
1972 message: `Plugin error creating asset "${assetName}" - no asset source set.`
1973 };
1974}
1975function errBadLoader(id) {
1976 return {
1977 code: Errors.BAD_LOADER,
1978 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
1979 };
1980}
1981function errDeprecation(deprecation) {
1982 return {
1983 code: Errors.DEPRECATED_FEATURE,
1984 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
1985 };
1986}
1987function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
1988 return {
1989 code: Errors.FILE_NOT_FOUND,
1990 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
1991 };
1992}
1993function errFileNameConflict(fileName) {
1994 return {
1995 code: Errors.FILE_NAME_CONFLICT,
1996 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
1997 };
1998}
1999function errFileNameOutsideOutputDirectory(fileName) {
2000 return {
2001 code: Errors.FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY,
2002 message: `The output file name "${fileName}" is not contained in the output directory. Make sure all file names are relative paths without ".." segments.`
2003 };
2004}
2005function errInputHookInOutputPlugin(pluginName, hookName) {
2006 return {
2007 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
2008 message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
2009 };
2010}
2011function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
2012 return {
2013 code: Errors.INVALID_CHUNK,
2014 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
2015 };
2016}
2017function errInvalidExportOptionValue(optionValue) {
2018 return {
2019 code: Errors.INVALID_EXPORT_OPTION,
2020 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
2021 url: `https://rollupjs.org/guide/en/#outputexports`
2022 };
2023}
2024function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
2025 return {
2026 code: 'INVALID_EXPORT_OPTION',
2027 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
2028 };
2029}
2030function errInternalIdCannotBeExternal(source, importer) {
2031 return {
2032 code: Errors.INVALID_EXTERNAL_ID,
2033 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
2034 };
2035}
2036function errInvalidOption(option, urlHash, explanation, value) {
2037 return {
2038 code: Errors.INVALID_OPTION,
2039 message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
2040 url: `https://rollupjs.org/guide/en/#${urlHash}`
2041 };
2042}
2043function errInvalidAddonPluginHook(hook, plugin) {
2044 return {
2045 code: Errors.INVALID_PLUGIN_HOOK,
2046 hook,
2047 message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a string, a function hook or an object with a "handler" string or function.`,
2048 plugin
2049 };
2050}
2051function errInvalidFunctionPluginHook(hook, plugin) {
2052 return {
2053 code: Errors.INVALID_PLUGIN_HOOK,
2054 hook,
2055 message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a function hook or an object with a "handler" function.`,
2056 plugin
2057 };
2058}
2059function errInvalidRollupPhaseForAddWatchFile() {
2060 return {
2061 code: Errors.INVALID_ROLLUP_PHASE,
2062 message: `Cannot call addWatchFile after the build has finished.`
2063 };
2064}
2065function errInvalidRollupPhaseForChunkEmission() {
2066 return {
2067 code: Errors.INVALID_ROLLUP_PHASE,
2068 message: `Cannot emit chunks after module loading has finished.`
2069 };
2070}
2071function errMissingExport(exportName, importingModule, importedModule) {
2072 return {
2073 code: Errors.MISSING_EXPORT,
2074 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
2075 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
2076 };
2077}
2078function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
2079 return {
2080 code: Errors.MISSING_IMPLICIT_DEPENDANT,
2081 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
2082 };
2083}
2084function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
2085 return {
2086 code: Errors.MISSING_IMPLICIT_DEPENDANT,
2087 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
2088 };
2089}
2090function errImplicitDependantIsNotIncluded(module) {
2091 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
2092 return {
2093 code: Errors.MISSING_IMPLICIT_DEPENDANT,
2094 message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
2095 };
2096}
2097function errMixedExport(facadeModuleId, name) {
2098 return {
2099 code: Errors.MIXED_EXPORTS,
2100 id: facadeModuleId,
2101 message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}["default"]\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning`,
2102 url: `https://rollupjs.org/guide/en/#outputexports`
2103 };
2104}
2105function errNamespaceConflict(name, reexportingModuleId, sources) {
2106 return {
2107 code: Errors.NAMESPACE_CONFLICT,
2108 message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
2109 name,
2110 reexporter: reexportingModuleId,
2111 sources
2112 };
2113}
2114function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
2115 return {
2116 code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
2117 message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
2118 name,
2119 reexporter: reexportingModule,
2120 sources
2121 };
2122}
2123function errNoTransformMapOrAstWithoutCode(pluginName) {
2124 return {
2125 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
2126 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
2127 'a "code". This will be ignored.'
2128 };
2129}
2130function errPreferNamedExports(facadeModuleId) {
2131 const file = relativeId(facadeModuleId);
2132 return {
2133 code: Errors.PREFER_NAMED_EXPORTS,
2134 id: facadeModuleId,
2135 message: `Entry module "${file}" is implicitly using "default" export mode, which means for CommonJS output that its default export is assigned to "module.exports". For many tools, such CommonJS output will not be interchangeable with the original ES module. If this is intended, explicitly set "output.exports" to either "auto" or "default", otherwise you might want to consider changing the signature of "${file}" to use named exports only.`,
2136 url: `https://rollupjs.org/guide/en/#outputexports`
2137 };
2138}
2139function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
2140 return {
2141 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
2142 id,
2143 message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
2144 ? `an explicit export named "${syntheticNamedExportsOption}"`
2145 : 'a default export'} that does not reexport an unresolved named export of the same module.`
2146 };
2147}
2148function errUnexpectedNamedImport(id, imported, isReexport) {
2149 const importType = isReexport ? 'reexport' : 'import';
2150 return {
2151 code: Errors.UNEXPECTED_NAMED_IMPORT,
2152 id,
2153 message: `The named export "${imported}" was ${importType}ed from the external module ${relativeId(id)} even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
2154 url: 'https://rollupjs.org/guide/en/#outputinterop'
2155 };
2156}
2157function errUnexpectedNamespaceReexport(id) {
2158 return {
2159 code: Errors.UNEXPECTED_NAMED_IMPORT,
2160 id,
2161 message: `There was a namespace "*" reexport from the external module ${relativeId(id)} even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
2162 url: 'https://rollupjs.org/guide/en/#outputinterop'
2163 };
2164}
2165function errEntryCannotBeExternal(unresolvedId) {
2166 return {
2167 code: Errors.UNRESOLVED_ENTRY,
2168 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
2169 };
2170}
2171function errUnresolvedEntry(unresolvedId) {
2172 return {
2173 code: Errors.UNRESOLVED_ENTRY,
2174 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
2175 };
2176}
2177function errUnresolvedImport(source, importer) {
2178 return {
2179 code: Errors.UNRESOLVED_IMPORT,
2180 message: `Could not resolve '${source}' from ${relativeId(importer)}`
2181 };
2182}
2183function errUnresolvedImportTreatedAsExternal(source, importer) {
2184 return {
2185 code: Errors.UNRESOLVED_IMPORT,
2186 importer: relativeId(importer),
2187 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
2188 source,
2189 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
2190 };
2191}
2192function errExternalSyntheticExports(source, importer) {
2193 return {
2194 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
2195 importer: relativeId(importer),
2196 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
2197 source
2198 };
2199}
2200function errFailedValidation(message) {
2201 return {
2202 code: Errors.VALIDATION_ERROR,
2203 message
2204 };
2205}
2206function errAlreadyClosed() {
2207 return {
2208 code: Errors.ALREADY_CLOSED,
2209 message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
2210 };
2211}
2212function warnDeprecation(deprecation, activeDeprecation, options) {
2213 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
2214}
2215function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
2216 if (activeDeprecation || strictDeprecations) {
2217 const warning = errDeprecation(deprecation);
2218 if (strictDeprecations) {
2219 return error(warning);
2220 }
2221 warn(warning);
2222 }
2223}
2224
2225const RESERVED_NAMES = new Set([
2226 'await',
2227 'break',
2228 'case',
2229 'catch',
2230 'class',
2231 'const',
2232 'continue',
2233 'debugger',
2234 'default',
2235 'delete',
2236 'do',
2237 'else',
2238 'enum',
2239 'eval',
2240 'export',
2241 'extends',
2242 'false',
2243 'finally',
2244 'for',
2245 'function',
2246 'if',
2247 'implements',
2248 'import',
2249 'in',
2250 'instanceof',
2251 'interface',
2252 'let',
2253 'NaN',
2254 'new',
2255 'null',
2256 'package',
2257 'private',
2258 'protected',
2259 'public',
2260 'return',
2261 'static',
2262 'super',
2263 'switch',
2264 'this',
2265 'throw',
2266 'true',
2267 'try',
2268 'typeof',
2269 'undefined',
2270 'var',
2271 'void',
2272 'while',
2273 'with',
2274 'yield'
2275]);
2276const RESERVED_NAMES$1 = RESERVED_NAMES;
2277
2278const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2279const startsWithDigit = (str) => /\d/.test(str[0]);
2280const needsEscape = (str) => startsWithDigit(str) || RESERVED_NAMES$1.has(str) || str === 'arguments';
2281function isLegal(str) {
2282 if (needsEscape(str)) {
2283 return false;
2284 }
2285 return !illegalCharacters.test(str);
2286}
2287function makeLegal(str) {
2288 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2289 if (needsEscape(str))
2290 str = `_${str}`;
2291 return str || '_';
2292}
2293
2294class ExternalModule {
2295 constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
2296 this.options = options;
2297 this.id = id;
2298 this.renormalizeRenderPath = renormalizeRenderPath;
2299 this.declarations = new Map();
2300 this.defaultVariableName = '';
2301 this.dynamicImporters = [];
2302 this.execIndex = Infinity;
2303 this.exportedVariables = new Map();
2304 this.importers = [];
2305 this.mostCommonSuggestion = 0;
2306 this.nameSuggestions = new Map();
2307 this.namespaceVariableName = '';
2308 this.reexported = false;
2309 this.renderPath = undefined;
2310 this.used = false;
2311 this.variableName = '';
2312 this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2313 const { importers, dynamicImporters } = this;
2314 const info = (this.info = {
2315 ast: null,
2316 code: null,
2317 dynamicallyImportedIdResolutions: EMPTY_ARRAY,
2318 dynamicallyImportedIds: EMPTY_ARRAY,
2319 get dynamicImporters() {
2320 return dynamicImporters.sort();
2321 },
2322 hasDefaultExport: null,
2323 get hasModuleSideEffects() {
2324 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
2325 return info.moduleSideEffects;
2326 },
2327 id,
2328 implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
2329 implicitlyLoadedBefore: EMPTY_ARRAY,
2330 importedIdResolutions: EMPTY_ARRAY,
2331 importedIds: EMPTY_ARRAY,
2332 get importers() {
2333 return importers.sort();
2334 },
2335 isEntry: false,
2336 isExternal: true,
2337 isIncluded: null,
2338 meta,
2339 moduleSideEffects,
2340 syntheticNamedExports: false
2341 });
2342 // Hide the deprecated key so that it only warns when accessed explicitly
2343 Object.defineProperty(this.info, 'hasModuleSideEffects', {
2344 enumerable: false
2345 });
2346 }
2347 getVariableForExportName(name) {
2348 const declaration = this.declarations.get(name);
2349 if (declaration)
2350 return [declaration];
2351 const externalVariable = new ExternalVariable(this, name);
2352 this.declarations.set(name, externalVariable);
2353 this.exportedVariables.set(externalVariable, name);
2354 return [externalVariable];
2355 }
2356 setRenderPath(options, inputBase) {
2357 this.renderPath =
2358 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2359 if (!this.renderPath) {
2360 this.renderPath = this.renormalizeRenderPath
2361 ? normalize(relative$1(inputBase, this.id))
2362 : this.id;
2363 }
2364 }
2365 suggestName(name) {
2366 var _a;
2367 const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
2368 this.nameSuggestions.set(name, value);
2369 if (value > this.mostCommonSuggestion) {
2370 this.mostCommonSuggestion = value;
2371 this.suggestedVariableName = name;
2372 }
2373 }
2374 warnUnusedImports() {
2375 const unused = Array.from(this.declarations)
2376 .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
2377 .map(([name]) => name);
2378 if (unused.length === 0)
2379 return;
2380 const importersSet = new Set();
2381 for (const name of unused) {
2382 for (const importer of this.declarations.get(name).module.importers) {
2383 importersSet.add(importer);
2384 }
2385 }
2386 const importersArray = [...importersSet];
2387 this.options.onwarn({
2388 code: 'UNUSED_EXTERNAL_IMPORT',
2389 message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
2390 names: unused,
2391 source: this.id,
2392 sources: importersArray
2393 });
2394 }
2395}
2396
2397function getDefaultExportFromCjs (x) {
2398 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2399}
2400
2401function getAugmentedNamespace(n) {
2402 var f = n.default;
2403 if (typeof f == "function") {
2404 var a = function () {
2405 return f.apply(this, arguments);
2406 };
2407 a.prototype = f.prototype;
2408 } else a = {};
2409 Object.defineProperty(a, '__esModule', {value: true});
2410 Object.keys(n).forEach(function (k) {
2411 var d = Object.getOwnPropertyDescriptor(n, k);
2412 Object.defineProperty(a, k, d.get ? d : {
2413 enumerable: true,
2414 get: function () {
2415 return n[k];
2416 }
2417 });
2418 });
2419 return a;
2420}
2421
2422var picomatch$1 = {exports: {}};
2423
2424var utils$3 = {};
2425
2426const path$1 = require$$0;
2427const WIN_SLASH = '\\\\/';
2428const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2429
2430/**
2431 * Posix glob regex
2432 */
2433
2434const DOT_LITERAL = '\\.';
2435const PLUS_LITERAL = '\\+';
2436const QMARK_LITERAL = '\\?';
2437const SLASH_LITERAL = '\\/';
2438const ONE_CHAR = '(?=.)';
2439const QMARK = '[^/]';
2440const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
2441const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
2442const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
2443const NO_DOT = `(?!${DOT_LITERAL})`;
2444const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
2445const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
2446const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
2447const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
2448const STAR = `${QMARK}*?`;
2449
2450const POSIX_CHARS = {
2451 DOT_LITERAL,
2452 PLUS_LITERAL,
2453 QMARK_LITERAL,
2454 SLASH_LITERAL,
2455 ONE_CHAR,
2456 QMARK,
2457 END_ANCHOR,
2458 DOTS_SLASH,
2459 NO_DOT,
2460 NO_DOTS,
2461 NO_DOT_SLASH,
2462 NO_DOTS_SLASH,
2463 QMARK_NO_DOT,
2464 STAR,
2465 START_ANCHOR
2466};
2467
2468/**
2469 * Windows glob regex
2470 */
2471
2472const WINDOWS_CHARS = {
2473 ...POSIX_CHARS,
2474
2475 SLASH_LITERAL: `[${WIN_SLASH}]`,
2476 QMARK: WIN_NO_SLASH,
2477 STAR: `${WIN_NO_SLASH}*?`,
2478 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
2479 NO_DOT: `(?!${DOT_LITERAL})`,
2480 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2481 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
2482 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2483 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
2484 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
2485 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
2486};
2487
2488/**
2489 * POSIX Bracket Regex
2490 */
2491
2492const POSIX_REGEX_SOURCE$1 = {
2493 alnum: 'a-zA-Z0-9',
2494 alpha: 'a-zA-Z',
2495 ascii: '\\x00-\\x7F',
2496 blank: ' \\t',
2497 cntrl: '\\x00-\\x1F\\x7F',
2498 digit: '0-9',
2499 graph: '\\x21-\\x7E',
2500 lower: 'a-z',
2501 print: '\\x20-\\x7E ',
2502 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
2503 space: ' \\t\\r\\n\\v\\f',
2504 upper: 'A-Z',
2505 word: 'A-Za-z0-9_',
2506 xdigit: 'A-Fa-f0-9'
2507};
2508
2509var constants$2 = {
2510 MAX_LENGTH: 1024 * 64,
2511 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
2512
2513 // regular expressions
2514 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
2515 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
2516 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
2517 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
2518 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
2519 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2520
2521 // Replace globs with equivalent patterns to reduce parsing time.
2522 REPLACEMENTS: {
2523 '***': '*',
2524 '**/**': '**',
2525 '**/**/**': '**'
2526 },
2527
2528 // Digits
2529 CHAR_0: 48, /* 0 */
2530 CHAR_9: 57, /* 9 */
2531
2532 // Alphabet chars.
2533 CHAR_UPPERCASE_A: 65, /* A */
2534 CHAR_LOWERCASE_A: 97, /* a */
2535 CHAR_UPPERCASE_Z: 90, /* Z */
2536 CHAR_LOWERCASE_Z: 122, /* z */
2537
2538 CHAR_LEFT_PARENTHESES: 40, /* ( */
2539 CHAR_RIGHT_PARENTHESES: 41, /* ) */
2540
2541 CHAR_ASTERISK: 42, /* * */
2542
2543 // Non-alphabetic chars.
2544 CHAR_AMPERSAND: 38, /* & */
2545 CHAR_AT: 64, /* @ */
2546 CHAR_BACKWARD_SLASH: 92, /* \ */
2547 CHAR_CARRIAGE_RETURN: 13, /* \r */
2548 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
2549 CHAR_COLON: 58, /* : */
2550 CHAR_COMMA: 44, /* , */
2551 CHAR_DOT: 46, /* . */
2552 CHAR_DOUBLE_QUOTE: 34, /* " */
2553 CHAR_EQUAL: 61, /* = */
2554 CHAR_EXCLAMATION_MARK: 33, /* ! */
2555 CHAR_FORM_FEED: 12, /* \f */
2556 CHAR_FORWARD_SLASH: 47, /* / */
2557 CHAR_GRAVE_ACCENT: 96, /* ` */
2558 CHAR_HASH: 35, /* # */
2559 CHAR_HYPHEN_MINUS: 45, /* - */
2560 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
2561 CHAR_LEFT_CURLY_BRACE: 123, /* { */
2562 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
2563 CHAR_LINE_FEED: 10, /* \n */
2564 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
2565 CHAR_PERCENT: 37, /* % */
2566 CHAR_PLUS: 43, /* + */
2567 CHAR_QUESTION_MARK: 63, /* ? */
2568 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
2569 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
2570 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
2571 CHAR_SEMICOLON: 59, /* ; */
2572 CHAR_SINGLE_QUOTE: 39, /* ' */
2573 CHAR_SPACE: 32, /* */
2574 CHAR_TAB: 9, /* \t */
2575 CHAR_UNDERSCORE: 95, /* _ */
2576 CHAR_VERTICAL_LINE: 124, /* | */
2577 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
2578
2579 SEP: path$1.sep,
2580
2581 /**
2582 * Create EXTGLOB_CHARS
2583 */
2584
2585 extglobChars(chars) {
2586 return {
2587 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
2588 '?': { type: 'qmark', open: '(?:', close: ')?' },
2589 '+': { type: 'plus', open: '(?:', close: ')+' },
2590 '*': { type: 'star', open: '(?:', close: ')*' },
2591 '@': { type: 'at', open: '(?:', close: ')' }
2592 };
2593 },
2594
2595 /**
2596 * Create GLOB_CHARS
2597 */
2598
2599 globChars(win32) {
2600 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
2601 }
2602};
2603
2604(function (exports) {
2605
2606 const path = require$$0;
2607 const win32 = process.platform === 'win32';
2608 const {
2609 REGEX_BACKSLASH,
2610 REGEX_REMOVE_BACKSLASH,
2611 REGEX_SPECIAL_CHARS,
2612 REGEX_SPECIAL_CHARS_GLOBAL
2613 } = constants$2;
2614
2615 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
2616 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
2617 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
2618 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
2619 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
2620
2621 exports.removeBackslashes = str => {
2622 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
2623 return match === '\\' ? '' : match;
2624 });
2625 };
2626
2627 exports.supportsLookbehinds = () => {
2628 const segs = process.version.slice(1).split('.').map(Number);
2629 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
2630 return true;
2631 }
2632 return false;
2633 };
2634
2635 exports.isWindows = options => {
2636 if (options && typeof options.windows === 'boolean') {
2637 return options.windows;
2638 }
2639 return win32 === true || path.sep === '\\';
2640 };
2641
2642 exports.escapeLast = (input, char, lastIdx) => {
2643 const idx = input.lastIndexOf(char, lastIdx);
2644 if (idx === -1) return input;
2645 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
2646 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
2647 };
2648
2649 exports.removePrefix = (input, state = {}) => {
2650 let output = input;
2651 if (output.startsWith('./')) {
2652 output = output.slice(2);
2653 state.prefix = './';
2654 }
2655 return output;
2656 };
2657
2658 exports.wrapOutput = (input, state = {}, options = {}) => {
2659 const prepend = options.contains ? '' : '^';
2660 const append = options.contains ? '' : '$';
2661
2662 let output = `${prepend}(?:${input})${append}`;
2663 if (state.negated === true) {
2664 output = `(?:^(?!${output}).*$)`;
2665 }
2666 return output;
2667 };
2668} (utils$3));
2669
2670const utils$2 = utils$3;
2671const {
2672 CHAR_ASTERISK, /* * */
2673 CHAR_AT, /* @ */
2674 CHAR_BACKWARD_SLASH, /* \ */
2675 CHAR_COMMA, /* , */
2676 CHAR_DOT, /* . */
2677 CHAR_EXCLAMATION_MARK, /* ! */
2678 CHAR_FORWARD_SLASH, /* / */
2679 CHAR_LEFT_CURLY_BRACE, /* { */
2680 CHAR_LEFT_PARENTHESES, /* ( */
2681 CHAR_LEFT_SQUARE_BRACKET, /* [ */
2682 CHAR_PLUS, /* + */
2683 CHAR_QUESTION_MARK, /* ? */
2684 CHAR_RIGHT_CURLY_BRACE, /* } */
2685 CHAR_RIGHT_PARENTHESES, /* ) */
2686 CHAR_RIGHT_SQUARE_BRACKET /* ] */
2687} = constants$2;
2688
2689const isPathSeparator = code => {
2690 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
2691};
2692
2693const depth = token => {
2694 if (token.isPrefix !== true) {
2695 token.depth = token.isGlobstar ? Infinity : 1;
2696 }
2697};
2698
2699/**
2700 * Quickly scans a glob pattern and returns an object with a handful of
2701 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
2702 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
2703 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
2704 *
2705 * ```js
2706 * const pm = require('picomatch');
2707 * console.log(pm.scan('foo/bar/*.js'));
2708 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
2709 * ```
2710 * @param {String} `str`
2711 * @param {Object} `options`
2712 * @return {Object} Returns an object with tokens and regex source string.
2713 * @api public
2714 */
2715
2716const scan$1 = (input, options) => {
2717 const opts = options || {};
2718
2719 const length = input.length - 1;
2720 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
2721 const slashes = [];
2722 const tokens = [];
2723 const parts = [];
2724
2725 let str = input;
2726 let index = -1;
2727 let start = 0;
2728 let lastIndex = 0;
2729 let isBrace = false;
2730 let isBracket = false;
2731 let isGlob = false;
2732 let isExtglob = false;
2733 let isGlobstar = false;
2734 let braceEscaped = false;
2735 let backslashes = false;
2736 let negated = false;
2737 let negatedExtglob = false;
2738 let finished = false;
2739 let braces = 0;
2740 let prev;
2741 let code;
2742 let token = { value: '', depth: 0, isGlob: false };
2743
2744 const eos = () => index >= length;
2745 const peek = () => str.charCodeAt(index + 1);
2746 const advance = () => {
2747 prev = code;
2748 return str.charCodeAt(++index);
2749 };
2750
2751 while (index < length) {
2752 code = advance();
2753 let next;
2754
2755 if (code === CHAR_BACKWARD_SLASH) {
2756 backslashes = token.backslashes = true;
2757 code = advance();
2758
2759 if (code === CHAR_LEFT_CURLY_BRACE) {
2760 braceEscaped = true;
2761 }
2762 continue;
2763 }
2764
2765 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
2766 braces++;
2767
2768 while (eos() !== true && (code = advance())) {
2769 if (code === CHAR_BACKWARD_SLASH) {
2770 backslashes = token.backslashes = true;
2771 advance();
2772 continue;
2773 }
2774
2775 if (code === CHAR_LEFT_CURLY_BRACE) {
2776 braces++;
2777 continue;
2778 }
2779
2780 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
2781 isBrace = token.isBrace = true;
2782 isGlob = token.isGlob = true;
2783 finished = true;
2784
2785 if (scanToEnd === true) {
2786 continue;
2787 }
2788
2789 break;
2790 }
2791
2792 if (braceEscaped !== true && code === CHAR_COMMA) {
2793 isBrace = token.isBrace = true;
2794 isGlob = token.isGlob = true;
2795 finished = true;
2796
2797 if (scanToEnd === true) {
2798 continue;
2799 }
2800
2801 break;
2802 }
2803
2804 if (code === CHAR_RIGHT_CURLY_BRACE) {
2805 braces--;
2806
2807 if (braces === 0) {
2808 braceEscaped = false;
2809 isBrace = token.isBrace = true;
2810 finished = true;
2811 break;
2812 }
2813 }
2814 }
2815
2816 if (scanToEnd === true) {
2817 continue;
2818 }
2819
2820 break;
2821 }
2822
2823 if (code === CHAR_FORWARD_SLASH) {
2824 slashes.push(index);
2825 tokens.push(token);
2826 token = { value: '', depth: 0, isGlob: false };
2827
2828 if (finished === true) continue;
2829 if (prev === CHAR_DOT && index === (start + 1)) {
2830 start += 2;
2831 continue;
2832 }
2833
2834 lastIndex = index + 1;
2835 continue;
2836 }
2837
2838 if (opts.noext !== true) {
2839 const isExtglobChar = code === CHAR_PLUS
2840 || code === CHAR_AT
2841 || code === CHAR_ASTERISK
2842 || code === CHAR_QUESTION_MARK
2843 || code === CHAR_EXCLAMATION_MARK;
2844
2845 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
2846 isGlob = token.isGlob = true;
2847 isExtglob = token.isExtglob = true;
2848 finished = true;
2849 if (code === CHAR_EXCLAMATION_MARK && index === start) {
2850 negatedExtglob = true;
2851 }
2852
2853 if (scanToEnd === true) {
2854 while (eos() !== true && (code = advance())) {
2855 if (code === CHAR_BACKWARD_SLASH) {
2856 backslashes = token.backslashes = true;
2857 code = advance();
2858 continue;
2859 }
2860
2861 if (code === CHAR_RIGHT_PARENTHESES) {
2862 isGlob = token.isGlob = true;
2863 finished = true;
2864 break;
2865 }
2866 }
2867 continue;
2868 }
2869 break;
2870 }
2871 }
2872
2873 if (code === CHAR_ASTERISK) {
2874 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
2875 isGlob = token.isGlob = true;
2876 finished = true;
2877
2878 if (scanToEnd === true) {
2879 continue;
2880 }
2881 break;
2882 }
2883
2884 if (code === CHAR_QUESTION_MARK) {
2885 isGlob = token.isGlob = true;
2886 finished = true;
2887
2888 if (scanToEnd === true) {
2889 continue;
2890 }
2891 break;
2892 }
2893
2894 if (code === CHAR_LEFT_SQUARE_BRACKET) {
2895 while (eos() !== true && (next = advance())) {
2896 if (next === CHAR_BACKWARD_SLASH) {
2897 backslashes = token.backslashes = true;
2898 advance();
2899 continue;
2900 }
2901
2902 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
2903 isBracket = token.isBracket = true;
2904 isGlob = token.isGlob = true;
2905 finished = true;
2906 break;
2907 }
2908 }
2909
2910 if (scanToEnd === true) {
2911 continue;
2912 }
2913
2914 break;
2915 }
2916
2917 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
2918 negated = token.negated = true;
2919 start++;
2920 continue;
2921 }
2922
2923 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
2924 isGlob = token.isGlob = true;
2925
2926 if (scanToEnd === true) {
2927 while (eos() !== true && (code = advance())) {
2928 if (code === CHAR_LEFT_PARENTHESES) {
2929 backslashes = token.backslashes = true;
2930 code = advance();
2931 continue;
2932 }
2933
2934 if (code === CHAR_RIGHT_PARENTHESES) {
2935 finished = true;
2936 break;
2937 }
2938 }
2939 continue;
2940 }
2941 break;
2942 }
2943
2944 if (isGlob === true) {
2945 finished = true;
2946
2947 if (scanToEnd === true) {
2948 continue;
2949 }
2950
2951 break;
2952 }
2953 }
2954
2955 if (opts.noext === true) {
2956 isExtglob = false;
2957 isGlob = false;
2958 }
2959
2960 let base = str;
2961 let prefix = '';
2962 let glob = '';
2963
2964 if (start > 0) {
2965 prefix = str.slice(0, start);
2966 str = str.slice(start);
2967 lastIndex -= start;
2968 }
2969
2970 if (base && isGlob === true && lastIndex > 0) {
2971 base = str.slice(0, lastIndex);
2972 glob = str.slice(lastIndex);
2973 } else if (isGlob === true) {
2974 base = '';
2975 glob = str;
2976 } else {
2977 base = str;
2978 }
2979
2980 if (base && base !== '' && base !== '/' && base !== str) {
2981 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
2982 base = base.slice(0, -1);
2983 }
2984 }
2985
2986 if (opts.unescape === true) {
2987 if (glob) glob = utils$2.removeBackslashes(glob);
2988
2989 if (base && backslashes === true) {
2990 base = utils$2.removeBackslashes(base);
2991 }
2992 }
2993
2994 const state = {
2995 prefix,
2996 input,
2997 start,
2998 base,
2999 glob,
3000 isBrace,
3001 isBracket,
3002 isGlob,
3003 isExtglob,
3004 isGlobstar,
3005 negated,
3006 negatedExtglob
3007 };
3008
3009 if (opts.tokens === true) {
3010 state.maxDepth = 0;
3011 if (!isPathSeparator(code)) {
3012 tokens.push(token);
3013 }
3014 state.tokens = tokens;
3015 }
3016
3017 if (opts.parts === true || opts.tokens === true) {
3018 let prevIndex;
3019
3020 for (let idx = 0; idx < slashes.length; idx++) {
3021 const n = prevIndex ? prevIndex + 1 : start;
3022 const i = slashes[idx];
3023 const value = input.slice(n, i);
3024 if (opts.tokens) {
3025 if (idx === 0 && start !== 0) {
3026 tokens[idx].isPrefix = true;
3027 tokens[idx].value = prefix;
3028 } else {
3029 tokens[idx].value = value;
3030 }
3031 depth(tokens[idx]);
3032 state.maxDepth += tokens[idx].depth;
3033 }
3034 if (idx !== 0 || value !== '') {
3035 parts.push(value);
3036 }
3037 prevIndex = i;
3038 }
3039
3040 if (prevIndex && prevIndex + 1 < input.length) {
3041 const value = input.slice(prevIndex + 1);
3042 parts.push(value);
3043
3044 if (opts.tokens) {
3045 tokens[tokens.length - 1].value = value;
3046 depth(tokens[tokens.length - 1]);
3047 state.maxDepth += tokens[tokens.length - 1].depth;
3048 }
3049 }
3050
3051 state.slashes = slashes;
3052 state.parts = parts;
3053 }
3054
3055 return state;
3056};
3057
3058var scan_1 = scan$1;
3059
3060const constants$1 = constants$2;
3061const utils$1 = utils$3;
3062
3063/**
3064 * Constants
3065 */
3066
3067const {
3068 MAX_LENGTH,
3069 POSIX_REGEX_SOURCE,
3070 REGEX_NON_SPECIAL_CHARS,
3071 REGEX_SPECIAL_CHARS_BACKREF,
3072 REPLACEMENTS
3073} = constants$1;
3074
3075/**
3076 * Helpers
3077 */
3078
3079const expandRange = (args, options) => {
3080 if (typeof options.expandRange === 'function') {
3081 return options.expandRange(...args, options);
3082 }
3083
3084 args.sort();
3085 const value = `[${args.join('-')}]`;
3086
3087 return value;
3088};
3089
3090/**
3091 * Create the message for a syntax error
3092 */
3093
3094const syntaxError = (type, char) => {
3095 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
3096};
3097
3098/**
3099 * Parse the given input string.
3100 * @param {String} input
3101 * @param {Object} options
3102 * @return {Object}
3103 */
3104
3105const parse$1 = (input, options) => {
3106 if (typeof input !== 'string') {
3107 throw new TypeError('Expected a string');
3108 }
3109
3110 input = REPLACEMENTS[input] || input;
3111
3112 const opts = { ...options };
3113 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
3114
3115 let len = input.length;
3116 if (len > max) {
3117 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
3118 }
3119
3120 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
3121 const tokens = [bos];
3122
3123 const capture = opts.capture ? '' : '?:';
3124 const win32 = utils$1.isWindows(options);
3125
3126 // create constants based on platform, for windows or posix
3127 const PLATFORM_CHARS = constants$1.globChars(win32);
3128 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
3129
3130 const {
3131 DOT_LITERAL,
3132 PLUS_LITERAL,
3133 SLASH_LITERAL,
3134 ONE_CHAR,
3135 DOTS_SLASH,
3136 NO_DOT,
3137 NO_DOT_SLASH,
3138 NO_DOTS_SLASH,
3139 QMARK,
3140 QMARK_NO_DOT,
3141 STAR,
3142 START_ANCHOR
3143 } = PLATFORM_CHARS;
3144
3145 const globstar = opts => {
3146 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
3147 };
3148
3149 const nodot = opts.dot ? '' : NO_DOT;
3150 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
3151 let star = opts.bash === true ? globstar(opts) : STAR;
3152
3153 if (opts.capture) {
3154 star = `(${star})`;
3155 }
3156
3157 // minimatch options support
3158 if (typeof opts.noext === 'boolean') {
3159 opts.noextglob = opts.noext;
3160 }
3161
3162 const state = {
3163 input,
3164 index: -1,
3165 start: 0,
3166 dot: opts.dot === true,
3167 consumed: '',
3168 output: '',
3169 prefix: '',
3170 backtrack: false,
3171 negated: false,
3172 brackets: 0,
3173 braces: 0,
3174 parens: 0,
3175 quotes: 0,
3176 globstar: false,
3177 tokens
3178 };
3179
3180 input = utils$1.removePrefix(input, state);
3181 len = input.length;
3182
3183 const extglobs = [];
3184 const braces = [];
3185 const stack = [];
3186 let prev = bos;
3187 let value;
3188
3189 /**
3190 * Tokenizing helpers
3191 */
3192
3193 const eos = () => state.index === len - 1;
3194 const peek = state.peek = (n = 1) => input[state.index + n];
3195 const advance = state.advance = () => input[++state.index] || '';
3196 const remaining = () => input.slice(state.index + 1);
3197 const consume = (value = '', num = 0) => {
3198 state.consumed += value;
3199 state.index += num;
3200 };
3201
3202 const append = token => {
3203 state.output += token.output != null ? token.output : token.value;
3204 consume(token.value);
3205 };
3206
3207 const negate = () => {
3208 let count = 1;
3209
3210 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
3211 advance();
3212 state.start++;
3213 count++;
3214 }
3215
3216 if (count % 2 === 0) {
3217 return false;
3218 }
3219
3220 state.negated = true;
3221 state.start++;
3222 return true;
3223 };
3224
3225 const increment = type => {
3226 state[type]++;
3227 stack.push(type);
3228 };
3229
3230 const decrement = type => {
3231 state[type]--;
3232 stack.pop();
3233 };
3234
3235 /**
3236 * Push tokens onto the tokens array. This helper speeds up
3237 * tokenizing by 1) helping us avoid backtracking as much as possible,
3238 * and 2) helping us avoid creating extra tokens when consecutive
3239 * characters are plain text. This improves performance and simplifies
3240 * lookbehinds.
3241 */
3242
3243 const push = tok => {
3244 if (prev.type === 'globstar') {
3245 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
3246 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
3247
3248 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
3249 state.output = state.output.slice(0, -prev.output.length);
3250 prev.type = 'star';
3251 prev.value = '*';
3252 prev.output = star;
3253 state.output += prev.output;
3254 }
3255 }
3256
3257 if (extglobs.length && tok.type !== 'paren') {
3258 extglobs[extglobs.length - 1].inner += tok.value;
3259 }
3260
3261 if (tok.value || tok.output) append(tok);
3262 if (prev && prev.type === 'text' && tok.type === 'text') {
3263 prev.value += tok.value;
3264 prev.output = (prev.output || '') + tok.value;
3265 return;
3266 }
3267
3268 tok.prev = prev;
3269 tokens.push(tok);
3270 prev = tok;
3271 };
3272
3273 const extglobOpen = (type, value) => {
3274 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
3275
3276 token.prev = prev;
3277 token.parens = state.parens;
3278 token.output = state.output;
3279 const output = (opts.capture ? '(' : '') + token.open;
3280
3281 increment('parens');
3282 push({ type, value, output: state.output ? '' : ONE_CHAR });
3283 push({ type: 'paren', extglob: true, value: advance(), output });
3284 extglobs.push(token);
3285 };
3286
3287 const extglobClose = token => {
3288 let output = token.close + (opts.capture ? ')' : '');
3289 let rest;
3290
3291 if (token.type === 'negate') {
3292 let extglobStar = star;
3293
3294 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
3295 extglobStar = globstar(opts);
3296 }
3297
3298 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
3299 output = token.close = `)$))${extglobStar}`;
3300 }
3301
3302 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
3303 // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
3304 // In this case, we need to parse the string and use it in the output of the original pattern.
3305 // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
3306 //
3307 // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
3308 const expression = parse$1(rest, { ...options, fastpaths: false }).output;
3309
3310 output = token.close = `)${expression})${extglobStar})`;
3311 }
3312
3313 if (token.prev.type === 'bos') {
3314 state.negatedExtglob = true;
3315 }
3316 }
3317
3318 push({ type: 'paren', extglob: true, value, output });
3319 decrement('parens');
3320 };
3321
3322 /**
3323 * Fast paths
3324 */
3325
3326 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
3327 let backslashes = false;
3328
3329 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
3330 if (first === '\\') {
3331 backslashes = true;
3332 return m;
3333 }
3334
3335 if (first === '?') {
3336 if (esc) {
3337 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
3338 }
3339 if (index === 0) {
3340 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
3341 }
3342 return QMARK.repeat(chars.length);
3343 }
3344
3345 if (first === '.') {
3346 return DOT_LITERAL.repeat(chars.length);
3347 }
3348
3349 if (first === '*') {
3350 if (esc) {
3351 return esc + first + (rest ? star : '');
3352 }
3353 return star;
3354 }
3355 return esc ? m : `\\${m}`;
3356 });
3357
3358 if (backslashes === true) {
3359 if (opts.unescape === true) {
3360 output = output.replace(/\\/g, '');
3361 } else {
3362 output = output.replace(/\\+/g, m => {
3363 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
3364 });
3365 }
3366 }
3367
3368 if (output === input && opts.contains === true) {
3369 state.output = input;
3370 return state;
3371 }
3372
3373 state.output = utils$1.wrapOutput(output, state, options);
3374 return state;
3375 }
3376
3377 /**
3378 * Tokenize input until we reach end-of-string
3379 */
3380
3381 while (!eos()) {
3382 value = advance();
3383
3384 if (value === '\u0000') {
3385 continue;
3386 }
3387
3388 /**
3389 * Escaped characters
3390 */
3391
3392 if (value === '\\') {
3393 const next = peek();
3394
3395 if (next === '/' && opts.bash !== true) {
3396 continue;
3397 }
3398
3399 if (next === '.' || next === ';') {
3400 continue;
3401 }
3402
3403 if (!next) {
3404 value += '\\';
3405 push({ type: 'text', value });
3406 continue;
3407 }
3408
3409 // collapse slashes to reduce potential for exploits
3410 const match = /^\\+/.exec(remaining());
3411 let slashes = 0;
3412
3413 if (match && match[0].length > 2) {
3414 slashes = match[0].length;
3415 state.index += slashes;
3416 if (slashes % 2 !== 0) {
3417 value += '\\';
3418 }
3419 }
3420
3421 if (opts.unescape === true) {
3422 value = advance();
3423 } else {
3424 value += advance();
3425 }
3426
3427 if (state.brackets === 0) {
3428 push({ type: 'text', value });
3429 continue;
3430 }
3431 }
3432
3433 /**
3434 * If we're inside a regex character class, continue
3435 * until we reach the closing bracket.
3436 */
3437
3438 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
3439 if (opts.posix !== false && value === ':') {
3440 const inner = prev.value.slice(1);
3441 if (inner.includes('[')) {
3442 prev.posix = true;
3443
3444 if (inner.includes(':')) {
3445 const idx = prev.value.lastIndexOf('[');
3446 const pre = prev.value.slice(0, idx);
3447 const rest = prev.value.slice(idx + 2);
3448 const posix = POSIX_REGEX_SOURCE[rest];
3449 if (posix) {
3450 prev.value = pre + posix;
3451 state.backtrack = true;
3452 advance();
3453
3454 if (!bos.output && tokens.indexOf(prev) === 1) {
3455 bos.output = ONE_CHAR;
3456 }
3457 continue;
3458 }
3459 }
3460 }
3461 }
3462
3463 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
3464 value = `\\${value}`;
3465 }
3466
3467 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
3468 value = `\\${value}`;
3469 }
3470
3471 if (opts.posix === true && value === '!' && prev.value === '[') {
3472 value = '^';
3473 }
3474
3475 prev.value += value;
3476 append({ value });
3477 continue;
3478 }
3479
3480 /**
3481 * If we're inside a quoted string, continue
3482 * until we reach the closing double quote.
3483 */
3484
3485 if (state.quotes === 1 && value !== '"') {
3486 value = utils$1.escapeRegex(value);
3487 prev.value += value;
3488 append({ value });
3489 continue;
3490 }
3491
3492 /**
3493 * Double quotes
3494 */
3495
3496 if (value === '"') {
3497 state.quotes = state.quotes === 1 ? 0 : 1;
3498 if (opts.keepQuotes === true) {
3499 push({ type: 'text', value });
3500 }
3501 continue;
3502 }
3503
3504 /**
3505 * Parentheses
3506 */
3507
3508 if (value === '(') {
3509 increment('parens');
3510 push({ type: 'paren', value });
3511 continue;
3512 }
3513
3514 if (value === ')') {
3515 if (state.parens === 0 && opts.strictBrackets === true) {
3516 throw new SyntaxError(syntaxError('opening', '('));
3517 }
3518
3519 const extglob = extglobs[extglobs.length - 1];
3520 if (extglob && state.parens === extglob.parens + 1) {
3521 extglobClose(extglobs.pop());
3522 continue;
3523 }
3524
3525 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
3526 decrement('parens');
3527 continue;
3528 }
3529
3530 /**
3531 * Square brackets
3532 */
3533
3534 if (value === '[') {
3535 if (opts.nobracket === true || !remaining().includes(']')) {
3536 if (opts.nobracket !== true && opts.strictBrackets === true) {
3537 throw new SyntaxError(syntaxError('closing', ']'));
3538 }
3539
3540 value = `\\${value}`;
3541 } else {
3542 increment('brackets');
3543 }
3544
3545 push({ type: 'bracket', value });
3546 continue;
3547 }
3548
3549 if (value === ']') {
3550 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
3551 push({ type: 'text', value, output: `\\${value}` });
3552 continue;
3553 }
3554
3555 if (state.brackets === 0) {
3556 if (opts.strictBrackets === true) {
3557 throw new SyntaxError(syntaxError('opening', '['));
3558 }
3559
3560 push({ type: 'text', value, output: `\\${value}` });
3561 continue;
3562 }
3563
3564 decrement('brackets');
3565
3566 const prevValue = prev.value.slice(1);
3567 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
3568 value = `/${value}`;
3569 }
3570
3571 prev.value += value;
3572 append({ value });
3573
3574 // when literal brackets are explicitly disabled
3575 // assume we should match with a regex character class
3576 if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
3577 continue;
3578 }
3579
3580 const escaped = utils$1.escapeRegex(prev.value);
3581 state.output = state.output.slice(0, -prev.value.length);
3582
3583 // when literal brackets are explicitly enabled
3584 // assume we should escape the brackets to match literal characters
3585 if (opts.literalBrackets === true) {
3586 state.output += escaped;
3587 prev.value = escaped;
3588 continue;
3589 }
3590
3591 // when the user specifies nothing, try to match both
3592 prev.value = `(${capture}${escaped}|${prev.value})`;
3593 state.output += prev.value;
3594 continue;
3595 }
3596
3597 /**
3598 * Braces
3599 */
3600
3601 if (value === '{' && opts.nobrace !== true) {
3602 increment('braces');
3603
3604 const open = {
3605 type: 'brace',
3606 value,
3607 output: '(',
3608 outputIndex: state.output.length,
3609 tokensIndex: state.tokens.length
3610 };
3611
3612 braces.push(open);
3613 push(open);
3614 continue;
3615 }
3616
3617 if (value === '}') {
3618 const brace = braces[braces.length - 1];
3619
3620 if (opts.nobrace === true || !brace) {
3621 push({ type: 'text', value, output: value });
3622 continue;
3623 }
3624
3625 let output = ')';
3626
3627 if (brace.dots === true) {
3628 const arr = tokens.slice();
3629 const range = [];
3630
3631 for (let i = arr.length - 1; i >= 0; i--) {
3632 tokens.pop();
3633 if (arr[i].type === 'brace') {
3634 break;
3635 }
3636 if (arr[i].type !== 'dots') {
3637 range.unshift(arr[i].value);
3638 }
3639 }
3640
3641 output = expandRange(range, opts);
3642 state.backtrack = true;
3643 }
3644
3645 if (brace.comma !== true && brace.dots !== true) {
3646 const out = state.output.slice(0, brace.outputIndex);
3647 const toks = state.tokens.slice(brace.tokensIndex);
3648 brace.value = brace.output = '\\{';
3649 value = output = '\\}';
3650 state.output = out;
3651 for (const t of toks) {
3652 state.output += (t.output || t.value);
3653 }
3654 }
3655
3656 push({ type: 'brace', value, output });
3657 decrement('braces');
3658 braces.pop();
3659 continue;
3660 }
3661
3662 /**
3663 * Pipes
3664 */
3665
3666 if (value === '|') {
3667 if (extglobs.length > 0) {
3668 extglobs[extglobs.length - 1].conditions++;
3669 }
3670 push({ type: 'text', value });
3671 continue;
3672 }
3673
3674 /**
3675 * Commas
3676 */
3677
3678 if (value === ',') {
3679 let output = value;
3680
3681 const brace = braces[braces.length - 1];
3682 if (brace && stack[stack.length - 1] === 'braces') {
3683 brace.comma = true;
3684 output = '|';
3685 }
3686
3687 push({ type: 'comma', value, output });
3688 continue;
3689 }
3690
3691 /**
3692 * Slashes
3693 */
3694
3695 if (value === '/') {
3696 // if the beginning of the glob is "./", advance the start
3697 // to the current index, and don't add the "./" characters
3698 // to the state. This greatly simplifies lookbehinds when
3699 // checking for BOS characters like "!" and "." (not "./")
3700 if (prev.type === 'dot' && state.index === state.start + 1) {
3701 state.start = state.index + 1;
3702 state.consumed = '';
3703 state.output = '';
3704 tokens.pop();
3705 prev = bos; // reset "prev" to the first token
3706 continue;
3707 }
3708
3709 push({ type: 'slash', value, output: SLASH_LITERAL });
3710 continue;
3711 }
3712
3713 /**
3714 * Dots
3715 */
3716
3717 if (value === '.') {
3718 if (state.braces > 0 && prev.type === 'dot') {
3719 if (prev.value === '.') prev.output = DOT_LITERAL;
3720 const brace = braces[braces.length - 1];
3721 prev.type = 'dots';
3722 prev.output += value;
3723 prev.value += value;
3724 brace.dots = true;
3725 continue;
3726 }
3727
3728 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
3729 push({ type: 'text', value, output: DOT_LITERAL });
3730 continue;
3731 }
3732
3733 push({ type: 'dot', value, output: DOT_LITERAL });
3734 continue;
3735 }
3736
3737 /**
3738 * Question marks
3739 */
3740
3741 if (value === '?') {
3742 const isGroup = prev && prev.value === '(';
3743 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3744 extglobOpen('qmark', value);
3745 continue;
3746 }
3747
3748 if (prev && prev.type === 'paren') {
3749 const next = peek();
3750 let output = value;
3751
3752 if (next === '<' && !utils$1.supportsLookbehinds()) {
3753 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
3754 }
3755
3756 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
3757 output = `\\${value}`;
3758 }
3759
3760 push({ type: 'text', value, output });
3761 continue;
3762 }
3763
3764 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
3765 push({ type: 'qmark', value, output: QMARK_NO_DOT });
3766 continue;
3767 }
3768
3769 push({ type: 'qmark', value, output: QMARK });
3770 continue;
3771 }
3772
3773 /**
3774 * Exclamation
3775 */
3776
3777 if (value === '!') {
3778 if (opts.noextglob !== true && peek() === '(') {
3779 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
3780 extglobOpen('negate', value);
3781 continue;
3782 }
3783 }
3784
3785 if (opts.nonegate !== true && state.index === 0) {
3786 negate();
3787 continue;
3788 }
3789 }
3790
3791 /**
3792 * Plus
3793 */
3794
3795 if (value === '+') {
3796 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3797 extglobOpen('plus', value);
3798 continue;
3799 }
3800
3801 if ((prev && prev.value === '(') || opts.regex === false) {
3802 push({ type: 'plus', value, output: PLUS_LITERAL });
3803 continue;
3804 }
3805
3806 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
3807 push({ type: 'plus', value });
3808 continue;
3809 }
3810
3811 push({ type: 'plus', value: PLUS_LITERAL });
3812 continue;
3813 }
3814
3815 /**
3816 * Plain text
3817 */
3818
3819 if (value === '@') {
3820 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3821 push({ type: 'at', extglob: true, value, output: '' });
3822 continue;
3823 }
3824
3825 push({ type: 'text', value });
3826 continue;
3827 }
3828
3829 /**
3830 * Plain text
3831 */
3832
3833 if (value !== '*') {
3834 if (value === '$' || value === '^') {
3835 value = `\\${value}`;
3836 }
3837
3838 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
3839 if (match) {
3840 value += match[0];
3841 state.index += match[0].length;
3842 }
3843
3844 push({ type: 'text', value });
3845 continue;
3846 }
3847
3848 /**
3849 * Stars
3850 */
3851
3852 if (prev && (prev.type === 'globstar' || prev.star === true)) {
3853 prev.type = 'star';
3854 prev.star = true;
3855 prev.value += value;
3856 prev.output = star;
3857 state.backtrack = true;
3858 state.globstar = true;
3859 consume(value);
3860 continue;
3861 }
3862
3863 let rest = remaining();
3864 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
3865 extglobOpen('star', value);
3866 continue;
3867 }
3868
3869 if (prev.type === 'star') {
3870 if (opts.noglobstar === true) {
3871 consume(value);
3872 continue;
3873 }
3874
3875 const prior = prev.prev;
3876 const before = prior.prev;
3877 const isStart = prior.type === 'slash' || prior.type === 'bos';
3878 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
3879
3880 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
3881 push({ type: 'star', value, output: '' });
3882 continue;
3883 }
3884
3885 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
3886 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
3887 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
3888 push({ type: 'star', value, output: '' });
3889 continue;
3890 }
3891
3892 // strip consecutive `/**/`
3893 while (rest.slice(0, 3) === '/**') {
3894 const after = input[state.index + 4];
3895 if (after && after !== '/') {
3896 break;
3897 }
3898 rest = rest.slice(3);
3899 consume('/**', 3);
3900 }
3901
3902 if (prior.type === 'bos' && eos()) {
3903 prev.type = 'globstar';
3904 prev.value += value;
3905 prev.output = globstar(opts);
3906 state.output = prev.output;
3907 state.globstar = true;
3908 consume(value);
3909 continue;
3910 }
3911
3912 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
3913 state.output = state.output.slice(0, -(prior.output + prev.output).length);
3914 prior.output = `(?:${prior.output}`;
3915
3916 prev.type = 'globstar';
3917 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
3918 prev.value += value;
3919 state.globstar = true;
3920 state.output += prior.output + prev.output;
3921 consume(value);
3922 continue;
3923 }
3924
3925 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
3926 const end = rest[1] !== void 0 ? '|$' : '';
3927
3928 state.output = state.output.slice(0, -(prior.output + prev.output).length);
3929 prior.output = `(?:${prior.output}`;
3930
3931 prev.type = 'globstar';
3932 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
3933 prev.value += value;
3934
3935 state.output += prior.output + prev.output;
3936 state.globstar = true;
3937
3938 consume(value + advance());
3939
3940 push({ type: 'slash', value: '/', output: '' });
3941 continue;
3942 }
3943
3944 if (prior.type === 'bos' && rest[0] === '/') {
3945 prev.type = 'globstar';
3946 prev.value += value;
3947 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
3948 state.output = prev.output;
3949 state.globstar = true;
3950 consume(value + advance());
3951 push({ type: 'slash', value: '/', output: '' });
3952 continue;
3953 }
3954
3955 // remove single star from output
3956 state.output = state.output.slice(0, -prev.output.length);
3957
3958 // reset previous token to globstar
3959 prev.type = 'globstar';
3960 prev.output = globstar(opts);
3961 prev.value += value;
3962
3963 // reset output with globstar
3964 state.output += prev.output;
3965 state.globstar = true;
3966 consume(value);
3967 continue;
3968 }
3969
3970 const token = { type: 'star', value, output: star };
3971
3972 if (opts.bash === true) {
3973 token.output = '.*?';
3974 if (prev.type === 'bos' || prev.type === 'slash') {
3975 token.output = nodot + token.output;
3976 }
3977 push(token);
3978 continue;
3979 }
3980
3981 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
3982 token.output = value;
3983 push(token);
3984 continue;
3985 }
3986
3987 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
3988 if (prev.type === 'dot') {
3989 state.output += NO_DOT_SLASH;
3990 prev.output += NO_DOT_SLASH;
3991
3992 } else if (opts.dot === true) {
3993 state.output += NO_DOTS_SLASH;
3994 prev.output += NO_DOTS_SLASH;
3995
3996 } else {
3997 state.output += nodot;
3998 prev.output += nodot;
3999 }
4000
4001 if (peek() !== '*') {
4002 state.output += ONE_CHAR;
4003 prev.output += ONE_CHAR;
4004 }
4005 }
4006
4007 push(token);
4008 }
4009
4010 while (state.brackets > 0) {
4011 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
4012 state.output = utils$1.escapeLast(state.output, '[');
4013 decrement('brackets');
4014 }
4015
4016 while (state.parens > 0) {
4017 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
4018 state.output = utils$1.escapeLast(state.output, '(');
4019 decrement('parens');
4020 }
4021
4022 while (state.braces > 0) {
4023 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
4024 state.output = utils$1.escapeLast(state.output, '{');
4025 decrement('braces');
4026 }
4027
4028 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
4029 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
4030 }
4031
4032 // rebuild the output if we had to backtrack at any point
4033 if (state.backtrack === true) {
4034 state.output = '';
4035
4036 for (const token of state.tokens) {
4037 state.output += token.output != null ? token.output : token.value;
4038
4039 if (token.suffix) {
4040 state.output += token.suffix;
4041 }
4042 }
4043 }
4044
4045 return state;
4046};
4047
4048/**
4049 * Fast paths for creating regular expressions for common glob patterns.
4050 * This can significantly speed up processing and has very little downside
4051 * impact when none of the fast paths match.
4052 */
4053
4054parse$1.fastpaths = (input, options) => {
4055 const opts = { ...options };
4056 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
4057 const len = input.length;
4058 if (len > max) {
4059 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
4060 }
4061
4062 input = REPLACEMENTS[input] || input;
4063 const win32 = utils$1.isWindows(options);
4064
4065 // create constants based on platform, for windows or posix
4066 const {
4067 DOT_LITERAL,
4068 SLASH_LITERAL,
4069 ONE_CHAR,
4070 DOTS_SLASH,
4071 NO_DOT,
4072 NO_DOTS,
4073 NO_DOTS_SLASH,
4074 STAR,
4075 START_ANCHOR
4076 } = constants$1.globChars(win32);
4077
4078 const nodot = opts.dot ? NO_DOTS : NO_DOT;
4079 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
4080 const capture = opts.capture ? '' : '?:';
4081 const state = { negated: false, prefix: '' };
4082 let star = opts.bash === true ? '.*?' : STAR;
4083
4084 if (opts.capture) {
4085 star = `(${star})`;
4086 }
4087
4088 const globstar = opts => {
4089 if (opts.noglobstar === true) return star;
4090 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
4091 };
4092
4093 const create = str => {
4094 switch (str) {
4095 case '*':
4096 return `${nodot}${ONE_CHAR}${star}`;
4097
4098 case '.*':
4099 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
4100
4101 case '*.*':
4102 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4103
4104 case '*/*':
4105 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
4106
4107 case '**':
4108 return nodot + globstar(opts);
4109
4110 case '**/*':
4111 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
4112
4113 case '**/*.*':
4114 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4115
4116 case '**/.*':
4117 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
4118
4119 default: {
4120 const match = /^(.*?)\.(\w+)$/.exec(str);
4121 if (!match) return;
4122
4123 const source = create(match[1]);
4124 if (!source) return;
4125
4126 return source + DOT_LITERAL + match[2];
4127 }
4128 }
4129 };
4130
4131 const output = utils$1.removePrefix(input, state);
4132 let source = create(output);
4133
4134 if (source && opts.strictSlashes !== true) {
4135 source += `${SLASH_LITERAL}?`;
4136 }
4137
4138 return source;
4139};
4140
4141var parse_1 = parse$1;
4142
4143const path = require$$0;
4144const scan = scan_1;
4145const parse = parse_1;
4146const utils = utils$3;
4147const constants = constants$2;
4148const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
4149
4150/**
4151 * Creates a matcher function from one or more glob patterns. The
4152 * returned function takes a string to match as its first argument,
4153 * and returns true if the string is a match. The returned matcher
4154 * function also takes a boolean as the second argument that, when true,
4155 * returns an object with additional information.
4156 *
4157 * ```js
4158 * const picomatch = require('picomatch');
4159 * // picomatch(glob[, options]);
4160 *
4161 * const isMatch = picomatch('*.!(*a)');
4162 * console.log(isMatch('a.a')); //=> false
4163 * console.log(isMatch('a.b')); //=> true
4164 * ```
4165 * @name picomatch
4166 * @param {String|Array} `globs` One or more glob patterns.
4167 * @param {Object=} `options`
4168 * @return {Function=} Returns a matcher function.
4169 * @api public
4170 */
4171
4172const picomatch = (glob, options, returnState = false) => {
4173 if (Array.isArray(glob)) {
4174 const fns = glob.map(input => picomatch(input, options, returnState));
4175 const arrayMatcher = str => {
4176 for (const isMatch of fns) {
4177 const state = isMatch(str);
4178 if (state) return state;
4179 }
4180 return false;
4181 };
4182 return arrayMatcher;
4183 }
4184
4185 const isState = isObject(glob) && glob.tokens && glob.input;
4186
4187 if (glob === '' || (typeof glob !== 'string' && !isState)) {
4188 throw new TypeError('Expected pattern to be a non-empty string');
4189 }
4190
4191 const opts = options || {};
4192 const posix = utils.isWindows(options);
4193 const regex = isState
4194 ? picomatch.compileRe(glob, options)
4195 : picomatch.makeRe(glob, options, false, true);
4196
4197 const state = regex.state;
4198 delete regex.state;
4199
4200 let isIgnored = () => false;
4201 if (opts.ignore) {
4202 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
4203 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
4204 }
4205
4206 const matcher = (input, returnObject = false) => {
4207 const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
4208 const result = { glob, state, regex, posix, input, output, match, isMatch };
4209
4210 if (typeof opts.onResult === 'function') {
4211 opts.onResult(result);
4212 }
4213
4214 if (isMatch === false) {
4215 result.isMatch = false;
4216 return returnObject ? result : false;
4217 }
4218
4219 if (isIgnored(input)) {
4220 if (typeof opts.onIgnore === 'function') {
4221 opts.onIgnore(result);
4222 }
4223 result.isMatch = false;
4224 return returnObject ? result : false;
4225 }
4226
4227 if (typeof opts.onMatch === 'function') {
4228 opts.onMatch(result);
4229 }
4230 return returnObject ? result : true;
4231 };
4232
4233 if (returnState) {
4234 matcher.state = state;
4235 }
4236
4237 return matcher;
4238};
4239
4240/**
4241 * Test `input` with the given `regex`. This is used by the main
4242 * `picomatch()` function to test the input string.
4243 *
4244 * ```js
4245 * const picomatch = require('picomatch');
4246 * // picomatch.test(input, regex[, options]);
4247 *
4248 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
4249 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
4250 * ```
4251 * @param {String} `input` String to test.
4252 * @param {RegExp} `regex`
4253 * @return {Object} Returns an object with matching info.
4254 * @api public
4255 */
4256
4257picomatch.test = (input, regex, options, { glob, posix } = {}) => {
4258 if (typeof input !== 'string') {
4259 throw new TypeError('Expected input to be a string');
4260 }
4261
4262 if (input === '') {
4263 return { isMatch: false, output: '' };
4264 }
4265
4266 const opts = options || {};
4267 const format = opts.format || (posix ? utils.toPosixSlashes : null);
4268 let match = input === glob;
4269 let output = (match && format) ? format(input) : input;
4270
4271 if (match === false) {
4272 output = format ? format(input) : input;
4273 match = output === glob;
4274 }
4275
4276 if (match === false || opts.capture === true) {
4277 if (opts.matchBase === true || opts.basename === true) {
4278 match = picomatch.matchBase(input, regex, options, posix);
4279 } else {
4280 match = regex.exec(output);
4281 }
4282 }
4283
4284 return { isMatch: Boolean(match), match, output };
4285};
4286
4287/**
4288 * Match the basename of a filepath.
4289 *
4290 * ```js
4291 * const picomatch = require('picomatch');
4292 * // picomatch.matchBase(input, glob[, options]);
4293 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
4294 * ```
4295 * @param {String} `input` String to test.
4296 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
4297 * @return {Boolean}
4298 * @api public
4299 */
4300
4301picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
4302 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
4303 return regex.test(path.basename(input));
4304};
4305
4306/**
4307 * Returns true if **any** of the given glob `patterns` match the specified `string`.
4308 *
4309 * ```js
4310 * const picomatch = require('picomatch');
4311 * // picomatch.isMatch(string, patterns[, options]);
4312 *
4313 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
4314 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
4315 * ```
4316 * @param {String|Array} str The string to test.
4317 * @param {String|Array} patterns One or more glob patterns to use for matching.
4318 * @param {Object} [options] See available [options](#options).
4319 * @return {Boolean} Returns true if any patterns match `str`
4320 * @api public
4321 */
4322
4323picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
4324
4325/**
4326 * Parse a glob pattern to create the source string for a regular
4327 * expression.
4328 *
4329 * ```js
4330 * const picomatch = require('picomatch');
4331 * const result = picomatch.parse(pattern[, options]);
4332 * ```
4333 * @param {String} `pattern`
4334 * @param {Object} `options`
4335 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
4336 * @api public
4337 */
4338
4339picomatch.parse = (pattern, options) => {
4340 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
4341 return parse(pattern, { ...options, fastpaths: false });
4342};
4343
4344/**
4345 * Scan a glob pattern to separate the pattern into segments.
4346 *
4347 * ```js
4348 * const picomatch = require('picomatch');
4349 * // picomatch.scan(input[, options]);
4350 *
4351 * const result = picomatch.scan('!./foo/*.js');
4352 * console.log(result);
4353 * { prefix: '!./',
4354 * input: '!./foo/*.js',
4355 * start: 3,
4356 * base: 'foo',
4357 * glob: '*.js',
4358 * isBrace: false,
4359 * isBracket: false,
4360 * isGlob: true,
4361 * isExtglob: false,
4362 * isGlobstar: false,
4363 * negated: true }
4364 * ```
4365 * @param {String} `input` Glob pattern to scan.
4366 * @param {Object} `options`
4367 * @return {Object} Returns an object with
4368 * @api public
4369 */
4370
4371picomatch.scan = (input, options) => scan(input, options);
4372
4373/**
4374 * Compile a regular expression from the `state` object returned by the
4375 * [parse()](#parse) method.
4376 *
4377 * @param {Object} `state`
4378 * @param {Object} `options`
4379 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
4380 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
4381 * @return {RegExp}
4382 * @api public
4383 */
4384
4385picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
4386 if (returnOutput === true) {
4387 return state.output;
4388 }
4389
4390 const opts = options || {};
4391 const prepend = opts.contains ? '' : '^';
4392 const append = opts.contains ? '' : '$';
4393
4394 let source = `${prepend}(?:${state.output})${append}`;
4395 if (state && state.negated === true) {
4396 source = `^(?!${source}).*$`;
4397 }
4398
4399 const regex = picomatch.toRegex(source, options);
4400 if (returnState === true) {
4401 regex.state = state;
4402 }
4403
4404 return regex;
4405};
4406
4407/**
4408 * Create a regular expression from a parsed glob pattern.
4409 *
4410 * ```js
4411 * const picomatch = require('picomatch');
4412 * const state = picomatch.parse('*.js');
4413 * // picomatch.compileRe(state[, options]);
4414 *
4415 * console.log(picomatch.compileRe(state));
4416 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4417 * ```
4418 * @param {String} `state` The object returned from the `.parse` method.
4419 * @param {Object} `options`
4420 * @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.
4421 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
4422 * @return {RegExp} Returns a regex created from the given pattern.
4423 * @api public
4424 */
4425
4426picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
4427 if (!input || typeof input !== 'string') {
4428 throw new TypeError('Expected a non-empty string');
4429 }
4430
4431 let parsed = { negated: false, fastpaths: true };
4432
4433 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
4434 parsed.output = parse.fastpaths(input, options);
4435 }
4436
4437 if (!parsed.output) {
4438 parsed = parse(input, options);
4439 }
4440
4441 return picomatch.compileRe(parsed, options, returnOutput, returnState);
4442};
4443
4444/**
4445 * Create a regular expression from the given regex source string.
4446 *
4447 * ```js
4448 * const picomatch = require('picomatch');
4449 * // picomatch.toRegex(source[, options]);
4450 *
4451 * const { output } = picomatch.parse('*.js');
4452 * console.log(picomatch.toRegex(output));
4453 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4454 * ```
4455 * @param {String} `source` Regular expression source string.
4456 * @param {Object} `options`
4457 * @return {RegExp}
4458 * @api public
4459 */
4460
4461picomatch.toRegex = (source, options) => {
4462 try {
4463 const opts = options || {};
4464 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
4465 } catch (err) {
4466 if (options && options.debug === true) throw err;
4467 return /$^/;
4468 }
4469};
4470
4471/**
4472 * Picomatch constants.
4473 * @return {Object}
4474 */
4475
4476picomatch.constants = constants;
4477
4478/**
4479 * Expose "picomatch"
4480 */
4481
4482var picomatch_1 = picomatch;
4483
4484(function (module) {
4485
4486 module.exports = picomatch_1;
4487} (picomatch$1));
4488
4489const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
4490
4491const extractors = {
4492 ArrayPattern(names, param) {
4493 for (const element of param.elements) {
4494 if (element)
4495 extractors[element.type](names, element);
4496 }
4497 },
4498 AssignmentPattern(names, param) {
4499 extractors[param.left.type](names, param.left);
4500 },
4501 Identifier(names, param) {
4502 names.push(param.name);
4503 },
4504 MemberExpression() { },
4505 ObjectPattern(names, param) {
4506 for (const prop of param.properties) {
4507 // @ts-ignore Typescript reports that this is not a valid type
4508 if (prop.type === 'RestElement') {
4509 extractors.RestElement(names, prop);
4510 }
4511 else {
4512 extractors[prop.value.type](names, prop.value);
4513 }
4514 }
4515 },
4516 RestElement(names, param) {
4517 extractors[param.argument.type](names, param.argument);
4518 }
4519};
4520const extractAssignedNames = function extractAssignedNames(param) {
4521 const names = [];
4522 extractors[param.type](names, param);
4523 return names;
4524};
4525
4526// Helper since Typescript can't detect readonly arrays with Array.isArray
4527function isArray$1(arg) {
4528 return Array.isArray(arg);
4529}
4530function ensureArray$1(thing) {
4531 if (isArray$1(thing))
4532 return thing;
4533 if (thing == null)
4534 return [];
4535 return [thing];
4536}
4537
4538const normalizePath = function normalizePath(filename) {
4539 return filename.split(win32.sep).join(posix.sep);
4540};
4541
4542function getMatcherString(id, resolutionBase) {
4543 if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
4544 return normalizePath(id);
4545 }
4546 // resolve('') is valid and will default to process.cwd()
4547 const basePath = normalizePath(resolve(resolutionBase || ''))
4548 // escape all possible (posix + win) path characters that might interfere with regex
4549 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
4550 // Note that we use posix.join because:
4551 // 1. the basePath has been normalized to use /
4552 // 2. the incoming glob (id) matcher, also uses /
4553 // otherwise Node will force backslash (\) on windows
4554 return posix.join(basePath, normalizePath(id));
4555}
4556const createFilter = function createFilter(include, exclude, options) {
4557 const resolutionBase = options && options.resolve;
4558 const getMatcher = (id) => id instanceof RegExp
4559 ? id
4560 : {
4561 test: (what) => {
4562 // this refactor is a tad overly verbose but makes for easy debugging
4563 const pattern = getMatcherString(id, resolutionBase);
4564 const fn = pm(pattern, { dot: true });
4565 const result = fn(what);
4566 return result;
4567 }
4568 };
4569 const includeMatchers = ensureArray$1(include).map(getMatcher);
4570 const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
4571 return function result(id) {
4572 if (typeof id !== 'string')
4573 return false;
4574 if (/\0/.test(id))
4575 return false;
4576 const pathId = normalizePath(id);
4577 for (let i = 0; i < excludeMatchers.length; ++i) {
4578 const matcher = excludeMatchers[i];
4579 if (matcher.test(pathId))
4580 return false;
4581 }
4582 for (let i = 0; i < includeMatchers.length; ++i) {
4583 const matcher = includeMatchers[i];
4584 if (matcher.test(pathId))
4585 return true;
4586 }
4587 return !includeMatchers.length;
4588 };
4589};
4590
4591const 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';
4592const 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';
4593const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
4594forbiddenIdentifiers.add('');
4595
4596const BROKEN_FLOW_NONE = 0;
4597const BROKEN_FLOW_BREAK_CONTINUE = 1;
4598const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
4599function createInclusionContext() {
4600 return {
4601 brokenFlow: BROKEN_FLOW_NONE,
4602 includedCallArguments: new Set(),
4603 includedLabels: new Set()
4604 };
4605}
4606function createHasEffectsContext() {
4607 return {
4608 accessed: new PathTracker(),
4609 assigned: new PathTracker(),
4610 brokenFlow: BROKEN_FLOW_NONE,
4611 called: new DiscriminatedPathTracker(),
4612 ignore: {
4613 breaks: false,
4614 continues: false,
4615 labels: new Set(),
4616 returnYield: false
4617 },
4618 includedLabels: new Set(),
4619 instantiated: new DiscriminatedPathTracker(),
4620 replacedVariableInits: new Map()
4621 };
4622}
4623
4624function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
4625 return Object.create(inheritedDescriptions, memberDescriptions);
4626}
4627const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
4628 getLiteralValueAtPath() {
4629 return undefined;
4630 }
4631})();
4632const returnsUnknown = {
4633 value: {
4634 hasEffectsWhenCalled: null,
4635 returns: UNKNOWN_EXPRESSION
4636 }
4637};
4638const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
4639 getReturnExpressionWhenCalledAtPath(path) {
4640 if (path.length === 1) {
4641 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
4642 }
4643 return UNKNOWN_EXPRESSION;
4644 }
4645 hasEffectsOnInteractionAtPath(path, interaction, context) {
4646 if (interaction.type === INTERACTION_ACCESSED) {
4647 return path.length > 1;
4648 }
4649 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4650 return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
4651 }
4652 return true;
4653 }
4654})();
4655const returnsBoolean = {
4656 value: {
4657 hasEffectsWhenCalled: null,
4658 returns: UNKNOWN_LITERAL_BOOLEAN
4659 }
4660};
4661const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
4662 getReturnExpressionWhenCalledAtPath(path) {
4663 if (path.length === 1) {
4664 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
4665 }
4666 return UNKNOWN_EXPRESSION;
4667 }
4668 hasEffectsOnInteractionAtPath(path, interaction, context) {
4669 if (interaction.type === INTERACTION_ACCESSED) {
4670 return path.length > 1;
4671 }
4672 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4673 return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
4674 }
4675 return true;
4676 }
4677})();
4678const returnsNumber = {
4679 value: {
4680 hasEffectsWhenCalled: null,
4681 returns: UNKNOWN_LITERAL_NUMBER
4682 }
4683};
4684const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
4685 getReturnExpressionWhenCalledAtPath(path) {
4686 if (path.length === 1) {
4687 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
4688 }
4689 return UNKNOWN_EXPRESSION;
4690 }
4691 hasEffectsOnInteractionAtPath(path, interaction, context) {
4692 if (interaction.type === INTERACTION_ACCESSED) {
4693 return path.length > 1;
4694 }
4695 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4696 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
4697 }
4698 return true;
4699 }
4700})();
4701const returnsString = {
4702 value: {
4703 hasEffectsWhenCalled: null,
4704 returns: UNKNOWN_LITERAL_STRING
4705 }
4706};
4707const stringReplace = {
4708 value: {
4709 hasEffectsWhenCalled({ args }, context) {
4710 const arg1 = args[1];
4711 return (args.length < 2 ||
4712 (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4713 deoptimizeCache() { }
4714 }) === 'symbol' &&
4715 arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
4716 },
4717 returns: UNKNOWN_LITERAL_STRING
4718 }
4719};
4720const objectMembers = assembleMemberDescriptions({
4721 hasOwnProperty: returnsBoolean,
4722 isPrototypeOf: returnsBoolean,
4723 propertyIsEnumerable: returnsBoolean,
4724 toLocaleString: returnsString,
4725 toString: returnsString,
4726 valueOf: returnsUnknown
4727});
4728const literalBooleanMembers = assembleMemberDescriptions({
4729 valueOf: returnsBoolean
4730}, objectMembers);
4731const literalNumberMembers = assembleMemberDescriptions({
4732 toExponential: returnsString,
4733 toFixed: returnsString,
4734 toLocaleString: returnsString,
4735 toPrecision: returnsString,
4736 valueOf: returnsNumber
4737}, objectMembers);
4738const literalStringMembers = assembleMemberDescriptions({
4739 anchor: returnsString,
4740 at: returnsUnknown,
4741 big: returnsString,
4742 blink: returnsString,
4743 bold: returnsString,
4744 charAt: returnsString,
4745 charCodeAt: returnsNumber,
4746 codePointAt: returnsUnknown,
4747 concat: returnsString,
4748 endsWith: returnsBoolean,
4749 fixed: returnsString,
4750 fontcolor: returnsString,
4751 fontsize: returnsString,
4752 includes: returnsBoolean,
4753 indexOf: returnsNumber,
4754 italics: returnsString,
4755 lastIndexOf: returnsNumber,
4756 link: returnsString,
4757 localeCompare: returnsNumber,
4758 match: returnsUnknown,
4759 matchAll: returnsUnknown,
4760 normalize: returnsString,
4761 padEnd: returnsString,
4762 padStart: returnsString,
4763 repeat: returnsString,
4764 replace: stringReplace,
4765 replaceAll: stringReplace,
4766 search: returnsNumber,
4767 slice: returnsString,
4768 small: returnsString,
4769 split: returnsUnknown,
4770 startsWith: returnsBoolean,
4771 strike: returnsString,
4772 sub: returnsString,
4773 substr: returnsString,
4774 substring: returnsString,
4775 sup: returnsString,
4776 toLocaleLowerCase: returnsString,
4777 toLocaleUpperCase: returnsString,
4778 toLowerCase: returnsString,
4779 toString: returnsString,
4780 toUpperCase: returnsString,
4781 trim: returnsString,
4782 trimEnd: returnsString,
4783 trimLeft: returnsString,
4784 trimRight: returnsString,
4785 trimStart: returnsString,
4786 valueOf: returnsString
4787}, objectMembers);
4788function getLiteralMembersForValue(value) {
4789 switch (typeof value) {
4790 case 'boolean':
4791 return literalBooleanMembers;
4792 case 'number':
4793 return literalNumberMembers;
4794 case 'string':
4795 return literalStringMembers;
4796 }
4797 return Object.create(null);
4798}
4799function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
4800 var _a, _b;
4801 if (typeof memberName !== 'string' || !members[memberName]) {
4802 return true;
4803 }
4804 return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
4805}
4806function getMemberReturnExpressionWhenCalled(members, memberName) {
4807 if (typeof memberName !== 'string' || !members[memberName])
4808 return UNKNOWN_EXPRESSION;
4809 return members[memberName].returns;
4810}
4811
4812// AST walker module for Mozilla Parser API compatible trees
4813
4814function skipThrough(node, st, c) { c(node, st); }
4815function ignore(_node, _st, _c) {}
4816
4817// Node walkers.
4818
4819var base$1 = {};
4820
4821base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
4822 for (var i = 0, list = node.body; i < list.length; i += 1)
4823 {
4824 var stmt = list[i];
4825
4826 c(stmt, st, "Statement");
4827 }
4828};
4829base$1.Statement = skipThrough;
4830base$1.EmptyStatement = ignore;
4831base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
4832 function (node, st, c) { return c(node.expression, st, "Expression"); };
4833base$1.IfStatement = function (node, st, c) {
4834 c(node.test, st, "Expression");
4835 c(node.consequent, st, "Statement");
4836 if (node.alternate) { c(node.alternate, st, "Statement"); }
4837};
4838base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
4839base$1.BreakStatement = base$1.ContinueStatement = ignore;
4840base$1.WithStatement = function (node, st, c) {
4841 c(node.object, st, "Expression");
4842 c(node.body, st, "Statement");
4843};
4844base$1.SwitchStatement = function (node, st, c) {
4845 c(node.discriminant, st, "Expression");
4846 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
4847 var cs = list$1[i$1];
4848
4849 if (cs.test) { c(cs.test, st, "Expression"); }
4850 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
4851 {
4852 var cons = list[i];
4853
4854 c(cons, st, "Statement");
4855 }
4856 }
4857};
4858base$1.SwitchCase = function (node, st, c) {
4859 if (node.test) { c(node.test, st, "Expression"); }
4860 for (var i = 0, list = node.consequent; i < list.length; i += 1)
4861 {
4862 var cons = list[i];
4863
4864 c(cons, st, "Statement");
4865 }
4866};
4867base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
4868 if (node.argument) { c(node.argument, st, "Expression"); }
4869};
4870base$1.ThrowStatement = base$1.SpreadElement =
4871 function (node, st, c) { return c(node.argument, st, "Expression"); };
4872base$1.TryStatement = function (node, st, c) {
4873 c(node.block, st, "Statement");
4874 if (node.handler) { c(node.handler, st); }
4875 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
4876};
4877base$1.CatchClause = function (node, st, c) {
4878 if (node.param) { c(node.param, st, "Pattern"); }
4879 c(node.body, st, "Statement");
4880};
4881base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
4882 c(node.test, st, "Expression");
4883 c(node.body, st, "Statement");
4884};
4885base$1.ForStatement = function (node, st, c) {
4886 if (node.init) { c(node.init, st, "ForInit"); }
4887 if (node.test) { c(node.test, st, "Expression"); }
4888 if (node.update) { c(node.update, st, "Expression"); }
4889 c(node.body, st, "Statement");
4890};
4891base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
4892 c(node.left, st, "ForInit");
4893 c(node.right, st, "Expression");
4894 c(node.body, st, "Statement");
4895};
4896base$1.ForInit = function (node, st, c) {
4897 if (node.type === "VariableDeclaration") { c(node, st); }
4898 else { c(node, st, "Expression"); }
4899};
4900base$1.DebuggerStatement = ignore;
4901
4902base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
4903base$1.VariableDeclaration = function (node, st, c) {
4904 for (var i = 0, list = node.declarations; i < list.length; i += 1)
4905 {
4906 var decl = list[i];
4907
4908 c(decl, st);
4909 }
4910};
4911base$1.VariableDeclarator = function (node, st, c) {
4912 c(node.id, st, "Pattern");
4913 if (node.init) { c(node.init, st, "Expression"); }
4914};
4915
4916base$1.Function = function (node, st, c) {
4917 if (node.id) { c(node.id, st, "Pattern"); }
4918 for (var i = 0, list = node.params; i < list.length; i += 1)
4919 {
4920 var param = list[i];
4921
4922 c(param, st, "Pattern");
4923 }
4924 c(node.body, st, node.expression ? "Expression" : "Statement");
4925};
4926
4927base$1.Pattern = function (node, st, c) {
4928 if (node.type === "Identifier")
4929 { c(node, st, "VariablePattern"); }
4930 else if (node.type === "MemberExpression")
4931 { c(node, st, "MemberPattern"); }
4932 else
4933 { c(node, st); }
4934};
4935base$1.VariablePattern = ignore;
4936base$1.MemberPattern = skipThrough;
4937base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
4938base$1.ArrayPattern = function (node, st, c) {
4939 for (var i = 0, list = node.elements; i < list.length; i += 1) {
4940 var elt = list[i];
4941
4942 if (elt) { c(elt, st, "Pattern"); }
4943 }
4944};
4945base$1.ObjectPattern = function (node, st, c) {
4946 for (var i = 0, list = node.properties; i < list.length; i += 1) {
4947 var prop = list[i];
4948
4949 if (prop.type === "Property") {
4950 if (prop.computed) { c(prop.key, st, "Expression"); }
4951 c(prop.value, st, "Pattern");
4952 } else if (prop.type === "RestElement") {
4953 c(prop.argument, st, "Pattern");
4954 }
4955 }
4956};
4957
4958base$1.Expression = skipThrough;
4959base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
4960base$1.ArrayExpression = function (node, st, c) {
4961 for (var i = 0, list = node.elements; i < list.length; i += 1) {
4962 var elt = list[i];
4963
4964 if (elt) { c(elt, st, "Expression"); }
4965 }
4966};
4967base$1.ObjectExpression = function (node, st, c) {
4968 for (var i = 0, list = node.properties; i < list.length; i += 1)
4969 {
4970 var prop = list[i];
4971
4972 c(prop, st);
4973 }
4974};
4975base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
4976base$1.SequenceExpression = function (node, st, c) {
4977 for (var i = 0, list = node.expressions; i < list.length; i += 1)
4978 {
4979 var expr = list[i];
4980
4981 c(expr, st, "Expression");
4982 }
4983};
4984base$1.TemplateLiteral = function (node, st, c) {
4985 for (var i = 0, list = node.quasis; i < list.length; i += 1)
4986 {
4987 var quasi = list[i];
4988
4989 c(quasi, st);
4990 }
4991
4992 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
4993 {
4994 var expr = list$1[i$1];
4995
4996 c(expr, st, "Expression");
4997 }
4998};
4999base$1.TemplateElement = ignore;
5000base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
5001 c(node.argument, st, "Expression");
5002};
5003base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
5004 c(node.left, st, "Expression");
5005 c(node.right, st, "Expression");
5006};
5007base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
5008 c(node.left, st, "Pattern");
5009 c(node.right, st, "Expression");
5010};
5011base$1.ConditionalExpression = function (node, st, c) {
5012 c(node.test, st, "Expression");
5013 c(node.consequent, st, "Expression");
5014 c(node.alternate, st, "Expression");
5015};
5016base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
5017 c(node.callee, st, "Expression");
5018 if (node.arguments)
5019 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
5020 {
5021 var arg = list[i];
5022
5023 c(arg, st, "Expression");
5024 } }
5025};
5026base$1.MemberExpression = function (node, st, c) {
5027 c(node.object, st, "Expression");
5028 if (node.computed) { c(node.property, st, "Expression"); }
5029};
5030base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
5031 if (node.declaration)
5032 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
5033 if (node.source) { c(node.source, st, "Expression"); }
5034};
5035base$1.ExportAllDeclaration = function (node, st, c) {
5036 if (node.exported)
5037 { c(node.exported, st); }
5038 c(node.source, st, "Expression");
5039};
5040base$1.ImportDeclaration = function (node, st, c) {
5041 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
5042 {
5043 var spec = list[i];
5044
5045 c(spec, st);
5046 }
5047 c(node.source, st, "Expression");
5048};
5049base$1.ImportExpression = function (node, st, c) {
5050 c(node.source, st, "Expression");
5051};
5052base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
5053
5054base$1.TaggedTemplateExpression = function (node, st, c) {
5055 c(node.tag, st, "Expression");
5056 c(node.quasi, st, "Expression");
5057};
5058base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
5059base$1.Class = function (node, st, c) {
5060 if (node.id) { c(node.id, st, "Pattern"); }
5061 if (node.superClass) { c(node.superClass, st, "Expression"); }
5062 c(node.body, st);
5063};
5064base$1.ClassBody = function (node, st, c) {
5065 for (var i = 0, list = node.body; i < list.length; i += 1)
5066 {
5067 var elt = list[i];
5068
5069 c(elt, st);
5070 }
5071};
5072base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
5073 if (node.computed) { c(node.key, st, "Expression"); }
5074 if (node.value) { c(node.value, st, "Expression"); }
5075};
5076
5077const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
5078const BinaryExpression$1 = 'BinaryExpression';
5079const BlockStatement$1 = 'BlockStatement';
5080const CallExpression$1 = 'CallExpression';
5081const ChainExpression$1 = 'ChainExpression';
5082const ConditionalExpression$1 = 'ConditionalExpression';
5083const ExpressionStatement$1 = 'ExpressionStatement';
5084const Identifier$1 = 'Identifier';
5085const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
5086const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
5087const LogicalExpression$1 = 'LogicalExpression';
5088const NewExpression$1 = 'NewExpression';
5089const Program$1 = 'Program';
5090const Property$1 = 'Property';
5091const ReturnStatement$1 = 'ReturnStatement';
5092const SequenceExpression$1 = 'SequenceExpression';
5093
5094// this looks ridiculous, but it prevents sourcemap tooling from mistaking
5095// this for an actual sourceMappingURL
5096let SOURCEMAPPING_URL = 'sourceMa';
5097SOURCEMAPPING_URL += 'ppingURL';
5098const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
5099const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
5100
5101const ANNOTATION_KEY = '_rollupAnnotations';
5102const INVALID_COMMENT_KEY = '_rollupRemoved';
5103function handlePureAnnotationsOfNode(node, state, type = node.type) {
5104 const { annotations } = state;
5105 let comment = annotations[state.annotationIndex];
5106 while (comment && node.start >= comment.end) {
5107 markPureNode(node, comment, state.code);
5108 comment = annotations[++state.annotationIndex];
5109 }
5110 if (comment && comment.end <= node.end) {
5111 base$1[type](node, state, handlePureAnnotationsOfNode);
5112 while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
5113 ++state.annotationIndex;
5114 annotateNode(node, comment, false);
5115 }
5116 }
5117}
5118const neitherWithespaceNorBrackets = /[^\s(]/g;
5119const noWhitespace = /\S/g;
5120function markPureNode(node, comment, code) {
5121 const annotatedNodes = [];
5122 let invalidAnnotation;
5123 const codeInBetween = code.slice(comment.end, node.start);
5124 if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
5125 const parentStart = node.start;
5126 while (true) {
5127 annotatedNodes.push(node);
5128 switch (node.type) {
5129 case ExpressionStatement$1:
5130 case ChainExpression$1:
5131 node = node.expression;
5132 continue;
5133 case SequenceExpression$1:
5134 // if there are parentheses, the annotation would apply to the entire expression
5135 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5136 node = node.expressions[0];
5137 continue;
5138 }
5139 invalidAnnotation = true;
5140 break;
5141 case ConditionalExpression$1:
5142 // if there are parentheses, the annotation would apply to the entire expression
5143 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5144 node = node.test;
5145 continue;
5146 }
5147 invalidAnnotation = true;
5148 break;
5149 case LogicalExpression$1:
5150 case BinaryExpression$1:
5151 // if there are parentheses, the annotation would apply to the entire expression
5152 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5153 node = node.left;
5154 continue;
5155 }
5156 invalidAnnotation = true;
5157 break;
5158 case CallExpression$1:
5159 case NewExpression$1:
5160 break;
5161 default:
5162 invalidAnnotation = true;
5163 }
5164 break;
5165 }
5166 }
5167 else {
5168 invalidAnnotation = true;
5169 }
5170 if (invalidAnnotation) {
5171 annotateNode(node, comment, false);
5172 }
5173 else {
5174 for (const node of annotatedNodes) {
5175 annotateNode(node, comment, true);
5176 }
5177 }
5178}
5179function doesNotMatchOutsideComment(code, forbiddenChars) {
5180 let nextMatch;
5181 while ((nextMatch = forbiddenChars.exec(code)) !== null) {
5182 if (nextMatch[0] === '/') {
5183 const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
5184 if (charCodeAfterSlash === 42 /*"*"*/) {
5185 forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
5186 continue;
5187 }
5188 else if (charCodeAfterSlash === 47 /*"/"*/) {
5189 forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
5190 continue;
5191 }
5192 }
5193 forbiddenChars.lastIndex = 0;
5194 return false;
5195 }
5196 return true;
5197}
5198const pureCommentRegex = /[@#]__PURE__/;
5199function addAnnotations(comments, esTreeAst, code) {
5200 const annotations = [];
5201 const sourceMappingComments = [];
5202 for (const comment of comments) {
5203 if (pureCommentRegex.test(comment.value)) {
5204 annotations.push(comment);
5205 }
5206 else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
5207 sourceMappingComments.push(comment);
5208 }
5209 }
5210 for (const comment of sourceMappingComments) {
5211 annotateNode(esTreeAst, comment, false);
5212 }
5213 handlePureAnnotationsOfNode(esTreeAst, {
5214 annotationIndex: 0,
5215 annotations,
5216 code
5217 });
5218}
5219function annotateNode(node, comment, valid) {
5220 const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
5221 const property = node[key];
5222 if (property) {
5223 property.push(comment);
5224 }
5225 else {
5226 node[key] = [comment];
5227 }
5228}
5229
5230const keys = {
5231 Literal: [],
5232 Program: ['body']
5233};
5234function getAndCreateKeys(esTreeNode) {
5235 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
5236 return keys[esTreeNode.type];
5237}
5238
5239const INCLUDE_PARAMETERS = 'variables';
5240class NodeBase extends ExpressionEntity {
5241 constructor(esTreeNode, parent, parentScope) {
5242 super();
5243 /**
5244 * Nodes can apply custom deoptimizations once they become part of the
5245 * executed code. To do this, they must initialize this as false, implement
5246 * applyDeoptimizations and call this from include and hasEffects if they have
5247 * custom handlers
5248 */
5249 this.deoptimized = false;
5250 this.esTreeNode = esTreeNode;
5251 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
5252 this.parent = parent;
5253 this.context = parent.context;
5254 this.createScope(parentScope);
5255 this.parseNode(esTreeNode);
5256 this.initialise();
5257 this.context.magicString.addSourcemapLocation(this.start);
5258 this.context.magicString.addSourcemapLocation(this.end);
5259 }
5260 addExportedVariables(_variables, _exportNamesByVariable) { }
5261 /**
5262 * Override this to bind assignments to variables and do any initialisations that
5263 * require the scopes to be populated with variables.
5264 */
5265 bind() {
5266 for (const key of this.keys) {
5267 const value = this[key];
5268 if (value === null)
5269 continue;
5270 if (Array.isArray(value)) {
5271 for (const child of value) {
5272 child === null || child === void 0 ? void 0 : child.bind();
5273 }
5274 }
5275 else {
5276 value.bind();
5277 }
5278 }
5279 }
5280 /**
5281 * Override if this node should receive a different scope than the parent scope.
5282 */
5283 createScope(parentScope) {
5284 this.scope = parentScope;
5285 }
5286 hasEffects(context) {
5287 if (!this.deoptimized)
5288 this.applyDeoptimizations();
5289 for (const key of this.keys) {
5290 const value = this[key];
5291 if (value === null)
5292 continue;
5293 if (Array.isArray(value)) {
5294 for (const child of value) {
5295 if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
5296 return true;
5297 }
5298 }
5299 else if (value.hasEffects(context))
5300 return true;
5301 }
5302 return false;
5303 }
5304 hasEffectsAsAssignmentTarget(context, _checkAccess) {
5305 return (this.hasEffects(context) ||
5306 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
5307 }
5308 include(context, includeChildrenRecursively, _options) {
5309 if (!this.deoptimized)
5310 this.applyDeoptimizations();
5311 this.included = true;
5312 for (const key of this.keys) {
5313 const value = this[key];
5314 if (value === null)
5315 continue;
5316 if (Array.isArray(value)) {
5317 for (const child of value) {
5318 child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
5319 }
5320 }
5321 else {
5322 value.include(context, includeChildrenRecursively);
5323 }
5324 }
5325 }
5326 includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
5327 this.include(context, includeChildrenRecursively);
5328 }
5329 /**
5330 * Override to perform special initialisation steps after the scope is initialised
5331 */
5332 initialise() { }
5333 insertSemicolon(code) {
5334 if (code.original[this.end - 1] !== ';') {
5335 code.appendLeft(this.end, ';');
5336 }
5337 }
5338 parseNode(esTreeNode) {
5339 for (const [key, value] of Object.entries(esTreeNode)) {
5340 // That way, we can override this function to add custom initialisation and then call super.parseNode
5341 if (this.hasOwnProperty(key))
5342 continue;
5343 if (key.charCodeAt(0) === 95 /* _ */) {
5344 if (key === ANNOTATION_KEY) {
5345 this.annotations = value;
5346 }
5347 else if (key === INVALID_COMMENT_KEY) {
5348 for (const { start, end } of value)
5349 this.context.magicString.remove(start, end);
5350 }
5351 }
5352 else if (typeof value !== 'object' || value === null) {
5353 this[key] = value;
5354 }
5355 else if (Array.isArray(value)) {
5356 this[key] = [];
5357 for (const child of value) {
5358 this[key].push(child === null
5359 ? null
5360 : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
5361 }
5362 }
5363 else {
5364 this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
5365 }
5366 }
5367 }
5368 render(code, options) {
5369 for (const key of this.keys) {
5370 const value = this[key];
5371 if (value === null)
5372 continue;
5373 if (Array.isArray(value)) {
5374 for (const child of value) {
5375 child === null || child === void 0 ? void 0 : child.render(code, options);
5376 }
5377 }
5378 else {
5379 value.render(code, options);
5380 }
5381 }
5382 }
5383 setAssignedValue(value) {
5384 this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
5385 }
5386 shouldBeIncluded(context) {
5387 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
5388 }
5389 /**
5390 * Just deoptimize everything by default so that when e.g. we do not track
5391 * something properly, it is deoptimized.
5392 * @protected
5393 */
5394 applyDeoptimizations() {
5395 this.deoptimized = true;
5396 for (const key of this.keys) {
5397 const value = this[key];
5398 if (value === null)
5399 continue;
5400 if (Array.isArray(value)) {
5401 for (const child of value) {
5402 child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
5403 }
5404 }
5405 else {
5406 value.deoptimizePath(UNKNOWN_PATH);
5407 }
5408 }
5409 this.context.requestTreeshakingPass();
5410 }
5411}
5412
5413class SpreadElement extends NodeBase {
5414 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5415 if (path.length > 0) {
5416 this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
5417 }
5418 }
5419 hasEffects(context) {
5420 if (!this.deoptimized)
5421 this.applyDeoptimizations();
5422 const { propertyReadSideEffects } = this.context.options
5423 .treeshake;
5424 return (this.argument.hasEffects(context) ||
5425 (propertyReadSideEffects &&
5426 (propertyReadSideEffects === 'always' ||
5427 this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
5428 }
5429 applyDeoptimizations() {
5430 this.deoptimized = true;
5431 // Only properties of properties of the argument could become subject to reassignment
5432 // This will also reassign the return values of iterators
5433 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
5434 this.context.requestTreeshakingPass();
5435 }
5436}
5437
5438class Method extends ExpressionEntity {
5439 constructor(description) {
5440 super();
5441 this.description = description;
5442 }
5443 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5444 if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
5445 thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
5446 }
5447 }
5448 getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
5449 if (path.length > 0) {
5450 return UNKNOWN_EXPRESSION;
5451 }
5452 return (this.description.returnsPrimitive ||
5453 (this.description.returns === 'self'
5454 ? thisArg || UNKNOWN_EXPRESSION
5455 : this.description.returns()));
5456 }
5457 hasEffectsOnInteractionAtPath(path, interaction, context) {
5458 var _a, _b;
5459 const { type } = interaction;
5460 if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
5461 return true;
5462 }
5463 if (type === INTERACTION_CALLED) {
5464 if (this.description.mutatesSelfAsArray === true &&
5465 ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
5466 return true;
5467 }
5468 if (this.description.callsArgs) {
5469 for (const argIndex of this.description.callsArgs) {
5470 if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
5471 return true;
5472 }
5473 }
5474 }
5475 }
5476 return false;
5477 }
5478}
5479const METHOD_RETURNS_BOOLEAN = [
5480 new Method({
5481 callsArgs: null,
5482 mutatesSelfAsArray: false,
5483 returns: null,
5484 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
5485 })
5486];
5487const METHOD_RETURNS_STRING = [
5488 new Method({
5489 callsArgs: null,
5490 mutatesSelfAsArray: false,
5491 returns: null,
5492 returnsPrimitive: UNKNOWN_LITERAL_STRING
5493 })
5494];
5495const METHOD_RETURNS_NUMBER = [
5496 new Method({
5497 callsArgs: null,
5498 mutatesSelfAsArray: false,
5499 returns: null,
5500 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5501 })
5502];
5503const METHOD_RETURNS_UNKNOWN = [
5504 new Method({
5505 callsArgs: null,
5506 mutatesSelfAsArray: false,
5507 returns: null,
5508 returnsPrimitive: UNKNOWN_EXPRESSION
5509 })
5510];
5511
5512const INTEGER_REG_EXP = /^\d+$/;
5513class ObjectEntity extends ExpressionEntity {
5514 // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
5515 // and we assume there are no setters or getters
5516 constructor(properties, prototypeExpression, immutable = false) {
5517 super();
5518 this.prototypeExpression = prototypeExpression;
5519 this.immutable = immutable;
5520 this.allProperties = [];
5521 this.deoptimizedPaths = Object.create(null);
5522 this.expressionsToBeDeoptimizedByKey = Object.create(null);
5523 this.gettersByKey = Object.create(null);
5524 this.hasLostTrack = false;
5525 this.hasUnknownDeoptimizedInteger = false;
5526 this.hasUnknownDeoptimizedProperty = false;
5527 this.propertiesAndGettersByKey = Object.create(null);
5528 this.propertiesAndSettersByKey = Object.create(null);
5529 this.settersByKey = Object.create(null);
5530 this.thisParametersToBeDeoptimized = new Set();
5531 this.unknownIntegerProps = [];
5532 this.unmatchableGetters = [];
5533 this.unmatchablePropertiesAndGetters = [];
5534 this.unmatchableSetters = [];
5535 if (Array.isArray(properties)) {
5536 this.buildPropertyMaps(properties);
5537 }
5538 else {
5539 this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
5540 for (const propertiesForKey of Object.values(properties)) {
5541 this.allProperties.push(...propertiesForKey);
5542 }
5543 }
5544 }
5545 deoptimizeAllProperties(noAccessors) {
5546 var _a;
5547 const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
5548 if (noAccessors) {
5549 this.hasUnknownDeoptimizedProperty = true;
5550 }
5551 else {
5552 this.hasLostTrack = true;
5553 }
5554 if (isDeoptimized) {
5555 return;
5556 }
5557 for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
5558 for (const property of properties) {
5559 property.deoptimizePath(UNKNOWN_PATH);
5560 }
5561 }
5562 // While the prototype itself cannot be mutated, each property can
5563 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
5564 this.deoptimizeCachedEntities();
5565 }
5566 deoptimizeIntegerProperties() {
5567 if (this.hasLostTrack ||
5568 this.hasUnknownDeoptimizedProperty ||
5569 this.hasUnknownDeoptimizedInteger) {
5570 return;
5571 }
5572 this.hasUnknownDeoptimizedInteger = true;
5573 for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
5574 if (INTEGER_REG_EXP.test(key)) {
5575 for (const property of propertiesAndGetters) {
5576 property.deoptimizePath(UNKNOWN_PATH);
5577 }
5578 }
5579 }
5580 this.deoptimizeCachedIntegerEntities();
5581 }
5582 // Assumption: If only a specific path is deoptimized, no accessors are created
5583 deoptimizePath(path) {
5584 var _a;
5585 if (this.hasLostTrack || this.immutable) {
5586 return;
5587 }
5588 const key = path[0];
5589 if (path.length === 1) {
5590 if (typeof key !== 'string') {
5591 if (key === UnknownInteger) {
5592 return this.deoptimizeIntegerProperties();
5593 }
5594 return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
5595 }
5596 if (!this.deoptimizedPaths[key]) {
5597 this.deoptimizedPaths[key] = true;
5598 // we only deoptimizeCache exact matches as in all other cases,
5599 // we do not return a literal value or return expression
5600 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
5601 if (expressionsToBeDeoptimized) {
5602 for (const expression of expressionsToBeDeoptimized) {
5603 expression.deoptimizeCache();
5604 }
5605 }
5606 }
5607 }
5608 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
5609 for (const property of typeof key === 'string'
5610 ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
5611 : this.allProperties) {
5612 property.deoptimizePath(subPath);
5613 }
5614 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
5615 }
5616 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5617 var _a;
5618 const [key, ...subPath] = path;
5619 if (this.hasLostTrack ||
5620 // single paths that are deoptimized will not become getters or setters
5621 ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
5622 (this.hasUnknownDeoptimizedProperty ||
5623 (typeof key === 'string' && this.deoptimizedPaths[key])))) {
5624 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
5625 return;
5626 }
5627 const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
5628 ? [
5629 this.propertiesAndGettersByKey,
5630 this.propertiesAndGettersByKey,
5631 this.unmatchablePropertiesAndGetters
5632 ]
5633 : interaction.type === INTERACTION_ACCESSED
5634 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5635 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5636 if (typeof key === 'string') {
5637 if (propertiesForExactMatchByKey[key]) {
5638 const properties = relevantPropertiesByKey[key];
5639 if (properties) {
5640 for (const property of properties) {
5641 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5642 }
5643 }
5644 if (!this.immutable) {
5645 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5646 }
5647 return;
5648 }
5649 for (const property of relevantUnmatchableProperties) {
5650 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5651 }
5652 if (INTEGER_REG_EXP.test(key)) {
5653 for (const property of this.unknownIntegerProps) {
5654 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5655 }
5656 }
5657 }
5658 else {
5659 for (const properties of Object.values(relevantPropertiesByKey).concat([
5660 relevantUnmatchableProperties
5661 ])) {
5662 for (const property of properties) {
5663 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5664 }
5665 }
5666 for (const property of this.unknownIntegerProps) {
5667 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5668 }
5669 }
5670 if (!this.immutable) {
5671 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5672 }
5673 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
5674 }
5675 getLiteralValueAtPath(path, recursionTracker, origin) {
5676 if (path.length === 0) {
5677 return UnknownTruthyValue;
5678 }
5679 const key = path[0];
5680 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5681 if (expressionAtPath) {
5682 return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
5683 }
5684 if (this.prototypeExpression) {
5685 return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
5686 }
5687 if (path.length === 1) {
5688 return undefined;
5689 }
5690 return UnknownValue;
5691 }
5692 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
5693 if (path.length === 0) {
5694 return UNKNOWN_EXPRESSION;
5695 }
5696 const [key, ...subPath] = path;
5697 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5698 if (expressionAtPath) {
5699 return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
5700 }
5701 if (this.prototypeExpression) {
5702 return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
5703 }
5704 return UNKNOWN_EXPRESSION;
5705 }
5706 hasEffectsOnInteractionAtPath(path, interaction, context) {
5707 const [key, ...subPath] = path;
5708 if (subPath.length || interaction.type === INTERACTION_CALLED) {
5709 const expressionAtPath = this.getMemberExpression(key);
5710 if (expressionAtPath) {
5711 return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
5712 }
5713 if (this.prototypeExpression) {
5714 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5715 }
5716 return true;
5717 }
5718 if (key === UnknownNonAccessorKey)
5719 return false;
5720 if (this.hasLostTrack)
5721 return true;
5722 const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
5723 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5724 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5725 if (typeof key === 'string') {
5726 if (propertiesAndAccessorsByKey[key]) {
5727 const accessors = accessorsByKey[key];
5728 if (accessors) {
5729 for (const accessor of accessors) {
5730 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5731 return true;
5732 }
5733 }
5734 return false;
5735 }
5736 for (const accessor of unmatchableAccessors) {
5737 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
5738 return true;
5739 }
5740 }
5741 }
5742 else {
5743 for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
5744 for (const accessor of accessors) {
5745 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5746 return true;
5747 }
5748 }
5749 }
5750 if (this.prototypeExpression) {
5751 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5752 }
5753 return false;
5754 }
5755 buildPropertyMaps(properties) {
5756 const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
5757 const unmatchablePropertiesAndSetters = [];
5758 for (let index = properties.length - 1; index >= 0; index--) {
5759 const { key, kind, property } = properties[index];
5760 allProperties.push(property);
5761 if (typeof key !== 'string') {
5762 if (key === UnknownInteger) {
5763 unknownIntegerProps.push(property);
5764 continue;
5765 }
5766 if (kind === 'set')
5767 unmatchableSetters.push(property);
5768 if (kind === 'get')
5769 unmatchableGetters.push(property);
5770 if (kind !== 'get')
5771 unmatchablePropertiesAndSetters.push(property);
5772 if (kind !== 'set')
5773 unmatchablePropertiesAndGetters.push(property);
5774 }
5775 else {
5776 if (kind === 'set') {
5777 if (!propertiesAndSettersByKey[key]) {
5778 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5779 settersByKey[key] = [property, ...unmatchableSetters];
5780 }
5781 }
5782 else if (kind === 'get') {
5783 if (!propertiesAndGettersByKey[key]) {
5784 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5785 gettersByKey[key] = [property, ...unmatchableGetters];
5786 }
5787 }
5788 else {
5789 if (!propertiesAndSettersByKey[key]) {
5790 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5791 }
5792 if (!propertiesAndGettersByKey[key]) {
5793 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5794 }
5795 }
5796 }
5797 }
5798 }
5799 deoptimizeCachedEntities() {
5800 for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
5801 for (const expression of expressionsToBeDeoptimized) {
5802 expression.deoptimizeCache();
5803 }
5804 }
5805 for (const expression of this.thisParametersToBeDeoptimized) {
5806 expression.deoptimizePath(UNKNOWN_PATH);
5807 }
5808 }
5809 deoptimizeCachedIntegerEntities() {
5810 for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
5811 if (INTEGER_REG_EXP.test(key)) {
5812 for (const expression of expressionsToBeDeoptimized) {
5813 expression.deoptimizeCache();
5814 }
5815 }
5816 }
5817 for (const expression of this.thisParametersToBeDeoptimized) {
5818 expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
5819 }
5820 }
5821 getMemberExpression(key) {
5822 if (this.hasLostTrack ||
5823 this.hasUnknownDeoptimizedProperty ||
5824 typeof key !== 'string' ||
5825 (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
5826 this.deoptimizedPaths[key]) {
5827 return UNKNOWN_EXPRESSION;
5828 }
5829 const properties = this.propertiesAndGettersByKey[key];
5830 if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
5831 return properties[0];
5832 }
5833 if (properties ||
5834 this.unmatchablePropertiesAndGetters.length > 0 ||
5835 (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
5836 return UNKNOWN_EXPRESSION;
5837 }
5838 return null;
5839 }
5840 getMemberExpressionAndTrackDeopt(key, origin) {
5841 if (typeof key !== 'string') {
5842 return UNKNOWN_EXPRESSION;
5843 }
5844 const expression = this.getMemberExpression(key);
5845 if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
5846 const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
5847 this.expressionsToBeDeoptimizedByKey[key] || []);
5848 expressionsToBeDeoptimized.push(origin);
5849 }
5850 return expression;
5851 }
5852}
5853
5854const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
5855// This makes sure unknown properties are not handled as "undefined" but as
5856// "unknown" but without access side effects. An exception is done for numeric
5857// properties as we do not expect new builtin properties to be numbers, this
5858// will improve tree-shaking for out-of-bounds array properties
5859const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
5860 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5861 if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
5862 thisArg.deoptimizePath(UNKNOWN_PATH);
5863 }
5864 }
5865 getLiteralValueAtPath(path) {
5866 // We ignore number properties as we do not expect new properties to be
5867 // numbers and also want to keep handling out-of-bound array elements as
5868 // "undefined"
5869 return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
5870 }
5871 hasEffectsOnInteractionAtPath(path, { type }) {
5872 return path.length > 1 || type === INTERACTION_CALLED;
5873 }
5874})();
5875const OBJECT_PROTOTYPE = new ObjectEntity({
5876 __proto__: null,
5877 hasOwnProperty: METHOD_RETURNS_BOOLEAN,
5878 isPrototypeOf: METHOD_RETURNS_BOOLEAN,
5879 propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
5880 toLocaleString: METHOD_RETURNS_STRING,
5881 toString: METHOD_RETURNS_STRING,
5882 valueOf: METHOD_RETURNS_UNKNOWN
5883}, OBJECT_PROTOTYPE_FALLBACK, true);
5884
5885const NEW_ARRAY_PROPERTIES = [
5886 { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
5887 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
5888];
5889const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
5890 new Method({
5891 callsArgs: [0],
5892 mutatesSelfAsArray: 'deopt-only',
5893 returns: null,
5894 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
5895 })
5896];
5897const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
5898 new Method({
5899 callsArgs: [0],
5900 mutatesSelfAsArray: 'deopt-only',
5901 returns: null,
5902 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5903 })
5904];
5905const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
5906 new Method({
5907 callsArgs: null,
5908 mutatesSelfAsArray: true,
5909 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
5910 returnsPrimitive: null
5911 })
5912];
5913const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
5914 new Method({
5915 callsArgs: null,
5916 mutatesSelfAsArray: 'deopt-only',
5917 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
5918 returnsPrimitive: null
5919 })
5920];
5921const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
5922 new Method({
5923 callsArgs: [0],
5924 mutatesSelfAsArray: 'deopt-only',
5925 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
5926 returnsPrimitive: null
5927 })
5928];
5929const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
5930 new Method({
5931 callsArgs: null,
5932 mutatesSelfAsArray: true,
5933 returns: null,
5934 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5935 })
5936];
5937const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
5938 new Method({
5939 callsArgs: null,
5940 mutatesSelfAsArray: true,
5941 returns: null,
5942 returnsPrimitive: UNKNOWN_EXPRESSION
5943 })
5944];
5945const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
5946 new Method({
5947 callsArgs: null,
5948 mutatesSelfAsArray: 'deopt-only',
5949 returns: null,
5950 returnsPrimitive: UNKNOWN_EXPRESSION
5951 })
5952];
5953const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
5954 new Method({
5955 callsArgs: [0],
5956 mutatesSelfAsArray: 'deopt-only',
5957 returns: null,
5958 returnsPrimitive: UNKNOWN_EXPRESSION
5959 })
5960];
5961const METHOD_MUTATES_SELF_RETURNS_SELF = [
5962 new Method({
5963 callsArgs: null,
5964 mutatesSelfAsArray: true,
5965 returns: 'self',
5966 returnsPrimitive: null
5967 })
5968];
5969const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
5970 new Method({
5971 callsArgs: [0],
5972 mutatesSelfAsArray: true,
5973 returns: 'self',
5974 returnsPrimitive: null
5975 })
5976];
5977const ARRAY_PROTOTYPE = new ObjectEntity({
5978 __proto__: null,
5979 // We assume that accessors have effects as we do not track the accessed value afterwards
5980 at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
5981 concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
5982 copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
5983 entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
5984 every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
5985 fill: METHOD_MUTATES_SELF_RETURNS_SELF,
5986 filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
5987 find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
5988 findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
5989 findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
5990 findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
5991 flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
5992 flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
5993 forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
5994 group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
5995 groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
5996 includes: METHOD_RETURNS_BOOLEAN,
5997 indexOf: METHOD_RETURNS_NUMBER,
5998 join: METHOD_RETURNS_STRING,
5999 keys: METHOD_RETURNS_UNKNOWN,
6000 lastIndexOf: METHOD_RETURNS_NUMBER,
6001 map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6002 pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6003 push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6004 reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6005 reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6006 reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
6007 shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6008 slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6009 some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6010 sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
6011 splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
6012 toLocaleString: METHOD_RETURNS_STRING,
6013 toString: METHOD_RETURNS_STRING,
6014 unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6015 values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
6016}, OBJECT_PROTOTYPE, true);
6017
6018class ArrayExpression extends NodeBase {
6019 constructor() {
6020 super(...arguments);
6021 this.objectEntity = null;
6022 }
6023 deoptimizePath(path) {
6024 this.getObjectEntity().deoptimizePath(path);
6025 }
6026 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6027 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
6028 }
6029 getLiteralValueAtPath(path, recursionTracker, origin) {
6030 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
6031 }
6032 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6033 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6034 }
6035 hasEffectsOnInteractionAtPath(path, interaction, context) {
6036 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
6037 }
6038 applyDeoptimizations() {
6039 this.deoptimized = true;
6040 let hasSpread = false;
6041 for (let index = 0; index < this.elements.length; index++) {
6042 const element = this.elements[index];
6043 if (element) {
6044 if (hasSpread || element instanceof SpreadElement) {
6045 hasSpread = true;
6046 element.deoptimizePath(UNKNOWN_PATH);
6047 }
6048 }
6049 }
6050 this.context.requestTreeshakingPass();
6051 }
6052 getObjectEntity() {
6053 if (this.objectEntity !== null) {
6054 return this.objectEntity;
6055 }
6056 const properties = [
6057 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6058 ];
6059 let hasSpread = false;
6060 for (let index = 0; index < this.elements.length; index++) {
6061 const element = this.elements[index];
6062 if (hasSpread || element instanceof SpreadElement) {
6063 if (element) {
6064 hasSpread = true;
6065 properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
6066 }
6067 }
6068 else if (!element) {
6069 properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
6070 }
6071 else {
6072 properties.push({ key: String(index), kind: 'init', property: element });
6073 }
6074 }
6075 return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
6076 }
6077}
6078
6079class ArrayPattern extends NodeBase {
6080 addExportedVariables(variables, exportNamesByVariable) {
6081 for (const element of this.elements) {
6082 element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
6083 }
6084 }
6085 declare(kind) {
6086 const variables = [];
6087 for (const element of this.elements) {
6088 if (element !== null) {
6089 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
6090 }
6091 }
6092 return variables;
6093 }
6094 // Patterns can only be deoptimized at the empty path at the moment
6095 deoptimizePath() {
6096 for (const element of this.elements) {
6097 element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
6098 }
6099 }
6100 // Patterns are only checked at the emtpy path at the moment
6101 hasEffectsOnInteractionAtPath(_path, interaction, context) {
6102 for (const element of this.elements) {
6103 if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
6104 return true;
6105 }
6106 return false;
6107 }
6108 markDeclarationReached() {
6109 for (const element of this.elements) {
6110 element === null || element === void 0 ? void 0 : element.markDeclarationReached();
6111 }
6112 }
6113}
6114
6115class LocalVariable extends Variable {
6116 constructor(name, declarator, init, context) {
6117 super(name);
6118 this.calledFromTryStatement = false;
6119 this.additionalInitializers = null;
6120 this.expressionsToBeDeoptimized = [];
6121 this.declarations = declarator ? [declarator] : [];
6122 this.init = init;
6123 this.deoptimizationTracker = context.deoptimizationTracker;
6124 this.module = context.module;
6125 }
6126 addDeclaration(identifier, init) {
6127 this.declarations.push(identifier);
6128 const additionalInitializers = this.markInitializersForDeoptimization();
6129 if (init !== null) {
6130 additionalInitializers.push(init);
6131 }
6132 }
6133 consolidateInitializers() {
6134 if (this.additionalInitializers !== null) {
6135 for (const initializer of this.additionalInitializers) {
6136 initializer.deoptimizePath(UNKNOWN_PATH);
6137 }
6138 this.additionalInitializers = null;
6139 }
6140 }
6141 deoptimizePath(path) {
6142 var _a, _b;
6143 if (this.isReassigned ||
6144 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
6145 return;
6146 }
6147 if (path.length === 0) {
6148 if (!this.isReassigned) {
6149 this.isReassigned = true;
6150 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6151 this.expressionsToBeDeoptimized = [];
6152 for (const expression of expressionsToBeDeoptimized) {
6153 expression.deoptimizeCache();
6154 }
6155 (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
6156 }
6157 }
6158 else {
6159 (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
6160 }
6161 }
6162 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6163 if (this.isReassigned || !this.init) {
6164 return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
6165 }
6166 recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
6167 }
6168 getLiteralValueAtPath(path, recursionTracker, origin) {
6169 if (this.isReassigned || !this.init) {
6170 return UnknownValue;
6171 }
6172 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6173 this.expressionsToBeDeoptimized.push(origin);
6174 return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
6175 }, UnknownValue);
6176 }
6177 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6178 if (this.isReassigned || !this.init) {
6179 return UNKNOWN_EXPRESSION;
6180 }
6181 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6182 this.expressionsToBeDeoptimized.push(origin);
6183 return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6184 }, UNKNOWN_EXPRESSION);
6185 }
6186 hasEffectsOnInteractionAtPath(path, interaction, context) {
6187 switch (interaction.type) {
6188 case INTERACTION_ACCESSED:
6189 if (this.isReassigned)
6190 return true;
6191 return (this.init &&
6192 !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
6193 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6194 case INTERACTION_ASSIGNED:
6195 if (this.included)
6196 return true;
6197 if (path.length === 0)
6198 return false;
6199 if (this.isReassigned)
6200 return true;
6201 return (this.init &&
6202 !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
6203 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6204 case INTERACTION_CALLED:
6205 if (this.isReassigned)
6206 return true;
6207 return (this.init &&
6208 !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
6209 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6210 }
6211 }
6212 include() {
6213 if (!this.included) {
6214 this.included = true;
6215 for (const declaration of this.declarations) {
6216 // If node is a default export, it can save a tree-shaking run to include the full declaration now
6217 if (!declaration.included)
6218 declaration.include(createInclusionContext(), false);
6219 let node = declaration.parent;
6220 while (!node.included) {
6221 // We do not want to properly include parents in case they are part of a dead branch
6222 // in which case .include() might pull in more dead code
6223 node.included = true;
6224 if (node.type === Program$1)
6225 break;
6226 node = node.parent;
6227 }
6228 }
6229 }
6230 }
6231 includeCallArguments(context, args) {
6232 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
6233 for (const arg of args) {
6234 arg.include(context, false);
6235 }
6236 }
6237 else if (this.init) {
6238 context.includedCallArguments.add(this.init);
6239 this.init.includeCallArguments(context, args);
6240 context.includedCallArguments.delete(this.init);
6241 }
6242 }
6243 markCalledFromTryStatement() {
6244 this.calledFromTryStatement = true;
6245 }
6246 markInitializersForDeoptimization() {
6247 if (this.additionalInitializers === null) {
6248 this.additionalInitializers = this.init === null ? [] : [this.init];
6249 this.init = UNKNOWN_EXPRESSION;
6250 this.isReassigned = true;
6251 }
6252 return this.additionalInitializers;
6253 }
6254}
6255
6256const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
6257const base = 64;
6258function toBase64(num) {
6259 let outStr = '';
6260 do {
6261 const curDigit = num % base;
6262 num = Math.floor(num / base);
6263 outStr = chars[curDigit] + outStr;
6264 } while (num !== 0);
6265 return outStr;
6266}
6267
6268function getSafeName(baseName, usedNames) {
6269 let safeName = baseName;
6270 let count = 1;
6271 while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
6272 safeName = `${baseName}$${toBase64(count++)}`;
6273 }
6274 usedNames.add(safeName);
6275 return safeName;
6276}
6277
6278class Scope$1 {
6279 constructor() {
6280 this.children = [];
6281 this.variables = new Map();
6282 }
6283 addDeclaration(identifier, context, init, _isHoisted) {
6284 const name = identifier.name;
6285 let variable = this.variables.get(name);
6286 if (variable) {
6287 variable.addDeclaration(identifier, init);
6288 }
6289 else {
6290 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
6291 this.variables.set(name, variable);
6292 }
6293 return variable;
6294 }
6295 contains(name) {
6296 return this.variables.has(name);
6297 }
6298 findVariable(_name) {
6299 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
6300 }
6301}
6302
6303class ChildScope extends Scope$1 {
6304 constructor(parent) {
6305 super();
6306 this.accessedOutsideVariables = new Map();
6307 this.parent = parent;
6308 parent.children.push(this);
6309 }
6310 addAccessedDynamicImport(importExpression) {
6311 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
6312 if (this.parent instanceof ChildScope) {
6313 this.parent.addAccessedDynamicImport(importExpression);
6314 }
6315 }
6316 addAccessedGlobals(globals, accessedGlobalsByScope) {
6317 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
6318 for (const name of globals) {
6319 accessedGlobals.add(name);
6320 }
6321 accessedGlobalsByScope.set(this, accessedGlobals);
6322 if (this.parent instanceof ChildScope) {
6323 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
6324 }
6325 }
6326 addNamespaceMemberAccess(name, variable) {
6327 this.accessedOutsideVariables.set(name, variable);
6328 this.parent.addNamespaceMemberAccess(name, variable);
6329 }
6330 addReturnExpression(expression) {
6331 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
6332 }
6333 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
6334 for (const variable of this.accessedOutsideVariables.values()) {
6335 if (variable.included) {
6336 usedNames.add(variable.getBaseVariableName());
6337 if (format === 'system' && exportNamesByVariable.has(variable)) {
6338 usedNames.add('exports');
6339 }
6340 }
6341 }
6342 const accessedGlobals = accessedGlobalsByScope.get(this);
6343 if (accessedGlobals) {
6344 for (const name of accessedGlobals) {
6345 usedNames.add(name);
6346 }
6347 }
6348 }
6349 contains(name) {
6350 return this.variables.has(name) || this.parent.contains(name);
6351 }
6352 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
6353 const usedNames = new Set();
6354 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
6355 if (this.accessedDynamicImports) {
6356 for (const importExpression of this.accessedDynamicImports) {
6357 if (importExpression.inlineNamespace) {
6358 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
6359 }
6360 }
6361 }
6362 for (const [name, variable] of this.variables) {
6363 if (variable.included || variable.alwaysRendered) {
6364 variable.setRenderNames(null, getSafeName(name, usedNames));
6365 }
6366 }
6367 for (const scope of this.children) {
6368 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
6369 }
6370 }
6371 findLexicalBoundary() {
6372 return this.parent.findLexicalBoundary();
6373 }
6374 findVariable(name) {
6375 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
6376 if (knownVariable) {
6377 return knownVariable;
6378 }
6379 const variable = this.parent.findVariable(name);
6380 this.accessedOutsideVariables.set(name, variable);
6381 return variable;
6382 }
6383}
6384
6385class ParameterScope extends ChildScope {
6386 constructor(parent, context) {
6387 super(parent);
6388 this.parameters = [];
6389 this.hasRest = false;
6390 this.context = context;
6391 this.hoistedBodyVarScope = new ChildScope(this);
6392 }
6393 /**
6394 * Adds a parameter to this scope. Parameters must be added in the correct
6395 * order, e.g. from left to right.
6396 */
6397 addParameterDeclaration(identifier) {
6398 const name = identifier.name;
6399 let variable = this.hoistedBodyVarScope.variables.get(name);
6400 if (variable) {
6401 variable.addDeclaration(identifier, null);
6402 }
6403 else {
6404 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
6405 }
6406 this.variables.set(name, variable);
6407 return variable;
6408 }
6409 addParameterVariables(parameters, hasRest) {
6410 this.parameters = parameters;
6411 for (const parameterList of parameters) {
6412 for (const parameter of parameterList) {
6413 parameter.alwaysRendered = true;
6414 }
6415 }
6416 this.hasRest = hasRest;
6417 }
6418 includeCallArguments(context, args) {
6419 let calledFromTryStatement = false;
6420 let argIncluded = false;
6421 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
6422 for (const checkedArg of args) {
6423 if (checkedArg instanceof SpreadElement) {
6424 for (const arg of args) {
6425 arg.include(context, false);
6426 }
6427 break;
6428 }
6429 }
6430 for (let index = args.length - 1; index >= 0; index--) {
6431 const paramVars = this.parameters[index] || restParam;
6432 const arg = args[index];
6433 if (paramVars) {
6434 calledFromTryStatement = false;
6435 if (paramVars.length === 0) {
6436 // handle empty destructuring
6437 argIncluded = true;
6438 }
6439 else {
6440 for (const variable of paramVars) {
6441 if (variable.included) {
6442 argIncluded = true;
6443 }
6444 if (variable.calledFromTryStatement) {
6445 calledFromTryStatement = true;
6446 }
6447 }
6448 }
6449 }
6450 if (!argIncluded && arg.shouldBeIncluded(context)) {
6451 argIncluded = true;
6452 }
6453 if (argIncluded) {
6454 arg.include(context, calledFromTryStatement);
6455 }
6456 }
6457 }
6458}
6459
6460class ReturnValueScope extends ParameterScope {
6461 constructor() {
6462 super(...arguments);
6463 this.returnExpression = null;
6464 this.returnExpressions = [];
6465 }
6466 addReturnExpression(expression) {
6467 this.returnExpressions.push(expression);
6468 }
6469 getReturnExpression() {
6470 if (this.returnExpression === null)
6471 this.updateReturnExpression();
6472 return this.returnExpression;
6473 }
6474 updateReturnExpression() {
6475 if (this.returnExpressions.length === 1) {
6476 this.returnExpression = this.returnExpressions[0];
6477 }
6478 else {
6479 this.returnExpression = UNKNOWN_EXPRESSION;
6480 for (const expression of this.returnExpressions) {
6481 expression.deoptimizePath(UNKNOWN_PATH);
6482 }
6483 }
6484 }
6485}
6486
6487//@ts-check
6488/** @typedef { import('estree').Node} Node */
6489/** @typedef {Node | {
6490 * type: 'PropertyDefinition';
6491 * computed: boolean;
6492 * value: Node
6493 * }} NodeWithPropertyDefinition */
6494
6495/**
6496 *
6497 * @param {NodeWithPropertyDefinition} node
6498 * @param {NodeWithPropertyDefinition} parent
6499 * @returns boolean
6500 */
6501function is_reference (node, parent) {
6502 if (node.type === 'MemberExpression') {
6503 return !node.computed && is_reference(node.object, node);
6504 }
6505
6506 if (node.type === 'Identifier') {
6507 if (!parent) return true;
6508
6509 switch (parent.type) {
6510 // disregard `bar` in `foo.bar`
6511 case 'MemberExpression': return parent.computed || node === parent.object;
6512
6513 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
6514 case 'MethodDefinition': return parent.computed;
6515
6516 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
6517 case 'PropertyDefinition': return parent.computed || node === parent.value;
6518
6519 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6520 case 'Property': return parent.computed || node === parent.value;
6521
6522 // disregard the `bar` in `export { foo as bar }` or
6523 // the foo in `import { foo as bar }`
6524 case 'ExportSpecifier':
6525 case 'ImportSpecifier': return node === parent.local;
6526
6527 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
6528 case 'LabeledStatement':
6529 case 'BreakStatement':
6530 case 'ContinueStatement': return false;
6531 default: return true;
6532 }
6533 }
6534
6535 return false;
6536}
6537
6538/* eslint sort-keys: "off" */
6539const ValueProperties = Symbol('Value Properties');
6540const PURE = {
6541 hasEffectsWhenCalled() {
6542 return false;
6543 }
6544};
6545const IMPURE = {
6546 hasEffectsWhenCalled() {
6547 return true;
6548 }
6549};
6550// We use shortened variables to reduce file size here
6551/* OBJECT */
6552const O = {
6553 __proto__: null,
6554 [ValueProperties]: IMPURE
6555};
6556/* PURE FUNCTION */
6557const PF = {
6558 __proto__: null,
6559 [ValueProperties]: PURE
6560};
6561/* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
6562const MUTATES_ARG_WITHOUT_ACCESSOR = {
6563 __proto__: null,
6564 [ValueProperties]: {
6565 hasEffectsWhenCalled({ args }, context) {
6566 return (!args.length ||
6567 args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
6568 }
6569 }
6570};
6571/* CONSTRUCTOR */
6572const C = {
6573 __proto__: null,
6574 [ValueProperties]: IMPURE,
6575 prototype: O
6576};
6577/* PURE CONSTRUCTOR */
6578const PC = {
6579 __proto__: null,
6580 [ValueProperties]: PURE,
6581 prototype: O
6582};
6583const ARRAY_TYPE = {
6584 __proto__: null,
6585 [ValueProperties]: PURE,
6586 from: PF,
6587 of: PF,
6588 prototype: O
6589};
6590const INTL_MEMBER = {
6591 __proto__: null,
6592 [ValueProperties]: PURE,
6593 supportedLocalesOf: PC
6594};
6595const knownGlobals = {
6596 // Placeholders for global objects to avoid shape mutations
6597 global: O,
6598 globalThis: O,
6599 self: O,
6600 window: O,
6601 // Common globals
6602 __proto__: null,
6603 [ValueProperties]: IMPURE,
6604 Array: {
6605 __proto__: null,
6606 [ValueProperties]: IMPURE,
6607 from: O,
6608 isArray: PF,
6609 of: PF,
6610 prototype: O
6611 },
6612 ArrayBuffer: {
6613 __proto__: null,
6614 [ValueProperties]: PURE,
6615 isView: PF,
6616 prototype: O
6617 },
6618 Atomics: O,
6619 BigInt: C,
6620 BigInt64Array: C,
6621 BigUint64Array: C,
6622 Boolean: PC,
6623 constructor: C,
6624 DataView: PC,
6625 Date: {
6626 __proto__: null,
6627 [ValueProperties]: PURE,
6628 now: PF,
6629 parse: PF,
6630 prototype: O,
6631 UTC: PF
6632 },
6633 decodeURI: PF,
6634 decodeURIComponent: PF,
6635 encodeURI: PF,
6636 encodeURIComponent: PF,
6637 Error: PC,
6638 escape: PF,
6639 eval: O,
6640 EvalError: PC,
6641 Float32Array: ARRAY_TYPE,
6642 Float64Array: ARRAY_TYPE,
6643 Function: C,
6644 hasOwnProperty: O,
6645 Infinity: O,
6646 Int16Array: ARRAY_TYPE,
6647 Int32Array: ARRAY_TYPE,
6648 Int8Array: ARRAY_TYPE,
6649 isFinite: PF,
6650 isNaN: PF,
6651 isPrototypeOf: O,
6652 JSON: O,
6653 Map: PC,
6654 Math: {
6655 __proto__: null,
6656 [ValueProperties]: IMPURE,
6657 abs: PF,
6658 acos: PF,
6659 acosh: PF,
6660 asin: PF,
6661 asinh: PF,
6662 atan: PF,
6663 atan2: PF,
6664 atanh: PF,
6665 cbrt: PF,
6666 ceil: PF,
6667 clz32: PF,
6668 cos: PF,
6669 cosh: PF,
6670 exp: PF,
6671 expm1: PF,
6672 floor: PF,
6673 fround: PF,
6674 hypot: PF,
6675 imul: PF,
6676 log: PF,
6677 log10: PF,
6678 log1p: PF,
6679 log2: PF,
6680 max: PF,
6681 min: PF,
6682 pow: PF,
6683 random: PF,
6684 round: PF,
6685 sign: PF,
6686 sin: PF,
6687 sinh: PF,
6688 sqrt: PF,
6689 tan: PF,
6690 tanh: PF,
6691 trunc: PF
6692 },
6693 NaN: O,
6694 Number: {
6695 __proto__: null,
6696 [ValueProperties]: PURE,
6697 isFinite: PF,
6698 isInteger: PF,
6699 isNaN: PF,
6700 isSafeInteger: PF,
6701 parseFloat: PF,
6702 parseInt: PF,
6703 prototype: O
6704 },
6705 Object: {
6706 __proto__: null,
6707 [ValueProperties]: PURE,
6708 create: PF,
6709 // Technically those can throw in certain situations, but we ignore this as
6710 // code that relies on this will hopefully wrap this in a try-catch, which
6711 // deoptimizes everything anyway
6712 defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
6713 defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
6714 getOwnPropertyDescriptor: PF,
6715 getOwnPropertyNames: PF,
6716 getOwnPropertySymbols: PF,
6717 getPrototypeOf: PF,
6718 hasOwn: PF,
6719 is: PF,
6720 isExtensible: PF,
6721 isFrozen: PF,
6722 isSealed: PF,
6723 keys: PF,
6724 fromEntries: PF,
6725 entries: PF,
6726 prototype: O
6727 },
6728 parseFloat: PF,
6729 parseInt: PF,
6730 Promise: {
6731 __proto__: null,
6732 [ValueProperties]: IMPURE,
6733 all: O,
6734 prototype: O,
6735 race: O,
6736 reject: O,
6737 resolve: O
6738 },
6739 propertyIsEnumerable: O,
6740 Proxy: O,
6741 RangeError: PC,
6742 ReferenceError: PC,
6743 Reflect: O,
6744 RegExp: PC,
6745 Set: PC,
6746 SharedArrayBuffer: C,
6747 String: {
6748 __proto__: null,
6749 [ValueProperties]: PURE,
6750 fromCharCode: PF,
6751 fromCodePoint: PF,
6752 prototype: O,
6753 raw: PF
6754 },
6755 Symbol: {
6756 __proto__: null,
6757 [ValueProperties]: PURE,
6758 for: PF,
6759 keyFor: PF,
6760 prototype: O
6761 },
6762 SyntaxError: PC,
6763 toLocaleString: O,
6764 toString: O,
6765 TypeError: PC,
6766 Uint16Array: ARRAY_TYPE,
6767 Uint32Array: ARRAY_TYPE,
6768 Uint8Array: ARRAY_TYPE,
6769 Uint8ClampedArray: ARRAY_TYPE,
6770 // Technically, this is a global, but it needs special handling
6771 // undefined: ?,
6772 unescape: PF,
6773 URIError: PC,
6774 valueOf: O,
6775 WeakMap: PC,
6776 WeakSet: PC,
6777 // Additional globals shared by Node and Browser that are not strictly part of the language
6778 clearInterval: C,
6779 clearTimeout: C,
6780 console: O,
6781 Intl: {
6782 __proto__: null,
6783 [ValueProperties]: IMPURE,
6784 Collator: INTL_MEMBER,
6785 DateTimeFormat: INTL_MEMBER,
6786 ListFormat: INTL_MEMBER,
6787 NumberFormat: INTL_MEMBER,
6788 PluralRules: INTL_MEMBER,
6789 RelativeTimeFormat: INTL_MEMBER
6790 },
6791 setInterval: C,
6792 setTimeout: C,
6793 TextDecoder: C,
6794 TextEncoder: C,
6795 URL: C,
6796 URLSearchParams: C,
6797 // Browser specific globals
6798 AbortController: C,
6799 AbortSignal: C,
6800 addEventListener: O,
6801 alert: O,
6802 AnalyserNode: C,
6803 Animation: C,
6804 AnimationEvent: C,
6805 applicationCache: O,
6806 ApplicationCache: C,
6807 ApplicationCacheErrorEvent: C,
6808 atob: O,
6809 Attr: C,
6810 Audio: C,
6811 AudioBuffer: C,
6812 AudioBufferSourceNode: C,
6813 AudioContext: C,
6814 AudioDestinationNode: C,
6815 AudioListener: C,
6816 AudioNode: C,
6817 AudioParam: C,
6818 AudioProcessingEvent: C,
6819 AudioScheduledSourceNode: C,
6820 AudioWorkletNode: C,
6821 BarProp: C,
6822 BaseAudioContext: C,
6823 BatteryManager: C,
6824 BeforeUnloadEvent: C,
6825 BiquadFilterNode: C,
6826 Blob: C,
6827 BlobEvent: C,
6828 blur: O,
6829 BroadcastChannel: C,
6830 btoa: O,
6831 ByteLengthQueuingStrategy: C,
6832 Cache: C,
6833 caches: O,
6834 CacheStorage: C,
6835 cancelAnimationFrame: O,
6836 cancelIdleCallback: O,
6837 CanvasCaptureMediaStreamTrack: C,
6838 CanvasGradient: C,
6839 CanvasPattern: C,
6840 CanvasRenderingContext2D: C,
6841 ChannelMergerNode: C,
6842 ChannelSplitterNode: C,
6843 CharacterData: C,
6844 clientInformation: O,
6845 ClipboardEvent: C,
6846 close: O,
6847 closed: O,
6848 CloseEvent: C,
6849 Comment: C,
6850 CompositionEvent: C,
6851 confirm: O,
6852 ConstantSourceNode: C,
6853 ConvolverNode: C,
6854 CountQueuingStrategy: C,
6855 createImageBitmap: O,
6856 Credential: C,
6857 CredentialsContainer: C,
6858 crypto: O,
6859 Crypto: C,
6860 CryptoKey: C,
6861 CSS: C,
6862 CSSConditionRule: C,
6863 CSSFontFaceRule: C,
6864 CSSGroupingRule: C,
6865 CSSImportRule: C,
6866 CSSKeyframeRule: C,
6867 CSSKeyframesRule: C,
6868 CSSMediaRule: C,
6869 CSSNamespaceRule: C,
6870 CSSPageRule: C,
6871 CSSRule: C,
6872 CSSRuleList: C,
6873 CSSStyleDeclaration: C,
6874 CSSStyleRule: C,
6875 CSSStyleSheet: C,
6876 CSSSupportsRule: C,
6877 CustomElementRegistry: C,
6878 customElements: O,
6879 CustomEvent: C,
6880 DataTransfer: C,
6881 DataTransferItem: C,
6882 DataTransferItemList: C,
6883 defaultstatus: O,
6884 defaultStatus: O,
6885 DelayNode: C,
6886 DeviceMotionEvent: C,
6887 DeviceOrientationEvent: C,
6888 devicePixelRatio: O,
6889 dispatchEvent: O,
6890 document: O,
6891 Document: C,
6892 DocumentFragment: C,
6893 DocumentType: C,
6894 DOMError: C,
6895 DOMException: C,
6896 DOMImplementation: C,
6897 DOMMatrix: C,
6898 DOMMatrixReadOnly: C,
6899 DOMParser: C,
6900 DOMPoint: C,
6901 DOMPointReadOnly: C,
6902 DOMQuad: C,
6903 DOMRect: C,
6904 DOMRectReadOnly: C,
6905 DOMStringList: C,
6906 DOMStringMap: C,
6907 DOMTokenList: C,
6908 DragEvent: C,
6909 DynamicsCompressorNode: C,
6910 Element: C,
6911 ErrorEvent: C,
6912 Event: C,
6913 EventSource: C,
6914 EventTarget: C,
6915 external: O,
6916 fetch: O,
6917 File: C,
6918 FileList: C,
6919 FileReader: C,
6920 find: O,
6921 focus: O,
6922 FocusEvent: C,
6923 FontFace: C,
6924 FontFaceSetLoadEvent: C,
6925 FormData: C,
6926 frames: O,
6927 GainNode: C,
6928 Gamepad: C,
6929 GamepadButton: C,
6930 GamepadEvent: C,
6931 getComputedStyle: O,
6932 getSelection: O,
6933 HashChangeEvent: C,
6934 Headers: C,
6935 history: O,
6936 History: C,
6937 HTMLAllCollection: C,
6938 HTMLAnchorElement: C,
6939 HTMLAreaElement: C,
6940 HTMLAudioElement: C,
6941 HTMLBaseElement: C,
6942 HTMLBodyElement: C,
6943 HTMLBRElement: C,
6944 HTMLButtonElement: C,
6945 HTMLCanvasElement: C,
6946 HTMLCollection: C,
6947 HTMLContentElement: C,
6948 HTMLDataElement: C,
6949 HTMLDataListElement: C,
6950 HTMLDetailsElement: C,
6951 HTMLDialogElement: C,
6952 HTMLDirectoryElement: C,
6953 HTMLDivElement: C,
6954 HTMLDListElement: C,
6955 HTMLDocument: C,
6956 HTMLElement: C,
6957 HTMLEmbedElement: C,
6958 HTMLFieldSetElement: C,
6959 HTMLFontElement: C,
6960 HTMLFormControlsCollection: C,
6961 HTMLFormElement: C,
6962 HTMLFrameElement: C,
6963 HTMLFrameSetElement: C,
6964 HTMLHeadElement: C,
6965 HTMLHeadingElement: C,
6966 HTMLHRElement: C,
6967 HTMLHtmlElement: C,
6968 HTMLIFrameElement: C,
6969 HTMLImageElement: C,
6970 HTMLInputElement: C,
6971 HTMLLabelElement: C,
6972 HTMLLegendElement: C,
6973 HTMLLIElement: C,
6974 HTMLLinkElement: C,
6975 HTMLMapElement: C,
6976 HTMLMarqueeElement: C,
6977 HTMLMediaElement: C,
6978 HTMLMenuElement: C,
6979 HTMLMetaElement: C,
6980 HTMLMeterElement: C,
6981 HTMLModElement: C,
6982 HTMLObjectElement: C,
6983 HTMLOListElement: C,
6984 HTMLOptGroupElement: C,
6985 HTMLOptionElement: C,
6986 HTMLOptionsCollection: C,
6987 HTMLOutputElement: C,
6988 HTMLParagraphElement: C,
6989 HTMLParamElement: C,
6990 HTMLPictureElement: C,
6991 HTMLPreElement: C,
6992 HTMLProgressElement: C,
6993 HTMLQuoteElement: C,
6994 HTMLScriptElement: C,
6995 HTMLSelectElement: C,
6996 HTMLShadowElement: C,
6997 HTMLSlotElement: C,
6998 HTMLSourceElement: C,
6999 HTMLSpanElement: C,
7000 HTMLStyleElement: C,
7001 HTMLTableCaptionElement: C,
7002 HTMLTableCellElement: C,
7003 HTMLTableColElement: C,
7004 HTMLTableElement: C,
7005 HTMLTableRowElement: C,
7006 HTMLTableSectionElement: C,
7007 HTMLTemplateElement: C,
7008 HTMLTextAreaElement: C,
7009 HTMLTimeElement: C,
7010 HTMLTitleElement: C,
7011 HTMLTrackElement: C,
7012 HTMLUListElement: C,
7013 HTMLUnknownElement: C,
7014 HTMLVideoElement: C,
7015 IDBCursor: C,
7016 IDBCursorWithValue: C,
7017 IDBDatabase: C,
7018 IDBFactory: C,
7019 IDBIndex: C,
7020 IDBKeyRange: C,
7021 IDBObjectStore: C,
7022 IDBOpenDBRequest: C,
7023 IDBRequest: C,
7024 IDBTransaction: C,
7025 IDBVersionChangeEvent: C,
7026 IdleDeadline: C,
7027 IIRFilterNode: C,
7028 Image: C,
7029 ImageBitmap: C,
7030 ImageBitmapRenderingContext: C,
7031 ImageCapture: C,
7032 ImageData: C,
7033 indexedDB: O,
7034 innerHeight: O,
7035 innerWidth: O,
7036 InputEvent: C,
7037 IntersectionObserver: C,
7038 IntersectionObserverEntry: C,
7039 isSecureContext: O,
7040 KeyboardEvent: C,
7041 KeyframeEffect: C,
7042 length: O,
7043 localStorage: O,
7044 location: O,
7045 Location: C,
7046 locationbar: O,
7047 matchMedia: O,
7048 MediaDeviceInfo: C,
7049 MediaDevices: C,
7050 MediaElementAudioSourceNode: C,
7051 MediaEncryptedEvent: C,
7052 MediaError: C,
7053 MediaKeyMessageEvent: C,
7054 MediaKeySession: C,
7055 MediaKeyStatusMap: C,
7056 MediaKeySystemAccess: C,
7057 MediaList: C,
7058 MediaQueryList: C,
7059 MediaQueryListEvent: C,
7060 MediaRecorder: C,
7061 MediaSettingsRange: C,
7062 MediaSource: C,
7063 MediaStream: C,
7064 MediaStreamAudioDestinationNode: C,
7065 MediaStreamAudioSourceNode: C,
7066 MediaStreamEvent: C,
7067 MediaStreamTrack: C,
7068 MediaStreamTrackEvent: C,
7069 menubar: O,
7070 MessageChannel: C,
7071 MessageEvent: C,
7072 MessagePort: C,
7073 MIDIAccess: C,
7074 MIDIConnectionEvent: C,
7075 MIDIInput: C,
7076 MIDIInputMap: C,
7077 MIDIMessageEvent: C,
7078 MIDIOutput: C,
7079 MIDIOutputMap: C,
7080 MIDIPort: C,
7081 MimeType: C,
7082 MimeTypeArray: C,
7083 MouseEvent: C,
7084 moveBy: O,
7085 moveTo: O,
7086 MutationEvent: C,
7087 MutationObserver: C,
7088 MutationRecord: C,
7089 name: O,
7090 NamedNodeMap: C,
7091 NavigationPreloadManager: C,
7092 navigator: O,
7093 Navigator: C,
7094 NetworkInformation: C,
7095 Node: C,
7096 NodeFilter: O,
7097 NodeIterator: C,
7098 NodeList: C,
7099 Notification: C,
7100 OfflineAudioCompletionEvent: C,
7101 OfflineAudioContext: C,
7102 offscreenBuffering: O,
7103 OffscreenCanvas: C,
7104 open: O,
7105 openDatabase: O,
7106 Option: C,
7107 origin: O,
7108 OscillatorNode: C,
7109 outerHeight: O,
7110 outerWidth: O,
7111 PageTransitionEvent: C,
7112 pageXOffset: O,
7113 pageYOffset: O,
7114 PannerNode: C,
7115 parent: O,
7116 Path2D: C,
7117 PaymentAddress: C,
7118 PaymentRequest: C,
7119 PaymentRequestUpdateEvent: C,
7120 PaymentResponse: C,
7121 performance: O,
7122 Performance: C,
7123 PerformanceEntry: C,
7124 PerformanceLongTaskTiming: C,
7125 PerformanceMark: C,
7126 PerformanceMeasure: C,
7127 PerformanceNavigation: C,
7128 PerformanceNavigationTiming: C,
7129 PerformanceObserver: C,
7130 PerformanceObserverEntryList: C,
7131 PerformancePaintTiming: C,
7132 PerformanceResourceTiming: C,
7133 PerformanceTiming: C,
7134 PeriodicWave: C,
7135 Permissions: C,
7136 PermissionStatus: C,
7137 personalbar: O,
7138 PhotoCapabilities: C,
7139 Plugin: C,
7140 PluginArray: C,
7141 PointerEvent: C,
7142 PopStateEvent: C,
7143 postMessage: O,
7144 Presentation: C,
7145 PresentationAvailability: C,
7146 PresentationConnection: C,
7147 PresentationConnectionAvailableEvent: C,
7148 PresentationConnectionCloseEvent: C,
7149 PresentationConnectionList: C,
7150 PresentationReceiver: C,
7151 PresentationRequest: C,
7152 print: O,
7153 ProcessingInstruction: C,
7154 ProgressEvent: C,
7155 PromiseRejectionEvent: C,
7156 prompt: O,
7157 PushManager: C,
7158 PushSubscription: C,
7159 PushSubscriptionOptions: C,
7160 queueMicrotask: O,
7161 RadioNodeList: C,
7162 Range: C,
7163 ReadableStream: C,
7164 RemotePlayback: C,
7165 removeEventListener: O,
7166 Request: C,
7167 requestAnimationFrame: O,
7168 requestIdleCallback: O,
7169 resizeBy: O,
7170 ResizeObserver: C,
7171 ResizeObserverEntry: C,
7172 resizeTo: O,
7173 Response: C,
7174 RTCCertificate: C,
7175 RTCDataChannel: C,
7176 RTCDataChannelEvent: C,
7177 RTCDtlsTransport: C,
7178 RTCIceCandidate: C,
7179 RTCIceTransport: C,
7180 RTCPeerConnection: C,
7181 RTCPeerConnectionIceEvent: C,
7182 RTCRtpReceiver: C,
7183 RTCRtpSender: C,
7184 RTCSctpTransport: C,
7185 RTCSessionDescription: C,
7186 RTCStatsReport: C,
7187 RTCTrackEvent: C,
7188 screen: O,
7189 Screen: C,
7190 screenLeft: O,
7191 ScreenOrientation: C,
7192 screenTop: O,
7193 screenX: O,
7194 screenY: O,
7195 ScriptProcessorNode: C,
7196 scroll: O,
7197 scrollbars: O,
7198 scrollBy: O,
7199 scrollTo: O,
7200 scrollX: O,
7201 scrollY: O,
7202 SecurityPolicyViolationEvent: C,
7203 Selection: C,
7204 ServiceWorker: C,
7205 ServiceWorkerContainer: C,
7206 ServiceWorkerRegistration: C,
7207 sessionStorage: O,
7208 ShadowRoot: C,
7209 SharedWorker: C,
7210 SourceBuffer: C,
7211 SourceBufferList: C,
7212 speechSynthesis: O,
7213 SpeechSynthesisEvent: C,
7214 SpeechSynthesisUtterance: C,
7215 StaticRange: C,
7216 status: O,
7217 statusbar: O,
7218 StereoPannerNode: C,
7219 stop: O,
7220 Storage: C,
7221 StorageEvent: C,
7222 StorageManager: C,
7223 styleMedia: O,
7224 StyleSheet: C,
7225 StyleSheetList: C,
7226 SubtleCrypto: C,
7227 SVGAElement: C,
7228 SVGAngle: C,
7229 SVGAnimatedAngle: C,
7230 SVGAnimatedBoolean: C,
7231 SVGAnimatedEnumeration: C,
7232 SVGAnimatedInteger: C,
7233 SVGAnimatedLength: C,
7234 SVGAnimatedLengthList: C,
7235 SVGAnimatedNumber: C,
7236 SVGAnimatedNumberList: C,
7237 SVGAnimatedPreserveAspectRatio: C,
7238 SVGAnimatedRect: C,
7239 SVGAnimatedString: C,
7240 SVGAnimatedTransformList: C,
7241 SVGAnimateElement: C,
7242 SVGAnimateMotionElement: C,
7243 SVGAnimateTransformElement: C,
7244 SVGAnimationElement: C,
7245 SVGCircleElement: C,
7246 SVGClipPathElement: C,
7247 SVGComponentTransferFunctionElement: C,
7248 SVGDefsElement: C,
7249 SVGDescElement: C,
7250 SVGDiscardElement: C,
7251 SVGElement: C,
7252 SVGEllipseElement: C,
7253 SVGFEBlendElement: C,
7254 SVGFEColorMatrixElement: C,
7255 SVGFEComponentTransferElement: C,
7256 SVGFECompositeElement: C,
7257 SVGFEConvolveMatrixElement: C,
7258 SVGFEDiffuseLightingElement: C,
7259 SVGFEDisplacementMapElement: C,
7260 SVGFEDistantLightElement: C,
7261 SVGFEDropShadowElement: C,
7262 SVGFEFloodElement: C,
7263 SVGFEFuncAElement: C,
7264 SVGFEFuncBElement: C,
7265 SVGFEFuncGElement: C,
7266 SVGFEFuncRElement: C,
7267 SVGFEGaussianBlurElement: C,
7268 SVGFEImageElement: C,
7269 SVGFEMergeElement: C,
7270 SVGFEMergeNodeElement: C,
7271 SVGFEMorphologyElement: C,
7272 SVGFEOffsetElement: C,
7273 SVGFEPointLightElement: C,
7274 SVGFESpecularLightingElement: C,
7275 SVGFESpotLightElement: C,
7276 SVGFETileElement: C,
7277 SVGFETurbulenceElement: C,
7278 SVGFilterElement: C,
7279 SVGForeignObjectElement: C,
7280 SVGGElement: C,
7281 SVGGeometryElement: C,
7282 SVGGradientElement: C,
7283 SVGGraphicsElement: C,
7284 SVGImageElement: C,
7285 SVGLength: C,
7286 SVGLengthList: C,
7287 SVGLinearGradientElement: C,
7288 SVGLineElement: C,
7289 SVGMarkerElement: C,
7290 SVGMaskElement: C,
7291 SVGMatrix: C,
7292 SVGMetadataElement: C,
7293 SVGMPathElement: C,
7294 SVGNumber: C,
7295 SVGNumberList: C,
7296 SVGPathElement: C,
7297 SVGPatternElement: C,
7298 SVGPoint: C,
7299 SVGPointList: C,
7300 SVGPolygonElement: C,
7301 SVGPolylineElement: C,
7302 SVGPreserveAspectRatio: C,
7303 SVGRadialGradientElement: C,
7304 SVGRect: C,
7305 SVGRectElement: C,
7306 SVGScriptElement: C,
7307 SVGSetElement: C,
7308 SVGStopElement: C,
7309 SVGStringList: C,
7310 SVGStyleElement: C,
7311 SVGSVGElement: C,
7312 SVGSwitchElement: C,
7313 SVGSymbolElement: C,
7314 SVGTextContentElement: C,
7315 SVGTextElement: C,
7316 SVGTextPathElement: C,
7317 SVGTextPositioningElement: C,
7318 SVGTitleElement: C,
7319 SVGTransform: C,
7320 SVGTransformList: C,
7321 SVGTSpanElement: C,
7322 SVGUnitTypes: C,
7323 SVGUseElement: C,
7324 SVGViewElement: C,
7325 TaskAttributionTiming: C,
7326 Text: C,
7327 TextEvent: C,
7328 TextMetrics: C,
7329 TextTrack: C,
7330 TextTrackCue: C,
7331 TextTrackCueList: C,
7332 TextTrackList: C,
7333 TimeRanges: C,
7334 toolbar: O,
7335 top: O,
7336 Touch: C,
7337 TouchEvent: C,
7338 TouchList: C,
7339 TrackEvent: C,
7340 TransitionEvent: C,
7341 TreeWalker: C,
7342 UIEvent: C,
7343 ValidityState: C,
7344 visualViewport: O,
7345 VisualViewport: C,
7346 VTTCue: C,
7347 WaveShaperNode: C,
7348 WebAssembly: O,
7349 WebGL2RenderingContext: C,
7350 WebGLActiveInfo: C,
7351 WebGLBuffer: C,
7352 WebGLContextEvent: C,
7353 WebGLFramebuffer: C,
7354 WebGLProgram: C,
7355 WebGLQuery: C,
7356 WebGLRenderbuffer: C,
7357 WebGLRenderingContext: C,
7358 WebGLSampler: C,
7359 WebGLShader: C,
7360 WebGLShaderPrecisionFormat: C,
7361 WebGLSync: C,
7362 WebGLTexture: C,
7363 WebGLTransformFeedback: C,
7364 WebGLUniformLocation: C,
7365 WebGLVertexArrayObject: C,
7366 WebSocket: C,
7367 WheelEvent: C,
7368 Window: C,
7369 Worker: C,
7370 WritableStream: C,
7371 XMLDocument: C,
7372 XMLHttpRequest: C,
7373 XMLHttpRequestEventTarget: C,
7374 XMLHttpRequestUpload: C,
7375 XMLSerializer: C,
7376 XPathEvaluator: C,
7377 XPathExpression: C,
7378 XPathResult: C,
7379 XSLTProcessor: C
7380};
7381for (const global of ['window', 'global', 'self', 'globalThis']) {
7382 knownGlobals[global] = knownGlobals;
7383}
7384function getGlobalAtPath(path) {
7385 let currentGlobal = knownGlobals;
7386 for (const pathSegment of path) {
7387 if (typeof pathSegment !== 'string') {
7388 return null;
7389 }
7390 currentGlobal = currentGlobal[pathSegment];
7391 if (!currentGlobal) {
7392 return null;
7393 }
7394 }
7395 return currentGlobal[ValueProperties];
7396}
7397
7398class GlobalVariable extends Variable {
7399 constructor() {
7400 super(...arguments);
7401 // Ensure we use live-bindings for globals as we do not know if they have
7402 // been reassigned
7403 this.isReassigned = true;
7404 }
7405 getLiteralValueAtPath(path, _recursionTracker, _origin) {
7406 return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
7407 }
7408 hasEffectsOnInteractionAtPath(path, interaction, context) {
7409 switch (interaction.type) {
7410 case INTERACTION_ACCESSED:
7411 if (path.length === 0) {
7412 // Technically, "undefined" is a global variable of sorts
7413 return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
7414 }
7415 return !getGlobalAtPath([this.name, ...path].slice(0, -1));
7416 case INTERACTION_ASSIGNED:
7417 return true;
7418 case INTERACTION_CALLED: {
7419 const globalAtPath = getGlobalAtPath([this.name, ...path]);
7420 return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
7421 }
7422 }
7423 }
7424}
7425
7426const tdzVariableKinds = {
7427 __proto__: null,
7428 class: true,
7429 const: true,
7430 let: true,
7431 var: true
7432};
7433class Identifier extends NodeBase {
7434 constructor() {
7435 super(...arguments);
7436 this.variable = null;
7437 this.isTDZAccess = null;
7438 }
7439 addExportedVariables(variables, exportNamesByVariable) {
7440 if (exportNamesByVariable.has(this.variable)) {
7441 variables.push(this.variable);
7442 }
7443 }
7444 bind() {
7445 if (!this.variable && is_reference(this, this.parent)) {
7446 this.variable = this.scope.findVariable(this.name);
7447 this.variable.addReference(this);
7448 }
7449 }
7450 declare(kind, init) {
7451 let variable;
7452 const { treeshake } = this.context.options;
7453 switch (kind) {
7454 case 'var':
7455 variable = this.scope.addDeclaration(this, this.context, init, true);
7456 if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
7457 // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
7458 variable.markInitializersForDeoptimization();
7459 }
7460 break;
7461 case 'function':
7462 // in strict mode, functions are only hoisted within a scope but not across block scopes
7463 variable = this.scope.addDeclaration(this, this.context, init, false);
7464 break;
7465 case 'let':
7466 case 'const':
7467 case 'class':
7468 variable = this.scope.addDeclaration(this, this.context, init, false);
7469 break;
7470 case 'parameter':
7471 variable = this.scope.addParameterDeclaration(this);
7472 break;
7473 /* istanbul ignore next */
7474 default:
7475 /* istanbul ignore next */
7476 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
7477 }
7478 variable.kind = kind;
7479 return [(this.variable = variable)];
7480 }
7481 deoptimizePath(path) {
7482 var _a;
7483 if (path.length === 0 && !this.scope.contains(this.name)) {
7484 this.disallowImportReassignment();
7485 }
7486 // We keep conditional chaining because an unknown Node could have an
7487 // Identifier as property that might be deoptimized by default
7488 (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
7489 }
7490 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
7491 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
7492 }
7493 getLiteralValueAtPath(path, recursionTracker, origin) {
7494 return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
7495 }
7496 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
7497 return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
7498 }
7499 hasEffects(context) {
7500 if (!this.deoptimized)
7501 this.applyDeoptimizations();
7502 if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
7503 return true;
7504 }
7505 return (this.context.options.treeshake.unknownGlobalSideEffects &&
7506 this.variable instanceof GlobalVariable &&
7507 this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
7508 }
7509 hasEffectsOnInteractionAtPath(path, interaction, context) {
7510 switch (interaction.type) {
7511 case INTERACTION_ACCESSED:
7512 return (this.variable !== null &&
7513 this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
7514 case INTERACTION_ASSIGNED:
7515 return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
7516 case INTERACTION_CALLED:
7517 return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
7518 }
7519 }
7520 include() {
7521 if (!this.deoptimized)
7522 this.applyDeoptimizations();
7523 if (!this.included) {
7524 this.included = true;
7525 if (this.variable !== null) {
7526 this.context.includeVariableInModule(this.variable);
7527 }
7528 }
7529 }
7530 includeCallArguments(context, args) {
7531 this.variable.includeCallArguments(context, args);
7532 }
7533 isPossibleTDZ() {
7534 // return cached value to avoid issues with the next tree-shaking pass
7535 if (this.isTDZAccess !== null)
7536 return this.isTDZAccess;
7537 if (!(this.variable instanceof LocalVariable) ||
7538 !this.variable.kind ||
7539 !(this.variable.kind in tdzVariableKinds)) {
7540 return (this.isTDZAccess = false);
7541 }
7542 let decl_id;
7543 if (this.variable.declarations &&
7544 this.variable.declarations.length === 1 &&
7545 (decl_id = this.variable.declarations[0]) &&
7546 this.start < decl_id.start &&
7547 closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
7548 // a variable accessed before its declaration
7549 // in the same function or at top level of module
7550 return (this.isTDZAccess = true);
7551 }
7552 if (!this.variable.initReached) {
7553 // Either a const/let TDZ violation or
7554 // var use before declaration was encountered.
7555 return (this.isTDZAccess = true);
7556 }
7557 return (this.isTDZAccess = false);
7558 }
7559 markDeclarationReached() {
7560 this.variable.initReached = true;
7561 }
7562 render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
7563 if (this.variable) {
7564 const name = this.variable.getName(getPropertyAccess);
7565 if (name !== this.name) {
7566 code.overwrite(this.start, this.end, name, {
7567 contentOnly: true,
7568 storeName: true
7569 });
7570 if (isShorthandProperty) {
7571 code.prependRight(this.start, `${this.name}: `);
7572 }
7573 }
7574 // In strict mode, any variable named "eval" must be the actual "eval" function
7575 if (name === 'eval' &&
7576 renderedParentType === CallExpression$1 &&
7577 isCalleeOfRenderedParent) {
7578 code.appendRight(this.start, '0, ');
7579 }
7580 }
7581 }
7582 applyDeoptimizations() {
7583 this.deoptimized = true;
7584 if (this.variable instanceof LocalVariable) {
7585 this.variable.consolidateInitializers();
7586 this.context.requestTreeshakingPass();
7587 }
7588 }
7589 disallowImportReassignment() {
7590 return this.context.error({
7591 code: 'ILLEGAL_REASSIGNMENT',
7592 message: `Illegal reassignment to import '${this.name}'`
7593 }, this.start);
7594 }
7595 getVariableRespectingTDZ() {
7596 if (this.isPossibleTDZ()) {
7597 return UNKNOWN_EXPRESSION;
7598 }
7599 return this.variable;
7600 }
7601}
7602function closestParentFunctionOrProgram(node) {
7603 while (node && !/^Program|Function/.test(node.type)) {
7604 node = node.parent;
7605 }
7606 // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
7607 return node;
7608}
7609
7610function treeshakeNode(node, code, start, end) {
7611 code.remove(start, end);
7612 if (node.annotations) {
7613 for (const annotation of node.annotations) {
7614 if (annotation.start < start) {
7615 code.remove(annotation.start, annotation.end);
7616 }
7617 else {
7618 return;
7619 }
7620 }
7621 }
7622}
7623function removeAnnotations(node, code) {
7624 if (!node.annotations && node.parent.type === ExpressionStatement$1) {
7625 node = node.parent;
7626 }
7627 if (node.annotations) {
7628 for (const annotation of node.annotations) {
7629 code.remove(annotation.start, annotation.end);
7630 }
7631 }
7632}
7633
7634const NO_SEMICOLON = { isNoStatement: true };
7635// This assumes there are only white-space and comments between start and the string we are looking for
7636function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
7637 let searchPos, charCodeAfterSlash;
7638 searchPos = code.indexOf(searchString, start);
7639 while (true) {
7640 start = code.indexOf('/', start);
7641 if (start === -1 || start >= searchPos)
7642 return searchPos;
7643 charCodeAfterSlash = code.charCodeAt(++start);
7644 ++start;
7645 // With our assumption, '/' always starts a comment. Determine comment type:
7646 start =
7647 charCodeAfterSlash === 47 /*"/"*/
7648 ? code.indexOf('\n', start) + 1
7649 : code.indexOf('*/', start) + 2;
7650 if (start > searchPos) {
7651 searchPos = code.indexOf(searchString, start);
7652 }
7653 }
7654}
7655const NON_WHITESPACE = /\S/g;
7656function findNonWhiteSpace(code, index) {
7657 NON_WHITESPACE.lastIndex = index;
7658 const result = NON_WHITESPACE.exec(code);
7659 return result.index;
7660}
7661// This assumes "code" only contains white-space and comments
7662// Returns position of line-comment if applicable
7663function findFirstLineBreakOutsideComment(code) {
7664 let lineBreakPos, charCodeAfterSlash, start = 0;
7665 lineBreakPos = code.indexOf('\n', start);
7666 while (true) {
7667 start = code.indexOf('/', start);
7668 if (start === -1 || start > lineBreakPos)
7669 return [lineBreakPos, lineBreakPos + 1];
7670 // With our assumption, '/' always starts a comment. Determine comment type:
7671 charCodeAfterSlash = code.charCodeAt(start + 1);
7672 if (charCodeAfterSlash === 47 /*"/"*/)
7673 return [start, lineBreakPos + 1];
7674 start = code.indexOf('*/', start + 3) + 2;
7675 if (start > lineBreakPos) {
7676 lineBreakPos = code.indexOf('\n', start);
7677 }
7678 }
7679}
7680function renderStatementList(statements, code, start, end, options) {
7681 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
7682 let nextNode = statements[0];
7683 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
7684 if (nextNodeNeedsBoundaries) {
7685 nextNodeStart =
7686 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
7687 }
7688 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
7689 currentNode = nextNode;
7690 currentNodeStart = nextNodeStart;
7691 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
7692 nextNode = statements[nextIndex];
7693 nextNodeNeedsBoundaries =
7694 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
7695 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
7696 nextNodeStart =
7697 currentNode.end +
7698 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
7699 if (currentNode.included) {
7700 currentNodeNeedsBoundaries
7701 ? currentNode.render(code, options, {
7702 end: nextNodeStart,
7703 start: currentNodeStart
7704 })
7705 : currentNode.render(code, options);
7706 }
7707 else {
7708 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
7709 }
7710 }
7711 else {
7712 currentNode.render(code, options);
7713 }
7714 }
7715}
7716// This assumes that the first character is not part of the first node
7717function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
7718 const splitUpNodes = [];
7719 let node, nextNode, nextNodeStart, contentEnd, char;
7720 let separator = start - 1;
7721 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
7722 nextNode = nodes[nextIndex];
7723 if (node !== undefined) {
7724 separator =
7725 node.end +
7726 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
7727 }
7728 nextNodeStart = contentEnd =
7729 separator +
7730 1 +
7731 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
7732 while (((char = code.original.charCodeAt(nextNodeStart)),
7733 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
7734 nextNodeStart++;
7735 if (node !== undefined) {
7736 splitUpNodes.push({
7737 contentEnd,
7738 end: nextNodeStart,
7739 node,
7740 separator,
7741 start
7742 });
7743 }
7744 node = nextNode;
7745 start = nextNodeStart;
7746 }
7747 splitUpNodes.push({
7748 contentEnd: end,
7749 end,
7750 node: node,
7751 separator: null,
7752 start
7753 });
7754 return splitUpNodes;
7755}
7756// This assumes there are only white-space and comments between start and end
7757function removeLineBreaks(code, start, end) {
7758 while (true) {
7759 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
7760 if (removeStart === -1) {
7761 break;
7762 }
7763 code.remove(start + removeStart, (start += removeEnd));
7764 }
7765}
7766
7767class BlockScope extends ChildScope {
7768 addDeclaration(identifier, context, init, isHoisted) {
7769 if (isHoisted) {
7770 const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
7771 // Necessary to make sure the init is deoptimized for conditional declarations.
7772 // We cannot call deoptimizePath here.
7773 variable.markInitializersForDeoptimization();
7774 return variable;
7775 }
7776 else {
7777 return super.addDeclaration(identifier, context, init, false);
7778 }
7779 }
7780}
7781
7782class ExpressionStatement extends NodeBase {
7783 initialise() {
7784 if (this.directive &&
7785 this.directive !== 'use strict' &&
7786 this.parent.type === Program$1) {
7787 this.context.warn(
7788 // This is necessary, because either way (deleting or not) can lead to errors.
7789 {
7790 code: 'MODULE_LEVEL_DIRECTIVE',
7791 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
7792 }, this.start);
7793 }
7794 }
7795 render(code, options) {
7796 super.render(code, options);
7797 if (this.included)
7798 this.insertSemicolon(code);
7799 }
7800 shouldBeIncluded(context) {
7801 if (this.directive && this.directive !== 'use strict')
7802 return this.parent.type !== Program$1;
7803 return super.shouldBeIncluded(context);
7804 }
7805 applyDeoptimizations() { }
7806}
7807
7808class BlockStatement extends NodeBase {
7809 constructor() {
7810 super(...arguments);
7811 this.directlyIncluded = false;
7812 }
7813 addImplicitReturnExpressionToScope() {
7814 const lastStatement = this.body[this.body.length - 1];
7815 if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
7816 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
7817 }
7818 }
7819 createScope(parentScope) {
7820 this.scope = this.parent.preventChildBlockScope
7821 ? parentScope
7822 : new BlockScope(parentScope);
7823 }
7824 hasEffects(context) {
7825 if (this.deoptimizeBody)
7826 return true;
7827 for (const node of this.body) {
7828 if (context.brokenFlow)
7829 break;
7830 if (node.hasEffects(context))
7831 return true;
7832 }
7833 return false;
7834 }
7835 include(context, includeChildrenRecursively) {
7836 if (!(this.deoptimizeBody && this.directlyIncluded)) {
7837 this.included = true;
7838 this.directlyIncluded = true;
7839 if (this.deoptimizeBody)
7840 includeChildrenRecursively = true;
7841 for (const node of this.body) {
7842 if (includeChildrenRecursively || node.shouldBeIncluded(context))
7843 node.include(context, includeChildrenRecursively);
7844 }
7845 }
7846 }
7847 initialise() {
7848 const firstBodyStatement = this.body[0];
7849 this.deoptimizeBody =
7850 firstBodyStatement instanceof ExpressionStatement &&
7851 firstBodyStatement.directive === 'use asm';
7852 }
7853 render(code, options) {
7854 if (this.body.length) {
7855 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
7856 }
7857 else {
7858 super.render(code, options);
7859 }
7860 }
7861}
7862
7863class RestElement extends NodeBase {
7864 constructor() {
7865 super(...arguments);
7866 this.declarationInit = null;
7867 }
7868 addExportedVariables(variables, exportNamesByVariable) {
7869 this.argument.addExportedVariables(variables, exportNamesByVariable);
7870 }
7871 declare(kind, init) {
7872 this.declarationInit = init;
7873 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
7874 }
7875 deoptimizePath(path) {
7876 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
7877 }
7878 hasEffectsOnInteractionAtPath(path, interaction, context) {
7879 return (path.length > 0 ||
7880 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
7881 }
7882 markDeclarationReached() {
7883 this.argument.markDeclarationReached();
7884 }
7885 applyDeoptimizations() {
7886 this.deoptimized = true;
7887 if (this.declarationInit !== null) {
7888 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
7889 this.context.requestTreeshakingPass();
7890 }
7891 }
7892}
7893
7894class FunctionBase extends NodeBase {
7895 constructor() {
7896 super(...arguments);
7897 this.objectEntity = null;
7898 this.deoptimizedReturn = false;
7899 }
7900 deoptimizePath(path) {
7901 this.getObjectEntity().deoptimizePath(path);
7902 if (path.length === 1 && path[0] === UnknownKey) {
7903 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
7904 // which means the return expression needs to be reassigned
7905 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
7906 }
7907 }
7908 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
7909 if (path.length > 0) {
7910 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
7911 }
7912 }
7913 getLiteralValueAtPath(path, recursionTracker, origin) {
7914 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
7915 }
7916 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
7917 if (path.length > 0) {
7918 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
7919 }
7920 if (this.async) {
7921 if (!this.deoptimizedReturn) {
7922 this.deoptimizedReturn = true;
7923 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
7924 this.context.requestTreeshakingPass();
7925 }
7926 return UNKNOWN_EXPRESSION;
7927 }
7928 return this.scope.getReturnExpression();
7929 }
7930 hasEffectsOnInteractionAtPath(path, interaction, context) {
7931 if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
7932 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
7933 }
7934 if (this.async) {
7935 const { propertyReadSideEffects } = this.context.options
7936 .treeshake;
7937 const returnExpression = this.scope.getReturnExpression();
7938 if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
7939 (propertyReadSideEffects &&
7940 (propertyReadSideEffects === 'always' ||
7941 returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
7942 return true;
7943 }
7944 }
7945 for (const param of this.params) {
7946 if (param.hasEffects(context))
7947 return true;
7948 }
7949 return false;
7950 }
7951 include(context, includeChildrenRecursively) {
7952 if (!this.deoptimized)
7953 this.applyDeoptimizations();
7954 this.included = true;
7955 const { brokenFlow } = context;
7956 context.brokenFlow = BROKEN_FLOW_NONE;
7957 this.body.include(context, includeChildrenRecursively);
7958 context.brokenFlow = brokenFlow;
7959 }
7960 includeCallArguments(context, args) {
7961 this.scope.includeCallArguments(context, args);
7962 }
7963 initialise() {
7964 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
7965 if (this.body instanceof BlockStatement) {
7966 this.body.addImplicitReturnExpressionToScope();
7967 }
7968 else {
7969 this.scope.addReturnExpression(this.body);
7970 }
7971 }
7972 parseNode(esTreeNode) {
7973 if (esTreeNode.body.type === BlockStatement$1) {
7974 this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
7975 }
7976 super.parseNode(esTreeNode);
7977 }
7978 applyDeoptimizations() { }
7979}
7980FunctionBase.prototype.preventChildBlockScope = true;
7981
7982class ArrowFunctionExpression extends FunctionBase {
7983 constructor() {
7984 super(...arguments);
7985 this.objectEntity = null;
7986 }
7987 createScope(parentScope) {
7988 this.scope = new ReturnValueScope(parentScope, this.context);
7989 }
7990 hasEffects() {
7991 if (!this.deoptimized)
7992 this.applyDeoptimizations();
7993 return false;
7994 }
7995 hasEffectsOnInteractionAtPath(path, interaction, context) {
7996 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
7997 return true;
7998 if (interaction.type === INTERACTION_CALLED) {
7999 const { ignore, brokenFlow } = context;
8000 context.ignore = {
8001 breaks: false,
8002 continues: false,
8003 labels: new Set(),
8004 returnYield: true
8005 };
8006 if (this.body.hasEffects(context))
8007 return true;
8008 context.ignore = ignore;
8009 context.brokenFlow = brokenFlow;
8010 }
8011 return false;
8012 }
8013 include(context, includeChildrenRecursively) {
8014 super.include(context, includeChildrenRecursively);
8015 for (const param of this.params) {
8016 if (!(param instanceof Identifier)) {
8017 param.include(context, includeChildrenRecursively);
8018 }
8019 }
8020 }
8021 getObjectEntity() {
8022 if (this.objectEntity !== null) {
8023 return this.objectEntity;
8024 }
8025 return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
8026 }
8027}
8028
8029function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
8030 if (exportedVariables.length === 1 &&
8031 exportNamesByVariable.get(exportedVariables[0]).length === 1) {
8032 const variable = exportedVariables[0];
8033 return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
8034 }
8035 else {
8036 const fields = [];
8037 for (const variable of exportedVariables) {
8038 for (const exportName of exportNamesByVariable.get(variable)) {
8039 fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
8040 }
8041 }
8042 return `exports(${getObject(fields, { lineBreakIndent: null })})`;
8043 }
8044}
8045function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
8046 code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
8047 code.appendLeft(expressionEnd, ')');
8048}
8049function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
8050 const { _, getDirectReturnIifeLeft } = options.snippets;
8051 code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
8052 code.appendLeft(expressionEnd, ')');
8053}
8054function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
8055 const { _, getPropertyAccess } = options.snippets;
8056 code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
8057 if (needsParens) {
8058 code.prependRight(expressionStart, '(');
8059 code.appendLeft(expressionEnd, ')');
8060 }
8061}
8062function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
8063 const { _ } = options.snippets;
8064 code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
8065 if (needsParens) {
8066 code.prependRight(expressionStart, '(');
8067 code.appendLeft(expressionEnd, ')');
8068 }
8069}
8070
8071class ObjectPattern extends NodeBase {
8072 addExportedVariables(variables, exportNamesByVariable) {
8073 for (const property of this.properties) {
8074 if (property.type === Property$1) {
8075 property.value.addExportedVariables(variables, exportNamesByVariable);
8076 }
8077 else {
8078 property.argument.addExportedVariables(variables, exportNamesByVariable);
8079 }
8080 }
8081 }
8082 declare(kind, init) {
8083 const variables = [];
8084 for (const property of this.properties) {
8085 variables.push(...property.declare(kind, init));
8086 }
8087 return variables;
8088 }
8089 deoptimizePath(path) {
8090 if (path.length === 0) {
8091 for (const property of this.properties) {
8092 property.deoptimizePath(path);
8093 }
8094 }
8095 }
8096 hasEffectsOnInteractionAtPath(
8097 // At the moment, this is only triggered for assignment left-hand sides,
8098 // where the path is empty
8099 _path, interaction, context) {
8100 for (const property of this.properties) {
8101 if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
8102 return true;
8103 }
8104 return false;
8105 }
8106 markDeclarationReached() {
8107 for (const property of this.properties) {
8108 property.markDeclarationReached();
8109 }
8110 }
8111}
8112
8113class AssignmentExpression extends NodeBase {
8114 hasEffects(context) {
8115 const { deoptimized, left, right } = this;
8116 if (!deoptimized)
8117 this.applyDeoptimizations();
8118 // MemberExpressions do not access the property before assignments if the
8119 // operator is '='.
8120 return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
8121 }
8122 hasEffectsOnInteractionAtPath(path, interaction, context) {
8123 return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
8124 }
8125 include(context, includeChildrenRecursively) {
8126 const { deoptimized, left, right, operator } = this;
8127 if (!deoptimized)
8128 this.applyDeoptimizations();
8129 this.included = true;
8130 if (includeChildrenRecursively ||
8131 operator !== '=' ||
8132 left.included ||
8133 left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
8134 left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
8135 }
8136 right.include(context, includeChildrenRecursively);
8137 }
8138 initialise() {
8139 this.left.setAssignedValue(this.right);
8140 }
8141 render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
8142 const { left, right, start, end, parent } = this;
8143 if (left.included) {
8144 left.render(code, options);
8145 right.render(code, options);
8146 }
8147 else {
8148 const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
8149 code.remove(start, inclusionStart);
8150 if (preventASI) {
8151 removeLineBreaks(code, inclusionStart, right.start);
8152 }
8153 right.render(code, options, {
8154 renderedParentType: renderedParentType || parent.type,
8155 renderedSurroundingElement: renderedSurroundingElement || parent.type
8156 });
8157 }
8158 if (options.format === 'system') {
8159 if (left instanceof Identifier) {
8160 const variable = left.variable;
8161 const exportNames = options.exportNamesByVariable.get(variable);
8162 if (exportNames) {
8163 if (exportNames.length === 1) {
8164 renderSystemExportExpression(variable, start, end, code, options);
8165 }
8166 else {
8167 renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
8168 }
8169 return;
8170 }
8171 }
8172 else {
8173 const systemPatternExports = [];
8174 left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
8175 if (systemPatternExports.length > 0) {
8176 renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
8177 return;
8178 }
8179 }
8180 }
8181 if (left.included &&
8182 left instanceof ObjectPattern &&
8183 (renderedSurroundingElement === ExpressionStatement$1 ||
8184 renderedSurroundingElement === ArrowFunctionExpression$1)) {
8185 code.appendRight(start, '(');
8186 code.prependLeft(end, ')');
8187 }
8188 }
8189 applyDeoptimizations() {
8190 this.deoptimized = true;
8191 this.left.deoptimizePath(EMPTY_PATH);
8192 this.right.deoptimizePath(UNKNOWN_PATH);
8193 this.context.requestTreeshakingPass();
8194 }
8195}
8196
8197class AssignmentPattern extends NodeBase {
8198 addExportedVariables(variables, exportNamesByVariable) {
8199 this.left.addExportedVariables(variables, exportNamesByVariable);
8200 }
8201 declare(kind, init) {
8202 return this.left.declare(kind, init);
8203 }
8204 deoptimizePath(path) {
8205 path.length === 0 && this.left.deoptimizePath(path);
8206 }
8207 hasEffectsOnInteractionAtPath(path, interaction, context) {
8208 return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
8209 }
8210 markDeclarationReached() {
8211 this.left.markDeclarationReached();
8212 }
8213 render(code, options, { isShorthandProperty } = BLANK) {
8214 this.left.render(code, options, { isShorthandProperty });
8215 this.right.render(code, options);
8216 }
8217 applyDeoptimizations() {
8218 this.deoptimized = true;
8219 this.left.deoptimizePath(EMPTY_PATH);
8220 this.right.deoptimizePath(UNKNOWN_PATH);
8221 this.context.requestTreeshakingPass();
8222 }
8223}
8224
8225class ArgumentsVariable extends LocalVariable {
8226 constructor(context) {
8227 super('arguments', null, UNKNOWN_EXPRESSION, context);
8228 }
8229 hasEffectsOnInteractionAtPath(path, { type }) {
8230 return type !== INTERACTION_ACCESSED || path.length > 1;
8231 }
8232}
8233
8234class ThisVariable extends LocalVariable {
8235 constructor(context) {
8236 super('this', null, null, context);
8237 this.deoptimizedPaths = [];
8238 this.entitiesToBeDeoptimized = new Set();
8239 this.thisDeoptimizationList = [];
8240 this.thisDeoptimizations = new DiscriminatedPathTracker();
8241 }
8242 addEntityToBeDeoptimized(entity) {
8243 for (const path of this.deoptimizedPaths) {
8244 entity.deoptimizePath(path);
8245 }
8246 for (const { interaction, path } of this.thisDeoptimizationList) {
8247 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8248 }
8249 this.entitiesToBeDeoptimized.add(entity);
8250 }
8251 deoptimizePath(path) {
8252 if (path.length === 0 ||
8253 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
8254 return;
8255 }
8256 this.deoptimizedPaths.push(path);
8257 for (const entity of this.entitiesToBeDeoptimized) {
8258 entity.deoptimizePath(path);
8259 }
8260 }
8261 deoptimizeThisOnInteractionAtPath(interaction, path) {
8262 const thisDeoptimization = {
8263 interaction,
8264 path
8265 };
8266 if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
8267 for (const entity of this.entitiesToBeDeoptimized) {
8268 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8269 }
8270 this.thisDeoptimizationList.push(thisDeoptimization);
8271 }
8272 }
8273 hasEffectsOnInteractionAtPath(path, interaction, context) {
8274 return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
8275 super.hasEffectsOnInteractionAtPath(path, interaction, context));
8276 }
8277 getInit(context) {
8278 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
8279 }
8280}
8281
8282class FunctionScope extends ReturnValueScope {
8283 constructor(parent, context) {
8284 super(parent, context);
8285 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
8286 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
8287 }
8288 findLexicalBoundary() {
8289 return this;
8290 }
8291 includeCallArguments(context, args) {
8292 super.includeCallArguments(context, args);
8293 if (this.argumentsVariable.included) {
8294 for (const arg of args) {
8295 if (!arg.included) {
8296 arg.include(context, false);
8297 }
8298 }
8299 }
8300 }
8301}
8302
8303class FunctionNode extends FunctionBase {
8304 constructor() {
8305 super(...arguments);
8306 this.objectEntity = null;
8307 }
8308 createScope(parentScope) {
8309 this.scope = new FunctionScope(parentScope, this.context);
8310 }
8311 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8312 super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8313 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
8314 this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
8315 }
8316 }
8317 hasEffects(context) {
8318 var _a;
8319 if (!this.deoptimized)
8320 this.applyDeoptimizations();
8321 return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
8322 }
8323 hasEffectsOnInteractionAtPath(path, interaction, context) {
8324 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
8325 return true;
8326 if (interaction.type === INTERACTION_CALLED) {
8327 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
8328 context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
8329 ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
8330 : UNKNOWN_EXPRESSION);
8331 const { brokenFlow, ignore } = context;
8332 context.ignore = {
8333 breaks: false,
8334 continues: false,
8335 labels: new Set(),
8336 returnYield: true
8337 };
8338 if (this.body.hasEffects(context))
8339 return true;
8340 context.brokenFlow = brokenFlow;
8341 if (thisInit) {
8342 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
8343 }
8344 else {
8345 context.replacedVariableInits.delete(this.scope.thisVariable);
8346 }
8347 context.ignore = ignore;
8348 }
8349 return false;
8350 }
8351 include(context, includeChildrenRecursively) {
8352 var _a;
8353 super.include(context, includeChildrenRecursively);
8354 (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
8355 const hasArguments = this.scope.argumentsVariable.included;
8356 for (const param of this.params) {
8357 if (!(param instanceof Identifier) || hasArguments) {
8358 param.include(context, includeChildrenRecursively);
8359 }
8360 }
8361 }
8362 initialise() {
8363 var _a;
8364 super.initialise();
8365 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
8366 }
8367 getObjectEntity() {
8368 if (this.objectEntity !== null) {
8369 return this.objectEntity;
8370 }
8371 return (this.objectEntity = new ObjectEntity([
8372 {
8373 key: 'prototype',
8374 kind: 'init',
8375 property: new ObjectEntity([], OBJECT_PROTOTYPE)
8376 }
8377 ], OBJECT_PROTOTYPE));
8378 }
8379}
8380
8381class AwaitExpression extends NodeBase {
8382 hasEffects() {
8383 if (!this.deoptimized)
8384 this.applyDeoptimizations();
8385 return true;
8386 }
8387 include(context, includeChildrenRecursively) {
8388 if (!this.deoptimized)
8389 this.applyDeoptimizations();
8390 if (!this.included) {
8391 this.included = true;
8392 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
8393 let parent = this.parent;
8394 do {
8395 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
8396 break checkTopLevelAwait;
8397 } while ((parent = parent.parent));
8398 this.context.usesTopLevelAwait = true;
8399 }
8400 }
8401 this.argument.include(context, includeChildrenRecursively);
8402 }
8403}
8404
8405const binaryOperators = {
8406 '!=': (left, right) => left != right,
8407 '!==': (left, right) => left !== right,
8408 '%': (left, right) => left % right,
8409 '&': (left, right) => left & right,
8410 '*': (left, right) => left * right,
8411 // At the moment, "**" will be transpiled to Math.pow
8412 '**': (left, right) => left ** right,
8413 '+': (left, right) => left + right,
8414 '-': (left, right) => left - right,
8415 '/': (left, right) => left / right,
8416 '<': (left, right) => left < right,
8417 '<<': (left, right) => left << right,
8418 '<=': (left, right) => left <= right,
8419 '==': (left, right) => left == right,
8420 '===': (left, right) => left === right,
8421 '>': (left, right) => left > right,
8422 '>=': (left, right) => left >= right,
8423 '>>': (left, right) => left >> right,
8424 '>>>': (left, right) => left >>> right,
8425 '^': (left, right) => left ^ right,
8426 '|': (left, right) => left | right
8427 // We use the fallback for cases where we return something unknown
8428 // in: () => UnknownValue,
8429 // instanceof: () => UnknownValue,
8430};
8431class BinaryExpression extends NodeBase {
8432 deoptimizeCache() { }
8433 getLiteralValueAtPath(path, recursionTracker, origin) {
8434 if (path.length > 0)
8435 return UnknownValue;
8436 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8437 if (typeof leftValue === 'symbol')
8438 return UnknownValue;
8439 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8440 if (typeof rightValue === 'symbol')
8441 return UnknownValue;
8442 const operatorFn = binaryOperators[this.operator];
8443 if (!operatorFn)
8444 return UnknownValue;
8445 return operatorFn(leftValue, rightValue);
8446 }
8447 hasEffects(context) {
8448 // support some implicit type coercion runtime errors
8449 if (this.operator === '+' &&
8450 this.parent instanceof ExpressionStatement &&
8451 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
8452 return true;
8453 }
8454 return super.hasEffects(context);
8455 }
8456 hasEffectsOnInteractionAtPath(path, { type }) {
8457 return type !== INTERACTION_ACCESSED || path.length > 1;
8458 }
8459 render(code, options, { renderedSurroundingElement } = BLANK) {
8460 this.left.render(code, options, { renderedSurroundingElement });
8461 this.right.render(code, options);
8462 }
8463}
8464
8465class BreakStatement extends NodeBase {
8466 hasEffects(context) {
8467 if (this.label) {
8468 if (!context.ignore.labels.has(this.label.name))
8469 return true;
8470 context.includedLabels.add(this.label.name);
8471 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8472 }
8473 else {
8474 if (!context.ignore.breaks)
8475 return true;
8476 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
8477 }
8478 return false;
8479 }
8480 include(context) {
8481 this.included = true;
8482 if (this.label) {
8483 this.label.include();
8484 context.includedLabels.add(this.label.name);
8485 }
8486 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
8487 }
8488}
8489
8490function renderCallArguments(code, options, node) {
8491 if (node.arguments.length > 0) {
8492 if (node.arguments[node.arguments.length - 1].included) {
8493 for (const arg of node.arguments) {
8494 arg.render(code, options);
8495 }
8496 }
8497 else {
8498 let lastIncludedIndex = node.arguments.length - 2;
8499 while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
8500 lastIncludedIndex--;
8501 }
8502 if (lastIncludedIndex >= 0) {
8503 for (let index = 0; index <= lastIncludedIndex; index++) {
8504 node.arguments[index].render(code, options);
8505 }
8506 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
8507 }
8508 else {
8509 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
8510 }
8511 }
8512 }
8513}
8514
8515class Literal extends NodeBase {
8516 deoptimizeThisOnInteractionAtPath() { }
8517 getLiteralValueAtPath(path) {
8518 if (path.length > 0 ||
8519 // unknown literals can also be null but do not start with an "n"
8520 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
8521 typeof this.value === 'bigint' ||
8522 // to support shims for regular expressions
8523 this.context.code.charCodeAt(this.start) === 47) {
8524 return UnknownValue;
8525 }
8526 return this.value;
8527 }
8528 getReturnExpressionWhenCalledAtPath(path) {
8529 if (path.length !== 1)
8530 return UNKNOWN_EXPRESSION;
8531 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
8532 }
8533 hasEffectsOnInteractionAtPath(path, interaction, context) {
8534 switch (interaction.type) {
8535 case INTERACTION_ACCESSED:
8536 return path.length > (this.value === null ? 0 : 1);
8537 case INTERACTION_ASSIGNED:
8538 return true;
8539 case INTERACTION_CALLED:
8540 return (path.length !== 1 ||
8541 hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
8542 }
8543 }
8544 initialise() {
8545 this.members = getLiteralMembersForValue(this.value);
8546 }
8547 parseNode(esTreeNode) {
8548 this.value = esTreeNode.value;
8549 this.regex = esTreeNode.regex;
8550 super.parseNode(esTreeNode);
8551 }
8552 render(code) {
8553 if (typeof this.value === 'string') {
8554 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
8555 }
8556 }
8557}
8558
8559// To avoid infinite recursions
8560const MAX_PATH_DEPTH = 7;
8561function getResolvablePropertyKey(memberExpression) {
8562 return memberExpression.computed
8563 ? getResolvableComputedPropertyKey(memberExpression.property)
8564 : memberExpression.property.name;
8565}
8566function getResolvableComputedPropertyKey(propertyKey) {
8567 if (propertyKey instanceof Literal) {
8568 return String(propertyKey.value);
8569 }
8570 return null;
8571}
8572function getPathIfNotComputed(memberExpression) {
8573 const nextPathKey = memberExpression.propertyKey;
8574 const object = memberExpression.object;
8575 if (typeof nextPathKey === 'string') {
8576 if (object instanceof Identifier) {
8577 return [
8578 { key: object.name, pos: object.start },
8579 { key: nextPathKey, pos: memberExpression.property.start }
8580 ];
8581 }
8582 if (object instanceof MemberExpression) {
8583 const parentPath = getPathIfNotComputed(object);
8584 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
8585 }
8586 }
8587 return null;
8588}
8589function getStringFromPath(path) {
8590 let pathString = path[0].key;
8591 for (let index = 1; index < path.length; index++) {
8592 pathString += '.' + path[index].key;
8593 }
8594 return pathString;
8595}
8596class MemberExpression extends NodeBase {
8597 constructor() {
8598 super(...arguments);
8599 this.variable = null;
8600 this.assignmentDeoptimized = false;
8601 this.bound = false;
8602 this.expressionsToBeDeoptimized = [];
8603 this.replacement = null;
8604 }
8605 bind() {
8606 this.bound = true;
8607 const path = getPathIfNotComputed(this);
8608 const baseVariable = path && this.scope.findVariable(path[0].key);
8609 if (baseVariable && baseVariable.isNamespace) {
8610 const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
8611 if (!resolvedVariable) {
8612 super.bind();
8613 }
8614 else if (typeof resolvedVariable === 'string') {
8615 this.replacement = resolvedVariable;
8616 }
8617 else {
8618 this.variable = resolvedVariable;
8619 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
8620 }
8621 }
8622 else {
8623 super.bind();
8624 }
8625 }
8626 deoptimizeCache() {
8627 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
8628 this.expressionsToBeDeoptimized = [];
8629 this.propertyKey = UnknownKey;
8630 this.object.deoptimizePath(UNKNOWN_PATH);
8631 for (const expression of expressionsToBeDeoptimized) {
8632 expression.deoptimizeCache();
8633 }
8634 }
8635 deoptimizePath(path) {
8636 if (path.length === 0)
8637 this.disallowNamespaceReassignment();
8638 if (this.variable) {
8639 this.variable.deoptimizePath(path);
8640 }
8641 else if (!this.replacement) {
8642 if (path.length < MAX_PATH_DEPTH) {
8643 const propertyKey = this.getPropertyKey();
8644 this.object.deoptimizePath([
8645 propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
8646 ...path
8647 ]);
8648 }
8649 }
8650 }
8651 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8652 if (this.variable) {
8653 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8654 }
8655 else if (!this.replacement) {
8656 if (path.length < MAX_PATH_DEPTH) {
8657 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
8658 }
8659 else {
8660 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
8661 }
8662 }
8663 }
8664 getLiteralValueAtPath(path, recursionTracker, origin) {
8665 if (this.variable) {
8666 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
8667 }
8668 if (this.replacement) {
8669 return UnknownValue;
8670 }
8671 this.expressionsToBeDeoptimized.push(origin);
8672 if (path.length < MAX_PATH_DEPTH) {
8673 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
8674 }
8675 return UnknownValue;
8676 }
8677 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8678 if (this.variable) {
8679 return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8680 }
8681 if (this.replacement) {
8682 return UNKNOWN_EXPRESSION;
8683 }
8684 this.expressionsToBeDeoptimized.push(origin);
8685 if (path.length < MAX_PATH_DEPTH) {
8686 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
8687 }
8688 return UNKNOWN_EXPRESSION;
8689 }
8690 hasEffects(context) {
8691 if (!this.deoptimized)
8692 this.applyDeoptimizations();
8693 return (this.property.hasEffects(context) ||
8694 this.object.hasEffects(context) ||
8695 this.hasAccessEffect(context));
8696 }
8697 hasEffectsAsAssignmentTarget(context, checkAccess) {
8698 if (checkAccess && !this.deoptimized)
8699 this.applyDeoptimizations();
8700 if (!this.assignmentDeoptimized)
8701 this.applyAssignmentDeoptimization();
8702 return (this.property.hasEffects(context) ||
8703 this.object.hasEffects(context) ||
8704 (checkAccess && this.hasAccessEffect(context)) ||
8705 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
8706 }
8707 hasEffectsOnInteractionAtPath(path, interaction, context) {
8708 if (this.variable) {
8709 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
8710 }
8711 if (this.replacement) {
8712 return true;
8713 }
8714 if (path.length < MAX_PATH_DEPTH) {
8715 return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
8716 }
8717 return true;
8718 }
8719 include(context, includeChildrenRecursively) {
8720 if (!this.deoptimized)
8721 this.applyDeoptimizations();
8722 this.includeProperties(context, includeChildrenRecursively);
8723 }
8724 includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
8725 if (!this.assignmentDeoptimized)
8726 this.applyAssignmentDeoptimization();
8727 if (deoptimizeAccess) {
8728 this.include(context, includeChildrenRecursively);
8729 }
8730 else {
8731 this.includeProperties(context, includeChildrenRecursively);
8732 }
8733 }
8734 includeCallArguments(context, args) {
8735 if (this.variable) {
8736 this.variable.includeCallArguments(context, args);
8737 }
8738 else {
8739 super.includeCallArguments(context, args);
8740 }
8741 }
8742 initialise() {
8743 this.propertyKey = getResolvablePropertyKey(this);
8744 this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
8745 }
8746 render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
8747 if (this.variable || this.replacement) {
8748 const { snippets: { getPropertyAccess } } = options;
8749 let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
8750 if (renderedParentType && isCalleeOfRenderedParent)
8751 replacement = '0, ' + replacement;
8752 code.overwrite(this.start, this.end, replacement, {
8753 contentOnly: true,
8754 storeName: true
8755 });
8756 }
8757 else {
8758 if (renderedParentType && isCalleeOfRenderedParent) {
8759 code.appendRight(this.start, '0, ');
8760 }
8761 this.object.render(code, options, { renderedSurroundingElement });
8762 this.property.render(code, options);
8763 }
8764 }
8765 setAssignedValue(value) {
8766 this.assignmentInteraction = {
8767 args: [value],
8768 thisArg: this.object,
8769 type: INTERACTION_ASSIGNED
8770 };
8771 }
8772 applyDeoptimizations() {
8773 this.deoptimized = true;
8774 const { propertyReadSideEffects } = this.context.options
8775 .treeshake;
8776 if (
8777 // Namespaces are not bound and should not be deoptimized
8778 this.bound &&
8779 propertyReadSideEffects &&
8780 !(this.variable || this.replacement)) {
8781 const propertyKey = this.getPropertyKey();
8782 this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
8783 this.context.requestTreeshakingPass();
8784 }
8785 }
8786 applyAssignmentDeoptimization() {
8787 this.assignmentDeoptimized = true;
8788 const { propertyReadSideEffects } = this.context.options
8789 .treeshake;
8790 if (
8791 // Namespaces are not bound and should not be deoptimized
8792 this.bound &&
8793 propertyReadSideEffects &&
8794 !(this.variable || this.replacement)) {
8795 this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
8796 this.context.requestTreeshakingPass();
8797 }
8798 }
8799 disallowNamespaceReassignment() {
8800 if (this.object instanceof Identifier) {
8801 const variable = this.scope.findVariable(this.object.name);
8802 if (variable.isNamespace) {
8803 if (this.variable) {
8804 this.context.includeVariableInModule(this.variable);
8805 }
8806 this.context.warn({
8807 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
8808 message: `Illegal reassignment to import '${this.object.name}'`
8809 }, this.start);
8810 }
8811 }
8812 }
8813 getPropertyKey() {
8814 if (this.propertyKey === null) {
8815 this.propertyKey = UnknownKey;
8816 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8817 return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
8818 }
8819 return this.propertyKey;
8820 }
8821 hasAccessEffect(context) {
8822 const { propertyReadSideEffects } = this.context.options
8823 .treeshake;
8824 return (!(this.variable || this.replacement) &&
8825 propertyReadSideEffects &&
8826 (propertyReadSideEffects === 'always' ||
8827 this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
8828 }
8829 includeProperties(context, includeChildrenRecursively) {
8830 if (!this.included) {
8831 this.included = true;
8832 if (this.variable) {
8833 this.context.includeVariableInModule(this.variable);
8834 }
8835 }
8836 this.object.include(context, includeChildrenRecursively);
8837 this.property.include(context, includeChildrenRecursively);
8838 }
8839}
8840function resolveNamespaceVariables(baseVariable, path, astContext) {
8841 if (path.length === 0)
8842 return baseVariable;
8843 if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
8844 return null;
8845 const exportName = path[0].key;
8846 const variable = baseVariable.context.traceExport(exportName);
8847 if (!variable) {
8848 const fileName = baseVariable.context.fileName;
8849 astContext.warn({
8850 code: 'MISSING_EXPORT',
8851 exporter: relativeId(fileName),
8852 importer: relativeId(astContext.fileName),
8853 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
8854 missing: exportName,
8855 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
8856 }, path[0].pos);
8857 return 'undefined';
8858 }
8859 return resolveNamespaceVariables(variable, path.slice(1), astContext);
8860}
8861
8862class CallExpressionBase extends NodeBase {
8863 constructor() {
8864 super(...arguments);
8865 this.returnExpression = null;
8866 this.deoptimizableDependentExpressions = [];
8867 this.expressionsToBeDeoptimized = new Set();
8868 }
8869 deoptimizeCache() {
8870 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
8871 this.returnExpression = UNKNOWN_EXPRESSION;
8872 for (const expression of this.deoptimizableDependentExpressions) {
8873 expression.deoptimizeCache();
8874 }
8875 for (const expression of this.expressionsToBeDeoptimized) {
8876 expression.deoptimizePath(UNKNOWN_PATH);
8877 }
8878 }
8879 }
8880 deoptimizePath(path) {
8881 if (path.length === 0 ||
8882 this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
8883 return;
8884 }
8885 const returnExpression = this.getReturnExpression();
8886 if (returnExpression !== UNKNOWN_EXPRESSION) {
8887 returnExpression.deoptimizePath(path);
8888 }
8889 }
8890 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8891 const returnExpression = this.getReturnExpression(recursionTracker);
8892 if (returnExpression === UNKNOWN_EXPRESSION) {
8893 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
8894 }
8895 else {
8896 recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
8897 this.expressionsToBeDeoptimized.add(interaction.thisArg);
8898 returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8899 }, undefined);
8900 }
8901 }
8902 getLiteralValueAtPath(path, recursionTracker, origin) {
8903 const returnExpression = this.getReturnExpression(recursionTracker);
8904 if (returnExpression === UNKNOWN_EXPRESSION) {
8905 return UnknownValue;
8906 }
8907 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
8908 this.deoptimizableDependentExpressions.push(origin);
8909 return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
8910 }, UnknownValue);
8911 }
8912 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8913 const returnExpression = this.getReturnExpression(recursionTracker);
8914 if (this.returnExpression === UNKNOWN_EXPRESSION) {
8915 return UNKNOWN_EXPRESSION;
8916 }
8917 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
8918 this.deoptimizableDependentExpressions.push(origin);
8919 return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8920 }, UNKNOWN_EXPRESSION);
8921 }
8922 hasEffectsOnInteractionAtPath(path, interaction, context) {
8923 const { type } = interaction;
8924 if (type === INTERACTION_CALLED) {
8925 if ((interaction.withNew
8926 ? context.instantiated
8927 : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
8928 return false;
8929 }
8930 }
8931 else if ((type === INTERACTION_ASSIGNED
8932 ? context.assigned
8933 : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
8934 return false;
8935 }
8936 return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
8937 }
8938}
8939
8940class CallExpression extends CallExpressionBase {
8941 bind() {
8942 super.bind();
8943 if (this.callee instanceof Identifier) {
8944 const variable = this.scope.findVariable(this.callee.name);
8945 if (variable.isNamespace) {
8946 this.context.warn({
8947 code: 'CANNOT_CALL_NAMESPACE',
8948 message: `Cannot call a namespace ('${this.callee.name}')`
8949 }, this.start);
8950 }
8951 if (this.callee.name === 'eval') {
8952 this.context.warn({
8953 code: 'EVAL',
8954 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
8955 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
8956 }, this.start);
8957 }
8958 }
8959 this.interaction = {
8960 args: this.arguments,
8961 thisArg: this.callee instanceof MemberExpression && !this.callee.variable
8962 ? this.callee.object
8963 : null,
8964 type: INTERACTION_CALLED,
8965 withNew: false
8966 };
8967 }
8968 hasEffects(context) {
8969 try {
8970 for (const argument of this.arguments) {
8971 if (argument.hasEffects(context))
8972 return true;
8973 }
8974 if (this.context.options.treeshake.annotations &&
8975 this.annotations)
8976 return false;
8977 return (this.callee.hasEffects(context) ||
8978 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
8979 }
8980 finally {
8981 if (!this.deoptimized)
8982 this.applyDeoptimizations();
8983 }
8984 }
8985 include(context, includeChildrenRecursively) {
8986 if (!this.deoptimized)
8987 this.applyDeoptimizations();
8988 if (includeChildrenRecursively) {
8989 super.include(context, includeChildrenRecursively);
8990 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
8991 this.callee instanceof Identifier &&
8992 this.callee.variable) {
8993 this.callee.variable.markCalledFromTryStatement();
8994 }
8995 }
8996 else {
8997 this.included = true;
8998 this.callee.include(context, false);
8999 }
9000 this.callee.includeCallArguments(context, this.arguments);
9001 }
9002 render(code, options, { renderedSurroundingElement } = BLANK) {
9003 this.callee.render(code, options, {
9004 isCalleeOfRenderedParent: true,
9005 renderedSurroundingElement
9006 });
9007 renderCallArguments(code, options, this);
9008 }
9009 applyDeoptimizations() {
9010 this.deoptimized = true;
9011 if (this.interaction.thisArg) {
9012 this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
9013 }
9014 for (const argument of this.arguments) {
9015 // This will make sure all properties of parameters behave as "unknown"
9016 argument.deoptimizePath(UNKNOWN_PATH);
9017 }
9018 this.context.requestTreeshakingPass();
9019 }
9020 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
9021 if (this.returnExpression === null) {
9022 this.returnExpression = UNKNOWN_EXPRESSION;
9023 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
9024 }
9025 return this.returnExpression;
9026 }
9027}
9028
9029class CatchScope extends ParameterScope {
9030 addDeclaration(identifier, context, init, isHoisted) {
9031 const existingParameter = this.variables.get(identifier.name);
9032 if (existingParameter) {
9033 // While we still create a hoisted declaration, the initializer goes to
9034 // the parameter. Note that technically, the declaration now belongs to
9035 // two variables, which is not correct but should not cause issues.
9036 this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
9037 existingParameter.addDeclaration(identifier, init);
9038 return existingParameter;
9039 }
9040 return this.parent.addDeclaration(identifier, context, init, isHoisted);
9041 }
9042}
9043
9044class CatchClause extends NodeBase {
9045 createScope(parentScope) {
9046 this.scope = new CatchScope(parentScope, this.context);
9047 }
9048 parseNode(esTreeNode) {
9049 // Parameters need to be declared first as the logic is that initializers
9050 // of hoisted body variables are associated with parameters of the same
9051 // name instead of the variable
9052 const { param } = esTreeNode;
9053 if (param) {
9054 this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
9055 this.param.declare('parameter', UNKNOWN_EXPRESSION);
9056 }
9057 super.parseNode(esTreeNode);
9058 }
9059}
9060
9061class ChainExpression extends NodeBase {
9062}
9063
9064class ClassBodyScope extends ChildScope {
9065 constructor(parent, classNode, context) {
9066 super(parent);
9067 this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
9068 this.instanceScope = new ChildScope(this);
9069 this.instanceScope.variables.set('this', new ThisVariable(context));
9070 }
9071 findLexicalBoundary() {
9072 return this;
9073 }
9074}
9075
9076class ClassBody extends NodeBase {
9077 createScope(parentScope) {
9078 this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
9079 }
9080 include(context, includeChildrenRecursively) {
9081 this.included = true;
9082 this.context.includeVariableInModule(this.scope.thisVariable);
9083 for (const definition of this.body) {
9084 definition.include(context, includeChildrenRecursively);
9085 }
9086 }
9087 parseNode(esTreeNode) {
9088 const body = (this.body = []);
9089 for (const definition of esTreeNode.body) {
9090 body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
9091 }
9092 super.parseNode(esTreeNode);
9093 }
9094 applyDeoptimizations() { }
9095}
9096
9097class MethodBase extends NodeBase {
9098 constructor() {
9099 super(...arguments);
9100 this.accessedValue = null;
9101 }
9102 // As getter properties directly receive their values from fixed function
9103 // expressions, there is no known situation where a getter is deoptimized.
9104 deoptimizeCache() { }
9105 deoptimizePath(path) {
9106 this.getAccessedValue().deoptimizePath(path);
9107 }
9108 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9109 if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
9110 return this.value.deoptimizeThisOnInteractionAtPath({
9111 args: NO_ARGS,
9112 thisArg: interaction.thisArg,
9113 type: INTERACTION_CALLED,
9114 withNew: false
9115 }, EMPTY_PATH, recursionTracker);
9116 }
9117 if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
9118 return this.value.deoptimizeThisOnInteractionAtPath({
9119 args: interaction.args,
9120 thisArg: interaction.thisArg,
9121 type: INTERACTION_CALLED,
9122 withNew: false
9123 }, EMPTY_PATH, recursionTracker);
9124 }
9125 this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9126 }
9127 getLiteralValueAtPath(path, recursionTracker, origin) {
9128 return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
9129 }
9130 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9131 return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9132 }
9133 hasEffects(context) {
9134 return this.key.hasEffects(context);
9135 }
9136 hasEffectsOnInteractionAtPath(path, interaction, context) {
9137 if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
9138 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9139 args: NO_ARGS,
9140 thisArg: interaction.thisArg,
9141 type: INTERACTION_CALLED,
9142 withNew: false
9143 }, context);
9144 }
9145 // setters are only called for empty paths
9146 if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
9147 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9148 args: interaction.args,
9149 thisArg: interaction.thisArg,
9150 type: INTERACTION_CALLED,
9151 withNew: false
9152 }, context);
9153 }
9154 return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
9155 }
9156 applyDeoptimizations() { }
9157 getAccessedValue() {
9158 if (this.accessedValue === null) {
9159 if (this.kind === 'get') {
9160 this.accessedValue = UNKNOWN_EXPRESSION;
9161 return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
9162 }
9163 else {
9164 return (this.accessedValue = this.value);
9165 }
9166 }
9167 return this.accessedValue;
9168 }
9169}
9170
9171class MethodDefinition extends MethodBase {
9172 applyDeoptimizations() { }
9173}
9174
9175class ObjectMember extends ExpressionEntity {
9176 constructor(object, key) {
9177 super();
9178 this.object = object;
9179 this.key = key;
9180 }
9181 deoptimizePath(path) {
9182 this.object.deoptimizePath([this.key, ...path]);
9183 }
9184 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9185 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
9186 }
9187 getLiteralValueAtPath(path, recursionTracker, origin) {
9188 return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
9189 }
9190 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9191 return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
9192 }
9193 hasEffectsOnInteractionAtPath(path, interaction, context) {
9194 return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
9195 }
9196}
9197
9198class ClassNode extends NodeBase {
9199 constructor() {
9200 super(...arguments);
9201 this.objectEntity = null;
9202 }
9203 createScope(parentScope) {
9204 this.scope = new ChildScope(parentScope);
9205 }
9206 deoptimizeCache() {
9207 this.getObjectEntity().deoptimizeAllProperties();
9208 }
9209 deoptimizePath(path) {
9210 this.getObjectEntity().deoptimizePath(path);
9211 }
9212 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9213 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9214 }
9215 getLiteralValueAtPath(path, recursionTracker, origin) {
9216 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
9217 }
9218 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9219 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9220 }
9221 hasEffects(context) {
9222 var _a, _b;
9223 if (!this.deoptimized)
9224 this.applyDeoptimizations();
9225 const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
9226 (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
9227 return initEffect || super.hasEffects(context);
9228 }
9229 hasEffectsOnInteractionAtPath(path, interaction, context) {
9230 var _a;
9231 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
9232 return (!interaction.withNew ||
9233 (this.classConstructor !== null
9234 ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
9235 : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
9236 false);
9237 }
9238 else {
9239 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
9240 }
9241 }
9242 include(context, includeChildrenRecursively) {
9243 var _a;
9244 if (!this.deoptimized)
9245 this.applyDeoptimizations();
9246 this.included = true;
9247 (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
9248 this.body.include(context, includeChildrenRecursively);
9249 if (this.id) {
9250 this.id.markDeclarationReached();
9251 this.id.include();
9252 }
9253 }
9254 initialise() {
9255 var _a;
9256 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
9257 for (const method of this.body.body) {
9258 if (method instanceof MethodDefinition && method.kind === 'constructor') {
9259 this.classConstructor = method;
9260 return;
9261 }
9262 }
9263 this.classConstructor = null;
9264 }
9265 applyDeoptimizations() {
9266 this.deoptimized = true;
9267 for (const definition of this.body.body) {
9268 if (!(definition.static ||
9269 (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
9270 // Calls to methods are not tracked, ensure that the return value is deoptimized
9271 definition.deoptimizePath(UNKNOWN_PATH);
9272 }
9273 }
9274 this.context.requestTreeshakingPass();
9275 }
9276 getObjectEntity() {
9277 if (this.objectEntity !== null) {
9278 return this.objectEntity;
9279 }
9280 const staticProperties = [];
9281 const dynamicMethods = [];
9282 for (const definition of this.body.body) {
9283 const properties = definition.static ? staticProperties : dynamicMethods;
9284 const definitionKind = definition.kind;
9285 // Note that class fields do not end up on the prototype
9286 if (properties === dynamicMethods && !definitionKind)
9287 continue;
9288 const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
9289 let key;
9290 if (definition.computed) {
9291 const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9292 if (typeof keyValue === 'symbol') {
9293 properties.push({ key: UnknownKey, kind, property: definition });
9294 continue;
9295 }
9296 else {
9297 key = String(keyValue);
9298 }
9299 }
9300 else {
9301 key =
9302 definition.key instanceof Identifier
9303 ? definition.key.name
9304 : String(definition.key.value);
9305 }
9306 properties.push({ key, kind, property: definition });
9307 }
9308 staticProperties.unshift({
9309 key: 'prototype',
9310 kind: 'init',
9311 property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
9312 });
9313 return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
9314 }
9315}
9316
9317class ClassDeclaration extends ClassNode {
9318 initialise() {
9319 super.initialise();
9320 if (this.id !== null) {
9321 this.id.variable.isId = true;
9322 }
9323 }
9324 parseNode(esTreeNode) {
9325 if (esTreeNode.id !== null) {
9326 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9327 }
9328 super.parseNode(esTreeNode);
9329 }
9330 render(code, options) {
9331 const { exportNamesByVariable, format, snippets: { _ } } = options;
9332 if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
9333 code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
9334 }
9335 super.render(code, options);
9336 }
9337}
9338
9339class ClassExpression extends ClassNode {
9340 render(code, options, { renderedSurroundingElement } = BLANK) {
9341 super.render(code, options);
9342 if (renderedSurroundingElement === ExpressionStatement$1) {
9343 code.appendRight(this.start, '(');
9344 code.prependLeft(this.end, ')');
9345 }
9346 }
9347}
9348
9349class MultiExpression extends ExpressionEntity {
9350 constructor(expressions) {
9351 super();
9352 this.expressions = expressions;
9353 this.included = false;
9354 }
9355 deoptimizePath(path) {
9356 for (const expression of this.expressions) {
9357 expression.deoptimizePath(path);
9358 }
9359 }
9360 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9361 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
9362 }
9363 hasEffectsOnInteractionAtPath(path, interaction, context) {
9364 for (const expression of this.expressions) {
9365 if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
9366 return true;
9367 }
9368 return false;
9369 }
9370}
9371
9372class ConditionalExpression extends NodeBase {
9373 constructor() {
9374 super(...arguments);
9375 this.expressionsToBeDeoptimized = [];
9376 this.isBranchResolutionAnalysed = false;
9377 this.usedBranch = null;
9378 }
9379 deoptimizeCache() {
9380 if (this.usedBranch !== null) {
9381 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
9382 this.usedBranch = null;
9383 unusedBranch.deoptimizePath(UNKNOWN_PATH);
9384 for (const expression of this.expressionsToBeDeoptimized) {
9385 expression.deoptimizeCache();
9386 }
9387 }
9388 }
9389 deoptimizePath(path) {
9390 const usedBranch = this.getUsedBranch();
9391 if (!usedBranch) {
9392 this.consequent.deoptimizePath(path);
9393 this.alternate.deoptimizePath(path);
9394 }
9395 else {
9396 usedBranch.deoptimizePath(path);
9397 }
9398 }
9399 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9400 this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9401 this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9402 }
9403 getLiteralValueAtPath(path, recursionTracker, origin) {
9404 const usedBranch = this.getUsedBranch();
9405 if (!usedBranch)
9406 return UnknownValue;
9407 this.expressionsToBeDeoptimized.push(origin);
9408 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
9409 }
9410 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9411 const usedBranch = this.getUsedBranch();
9412 if (!usedBranch)
9413 return new MultiExpression([
9414 this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
9415 this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
9416 ]);
9417 this.expressionsToBeDeoptimized.push(origin);
9418 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9419 }
9420 hasEffects(context) {
9421 if (this.test.hasEffects(context))
9422 return true;
9423 const usedBranch = this.getUsedBranch();
9424 if (!usedBranch) {
9425 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
9426 }
9427 return usedBranch.hasEffects(context);
9428 }
9429 hasEffectsOnInteractionAtPath(path, interaction, context) {
9430 const usedBranch = this.getUsedBranch();
9431 if (!usedBranch) {
9432 return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
9433 this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
9434 }
9435 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
9436 }
9437 include(context, includeChildrenRecursively) {
9438 this.included = true;
9439 const usedBranch = this.getUsedBranch();
9440 if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
9441 this.test.include(context, includeChildrenRecursively);
9442 this.consequent.include(context, includeChildrenRecursively);
9443 this.alternate.include(context, includeChildrenRecursively);
9444 }
9445 else {
9446 usedBranch.include(context, includeChildrenRecursively);
9447 }
9448 }
9449 includeCallArguments(context, args) {
9450 const usedBranch = this.getUsedBranch();
9451 if (!usedBranch) {
9452 this.consequent.includeCallArguments(context, args);
9453 this.alternate.includeCallArguments(context, args);
9454 }
9455 else {
9456 usedBranch.includeCallArguments(context, args);
9457 }
9458 }
9459 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
9460 const usedBranch = this.getUsedBranch();
9461 if (!this.test.included) {
9462 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
9463 const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
9464 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
9465 : colonPos) + 1);
9466 if (preventASI) {
9467 removeLineBreaks(code, inclusionStart, usedBranch.start);
9468 }
9469 code.remove(this.start, inclusionStart);
9470 if (this.consequent.included) {
9471 code.remove(colonPos, this.end);
9472 }
9473 removeAnnotations(this, code);
9474 usedBranch.render(code, options, {
9475 isCalleeOfRenderedParent,
9476 preventASI: true,
9477 renderedParentType: renderedParentType || this.parent.type,
9478 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
9479 });
9480 }
9481 else {
9482 this.test.render(code, options, { renderedSurroundingElement });
9483 this.consequent.render(code, options);
9484 this.alternate.render(code, options);
9485 }
9486 }
9487 getUsedBranch() {
9488 if (this.isBranchResolutionAnalysed) {
9489 return this.usedBranch;
9490 }
9491 this.isBranchResolutionAnalysed = true;
9492 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9493 return typeof testValue === 'symbol'
9494 ? null
9495 : (this.usedBranch = testValue ? this.consequent : this.alternate);
9496 }
9497}
9498
9499class ContinueStatement extends NodeBase {
9500 hasEffects(context) {
9501 if (this.label) {
9502 if (!context.ignore.labels.has(this.label.name))
9503 return true;
9504 context.includedLabels.add(this.label.name);
9505 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
9506 }
9507 else {
9508 if (!context.ignore.continues)
9509 return true;
9510 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
9511 }
9512 return false;
9513 }
9514 include(context) {
9515 this.included = true;
9516 if (this.label) {
9517 this.label.include();
9518 context.includedLabels.add(this.label.name);
9519 }
9520 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
9521 }
9522}
9523
9524class DoWhileStatement extends NodeBase {
9525 hasEffects(context) {
9526 if (this.test.hasEffects(context))
9527 return true;
9528 const { brokenFlow, ignore: { breaks, continues } } = context;
9529 context.ignore.breaks = true;
9530 context.ignore.continues = true;
9531 if (this.body.hasEffects(context))
9532 return true;
9533 context.ignore.breaks = breaks;
9534 context.ignore.continues = continues;
9535 context.brokenFlow = brokenFlow;
9536 return false;
9537 }
9538 include(context, includeChildrenRecursively) {
9539 this.included = true;
9540 this.test.include(context, includeChildrenRecursively);
9541 const { brokenFlow } = context;
9542 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9543 context.brokenFlow = brokenFlow;
9544 }
9545}
9546
9547class EmptyStatement extends NodeBase {
9548 hasEffects() {
9549 return false;
9550 }
9551}
9552
9553class ExportAllDeclaration extends NodeBase {
9554 hasEffects() {
9555 return false;
9556 }
9557 initialise() {
9558 this.context.addExport(this);
9559 }
9560 render(code, _options, nodeRenderOptions) {
9561 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
9562 }
9563 applyDeoptimizations() { }
9564}
9565ExportAllDeclaration.prototype.needsBoundaries = true;
9566
9567class FunctionDeclaration extends FunctionNode {
9568 initialise() {
9569 super.initialise();
9570 if (this.id !== null) {
9571 this.id.variable.isId = true;
9572 }
9573 }
9574 parseNode(esTreeNode) {
9575 if (esTreeNode.id !== null) {
9576 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9577 }
9578 super.parseNode(esTreeNode);
9579 }
9580}
9581
9582// The header ends at the first non-white-space after "default"
9583function getDeclarationStart(code, start) {
9584 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
9585}
9586function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
9587 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
9588 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
9589 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
9590 if (generatorStarPos === -1) {
9591 return declarationEnd;
9592 }
9593 return declarationEnd + generatorStarPos + 1;
9594}
9595class ExportDefaultDeclaration extends NodeBase {
9596 include(context, includeChildrenRecursively) {
9597 super.include(context, includeChildrenRecursively);
9598 if (includeChildrenRecursively) {
9599 this.context.includeVariableInModule(this.variable);
9600 }
9601 }
9602 initialise() {
9603 const declaration = this.declaration;
9604 this.declarationName =
9605 (declaration.id && declaration.id.name) || this.declaration.name;
9606 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
9607 this.context.addExport(this);
9608 }
9609 render(code, options, nodeRenderOptions) {
9610 const { start, end } = nodeRenderOptions;
9611 const declarationStart = getDeclarationStart(code.original, this.start);
9612 if (this.declaration instanceof FunctionDeclaration) {
9613 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
9614 }
9615 else if (this.declaration instanceof ClassDeclaration) {
9616 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
9617 }
9618 else if (this.variable.getOriginalVariable() !== this.variable) {
9619 // Remove altogether to prevent re-declaring the same variable
9620 treeshakeNode(this, code, start, end);
9621 return;
9622 }
9623 else if (this.variable.included) {
9624 this.renderVariableDeclaration(code, declarationStart, options);
9625 }
9626 else {
9627 code.remove(this.start, declarationStart);
9628 this.declaration.render(code, options, {
9629 renderedSurroundingElement: ExpressionStatement$1
9630 });
9631 if (code.original[this.end - 1] !== ';') {
9632 code.appendLeft(this.end, ';');
9633 }
9634 return;
9635 }
9636 this.declaration.render(code, options);
9637 }
9638 applyDeoptimizations() { }
9639 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
9640 const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
9641 const name = this.variable.getName(getPropertyAccess);
9642 // Remove `export default`
9643 code.remove(this.start, declarationStart);
9644 if (needsId) {
9645 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
9646 }
9647 if (format === 'system' &&
9648 this.declaration instanceof ClassDeclaration &&
9649 exportNamesByVariable.has(this.variable)) {
9650 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
9651 }
9652 }
9653 renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
9654 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
9655 const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
9656 if (systemExportNames) {
9657 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
9658 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
9659 }
9660 else {
9661 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
9662 if (!hasTrailingSemicolon) {
9663 code.appendLeft(this.end, ';');
9664 }
9665 }
9666 }
9667}
9668ExportDefaultDeclaration.prototype.needsBoundaries = true;
9669
9670class ExportNamedDeclaration extends NodeBase {
9671 bind() {
9672 var _a;
9673 // Do not bind specifiers
9674 (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
9675 }
9676 hasEffects(context) {
9677 var _a;
9678 return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
9679 }
9680 initialise() {
9681 this.context.addExport(this);
9682 }
9683 render(code, options, nodeRenderOptions) {
9684 const { start, end } = nodeRenderOptions;
9685 if (this.declaration === null) {
9686 code.remove(start, end);
9687 }
9688 else {
9689 code.remove(this.start, this.declaration.start);
9690 this.declaration.render(code, options, { end, start });
9691 }
9692 }
9693 applyDeoptimizations() { }
9694}
9695ExportNamedDeclaration.prototype.needsBoundaries = true;
9696
9697class ExportSpecifier extends NodeBase {
9698 applyDeoptimizations() { }
9699}
9700
9701class ForInStatement extends NodeBase {
9702 createScope(parentScope) {
9703 this.scope = new BlockScope(parentScope);
9704 }
9705 hasEffects(context) {
9706 const { deoptimized, left, right } = this;
9707 if (!deoptimized)
9708 this.applyDeoptimizations();
9709 if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
9710 return true;
9711 const { brokenFlow, ignore: { breaks, continues } } = context;
9712 context.ignore.breaks = true;
9713 context.ignore.continues = true;
9714 if (this.body.hasEffects(context))
9715 return true;
9716 context.ignore.breaks = breaks;
9717 context.ignore.continues = continues;
9718 context.brokenFlow = brokenFlow;
9719 return false;
9720 }
9721 include(context, includeChildrenRecursively) {
9722 const { body, deoptimized, left, right } = this;
9723 if (!deoptimized)
9724 this.applyDeoptimizations();
9725 this.included = true;
9726 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9727 right.include(context, includeChildrenRecursively);
9728 const { brokenFlow } = context;
9729 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9730 context.brokenFlow = brokenFlow;
9731 }
9732 initialise() {
9733 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9734 }
9735 render(code, options) {
9736 this.left.render(code, options, NO_SEMICOLON);
9737 this.right.render(code, options, NO_SEMICOLON);
9738 // handle no space between "in" and the right side
9739 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
9740 code.prependLeft(this.right.start, ' ');
9741 }
9742 this.body.render(code, options);
9743 }
9744 applyDeoptimizations() {
9745 this.deoptimized = true;
9746 this.left.deoptimizePath(EMPTY_PATH);
9747 this.context.requestTreeshakingPass();
9748 }
9749}
9750
9751class ForOfStatement extends NodeBase {
9752 createScope(parentScope) {
9753 this.scope = new BlockScope(parentScope);
9754 }
9755 hasEffects() {
9756 if (!this.deoptimized)
9757 this.applyDeoptimizations();
9758 // Placeholder until proper Symbol.Iterator support
9759 return true;
9760 }
9761 include(context, includeChildrenRecursively) {
9762 const { body, deoptimized, left, right } = this;
9763 if (!deoptimized)
9764 this.applyDeoptimizations();
9765 this.included = true;
9766 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9767 right.include(context, includeChildrenRecursively);
9768 const { brokenFlow } = context;
9769 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9770 context.brokenFlow = brokenFlow;
9771 }
9772 initialise() {
9773 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9774 }
9775 render(code, options) {
9776 this.left.render(code, options, NO_SEMICOLON);
9777 this.right.render(code, options, NO_SEMICOLON);
9778 // handle no space between "of" and the right side
9779 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
9780 code.prependLeft(this.right.start, ' ');
9781 }
9782 this.body.render(code, options);
9783 }
9784 applyDeoptimizations() {
9785 this.deoptimized = true;
9786 this.left.deoptimizePath(EMPTY_PATH);
9787 this.context.requestTreeshakingPass();
9788 }
9789}
9790
9791class ForStatement extends NodeBase {
9792 createScope(parentScope) {
9793 this.scope = new BlockScope(parentScope);
9794 }
9795 hasEffects(context) {
9796 var _a, _b, _c;
9797 if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
9798 ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
9799 ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
9800 return true;
9801 const { brokenFlow, ignore: { breaks, continues } } = context;
9802 context.ignore.breaks = true;
9803 context.ignore.continues = true;
9804 if (this.body.hasEffects(context))
9805 return true;
9806 context.ignore.breaks = breaks;
9807 context.ignore.continues = continues;
9808 context.brokenFlow = brokenFlow;
9809 return false;
9810 }
9811 include(context, includeChildrenRecursively) {
9812 var _a, _b, _c;
9813 this.included = true;
9814 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
9815 (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
9816 const { brokenFlow } = context;
9817 (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
9818 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9819 context.brokenFlow = brokenFlow;
9820 }
9821 render(code, options) {
9822 var _a, _b, _c;
9823 (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
9824 (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
9825 (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
9826 this.body.render(code, options);
9827 }
9828}
9829
9830class FunctionExpression extends FunctionNode {
9831 render(code, options, { renderedSurroundingElement } = BLANK) {
9832 super.render(code, options);
9833 if (renderedSurroundingElement === ExpressionStatement$1) {
9834 code.appendRight(this.start, '(');
9835 code.prependLeft(this.end, ')');
9836 }
9837 }
9838}
9839
9840class TrackingScope extends BlockScope {
9841 constructor() {
9842 super(...arguments);
9843 this.hoistedDeclarations = [];
9844 }
9845 addDeclaration(identifier, context, init, isHoisted) {
9846 this.hoistedDeclarations.push(identifier);
9847 return super.addDeclaration(identifier, context, init, isHoisted);
9848 }
9849}
9850
9851const unset = Symbol('unset');
9852class IfStatement extends NodeBase {
9853 constructor() {
9854 super(...arguments);
9855 this.testValue = unset;
9856 }
9857 deoptimizeCache() {
9858 this.testValue = UnknownValue;
9859 }
9860 hasEffects(context) {
9861 var _a;
9862 if (this.test.hasEffects(context)) {
9863 return true;
9864 }
9865 const testValue = this.getTestValue();
9866 if (typeof testValue === 'symbol') {
9867 const { brokenFlow } = context;
9868 if (this.consequent.hasEffects(context))
9869 return true;
9870 const consequentBrokenFlow = context.brokenFlow;
9871 context.brokenFlow = brokenFlow;
9872 if (this.alternate === null)
9873 return false;
9874 if (this.alternate.hasEffects(context))
9875 return true;
9876 context.brokenFlow =
9877 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
9878 return false;
9879 }
9880 return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
9881 }
9882 include(context, includeChildrenRecursively) {
9883 this.included = true;
9884 if (includeChildrenRecursively) {
9885 this.includeRecursively(includeChildrenRecursively, context);
9886 }
9887 else {
9888 const testValue = this.getTestValue();
9889 if (typeof testValue === 'symbol') {
9890 this.includeUnknownTest(context);
9891 }
9892 else {
9893 this.includeKnownTest(context, testValue);
9894 }
9895 }
9896 }
9897 parseNode(esTreeNode) {
9898 this.consequentScope = new TrackingScope(this.scope);
9899 this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
9900 if (esTreeNode.alternate) {
9901 this.alternateScope = new TrackingScope(this.scope);
9902 this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
9903 }
9904 super.parseNode(esTreeNode);
9905 }
9906 render(code, options) {
9907 const { snippets: { getPropertyAccess } } = options;
9908 // Note that unknown test values are always included
9909 const testValue = this.getTestValue();
9910 const hoistedDeclarations = [];
9911 const includesIfElse = this.test.included;
9912 const noTreeshake = !this.context.options.treeshake;
9913 if (includesIfElse) {
9914 this.test.render(code, options);
9915 }
9916 else {
9917 code.remove(this.start, this.consequent.start);
9918 }
9919 if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
9920 this.consequent.render(code, options);
9921 }
9922 else {
9923 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
9924 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
9925 }
9926 if (this.alternate) {
9927 if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
9928 if (includesIfElse) {
9929 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
9930 code.prependLeft(this.alternate.start, ' ');
9931 }
9932 }
9933 else {
9934 code.remove(this.consequent.end, this.alternate.start);
9935 }
9936 this.alternate.render(code, options);
9937 }
9938 else {
9939 if (includesIfElse && this.shouldKeepAlternateBranch()) {
9940 code.overwrite(this.alternate.start, this.end, ';');
9941 }
9942 else {
9943 code.remove(this.consequent.end, this.end);
9944 }
9945 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
9946 }
9947 }
9948 this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
9949 }
9950 applyDeoptimizations() { }
9951 getTestValue() {
9952 if (this.testValue === unset) {
9953 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
9954 }
9955 return this.testValue;
9956 }
9957 includeKnownTest(context, testValue) {
9958 var _a;
9959 if (this.test.shouldBeIncluded(context)) {
9960 this.test.include(context, false);
9961 }
9962 if (testValue && this.consequent.shouldBeIncluded(context)) {
9963 this.consequent.include(context, false, { asSingleStatement: true });
9964 }
9965 if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
9966 this.alternate.include(context, false, { asSingleStatement: true });
9967 }
9968 }
9969 includeRecursively(includeChildrenRecursively, context) {
9970 var _a;
9971 this.test.include(context, includeChildrenRecursively);
9972 this.consequent.include(context, includeChildrenRecursively);
9973 (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
9974 }
9975 includeUnknownTest(context) {
9976 var _a;
9977 this.test.include(context, false);
9978 const { brokenFlow } = context;
9979 let consequentBrokenFlow = BROKEN_FLOW_NONE;
9980 if (this.consequent.shouldBeIncluded(context)) {
9981 this.consequent.include(context, false, { asSingleStatement: true });
9982 consequentBrokenFlow = context.brokenFlow;
9983 context.brokenFlow = brokenFlow;
9984 }
9985 if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
9986 this.alternate.include(context, false, { asSingleStatement: true });
9987 context.brokenFlow =
9988 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
9989 }
9990 }
9991 renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
9992 const hoistedVars = [
9993 ...new Set(hoistedDeclarations.map(identifier => {
9994 const variable = identifier.variable;
9995 return variable.included ? variable.getName(getPropertyAccess) : '';
9996 }))
9997 ]
9998 .filter(Boolean)
9999 .join(', ');
10000 if (hoistedVars) {
10001 const parentType = this.parent.type;
10002 const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
10003 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
10004 if (needsBraces) {
10005 code.appendLeft(this.end, ` }`);
10006 }
10007 }
10008 }
10009 shouldKeepAlternateBranch() {
10010 let currentParent = this.parent;
10011 do {
10012 if (currentParent instanceof IfStatement && currentParent.alternate) {
10013 return true;
10014 }
10015 if (currentParent instanceof BlockStatement) {
10016 return false;
10017 }
10018 currentParent = currentParent.parent;
10019 } while (currentParent);
10020 return false;
10021 }
10022}
10023
10024class ImportDeclaration extends NodeBase {
10025 // Do not bind specifiers
10026 bind() { }
10027 hasEffects() {
10028 return false;
10029 }
10030 initialise() {
10031 this.context.addImport(this);
10032 }
10033 render(code, _options, nodeRenderOptions) {
10034 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
10035 }
10036 applyDeoptimizations() { }
10037}
10038ImportDeclaration.prototype.needsBoundaries = true;
10039
10040class ImportDefaultSpecifier extends NodeBase {
10041 applyDeoptimizations() { }
10042}
10043
10044const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
10045const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
10046const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
10047const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
10048const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
10049const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
10050const defaultInteropHelpersByInteropType = {
10051 auto: INTEROP_DEFAULT_VARIABLE,
10052 default: null,
10053 defaultOnly: null,
10054 esModule: null,
10055 false: null,
10056 true: INTEROP_DEFAULT_LEGACY_VARIABLE
10057};
10058const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
10059 (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
10060const namespaceInteropHelpersByInteropType = {
10061 auto: INTEROP_NAMESPACE_VARIABLE,
10062 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
10063 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
10064 esModule: null,
10065 false: null,
10066 true: INTEROP_NAMESPACE_VARIABLE
10067};
10068const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
10069 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
10070const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
10071 const usedHelpers = new Set(additionalHelpers);
10072 for (const variable of HELPER_NAMES) {
10073 if (accessedGlobals.has(variable)) {
10074 usedHelpers.add(variable);
10075 }
10076 }
10077 return HELPER_NAMES.map(variable => usedHelpers.has(variable)
10078 ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
10079 : '').join('');
10080};
10081const HELPER_GENERATORS = {
10082 [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
10083 const { _, getDirectReturnFunction, n } = snippets;
10084 const [left, right] = getDirectReturnFunction(['e'], {
10085 functionReturn: true,
10086 lineBreakIndent: null,
10087 name: INTEROP_DEFAULT_LEGACY_VARIABLE
10088 });
10089 return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
10090 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10091 },
10092 [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
10093 const { _, getDirectReturnFunction, n } = snippets;
10094 const [left, right] = getDirectReturnFunction(['e'], {
10095 functionReturn: true,
10096 lineBreakIndent: null,
10097 name: INTEROP_DEFAULT_VARIABLE
10098 });
10099 return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
10100 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10101 },
10102 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
10103 const { getDirectReturnFunction, getObject, n } = snippets;
10104 const [left, right] = getDirectReturnFunction(['e'], {
10105 functionReturn: true,
10106 lineBreakIndent: null,
10107 name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10108 });
10109 return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
10110 ['__proto__', 'null'],
10111 ['default', 'e']
10112 ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
10113 },
10114 [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10115 const { _, n } = snippets;
10116 return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
10117 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10118 `}${n}${n}`);
10119 },
10120 [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
10121 const { _, getDirectReturnFunction, n } = snippets;
10122 if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
10123 const [left, right] = getDirectReturnFunction(['e'], {
10124 functionReturn: true,
10125 lineBreakIndent: null,
10126 name: INTEROP_NAMESPACE_VARIABLE
10127 });
10128 return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
10129 }
10130 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
10131 `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
10132 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10133 `}${n}${n}`);
10134 },
10135 [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10136 const { _, cnst, n } = snippets;
10137 const useForEach = cnst === 'var' && liveBindings;
10138 return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
10139 `${t}${loopOverNamespaces(`{${n}` +
10140 `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
10141 (liveBindings
10142 ? useForEach
10143 ? copyOwnPropertyLiveBinding
10144 : copyPropertyLiveBinding
10145 : copyPropertyStatic)(t, t + t + t + t, snippets) +
10146 `${t}${t}${t}}${n}` +
10147 `${t}${t}}`, useForEach, t, snippets)}${n}` +
10148 `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
10149 `}${n}${n}`);
10150 }
10151};
10152const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
10153const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
10154const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
10155 const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
10156 const copyProperty = `{${n}` +
10157 (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
10158 `${i}${t}}`;
10159 return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
10160 ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
10161 : ''});${n}` +
10162 `${i}if${_}(e)${_}{${n}` +
10163 `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
10164 `${i}}${n}` +
10165 `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
10166 `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
10167};
10168const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
10169 ? `for${_}(${cnst} k in e)${_}${body}`
10170 : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
10171 isAsync: false,
10172 name: null
10173 })}${body})${s}`;
10174const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
10175 if (useForEach) {
10176 const [left, right] = getDirectReturnFunction(['e'], {
10177 functionReturn: false,
10178 lineBreakIndent: { base: t, t },
10179 name: null
10180 });
10181 return (`m.forEach(${left}` +
10182 `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
10183 isAsync: false,
10184 name: null
10185 })}${body})${right});`);
10186 }
10187 return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
10188 `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
10189 `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
10190};
10191const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
10192 const { _, n } = snippets;
10193 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
10194 copyOwnPropertyLiveBinding(t, i + t, snippets) +
10195 `${i}}${n}`);
10196};
10197const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10198 const [left, right] = getDirectReturnFunction([], {
10199 functionReturn: true,
10200 lineBreakIndent: null,
10201 name: null
10202 });
10203 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10204 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10205 `${i}${t}enumerable:${_}true,${n}` +
10206 `${i}${t}get:${_}${left}e[k]${right}${n}` +
10207 `${i}});${n}`);
10208};
10209const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10210 const [left, right] = getDirectReturnFunction([], {
10211 functionReturn: true,
10212 lineBreakIndent: null,
10213 name: null
10214 });
10215 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10216 `${i}if${_}(d)${_}{${n}` +
10217 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10218 `${i}${t}${t}enumerable:${_}true,${n}` +
10219 `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
10220 `${i}${t}});${n}` +
10221 `${i}}${n}`);
10222};
10223const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
10224const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
10225const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
10226 ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
10227 : fragment;
10228const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
10229function getToStringTagValue(getObject) {
10230 return getObject([['value', "'Module'"]], {
10231 lineBreakIndent: null
10232 });
10233}
10234
10235class ImportExpression extends NodeBase {
10236 constructor() {
10237 super(...arguments);
10238 this.inlineNamespace = null;
10239 this.mechanism = null;
10240 this.resolution = null;
10241 }
10242 hasEffects() {
10243 return true;
10244 }
10245 include(context, includeChildrenRecursively) {
10246 if (!this.included) {
10247 this.included = true;
10248 this.context.includeDynamicImport(this);
10249 this.scope.addAccessedDynamicImport(this);
10250 }
10251 this.source.include(context, includeChildrenRecursively);
10252 }
10253 initialise() {
10254 this.context.addDynamicImport(this);
10255 }
10256 render(code, options) {
10257 if (this.inlineNamespace) {
10258 const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10259 const [left, right] = getDirectReturnFunction([], {
10260 functionReturn: true,
10261 lineBreakIndent: null,
10262 name: null
10263 });
10264 code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
10265 return;
10266 }
10267 if (this.mechanism) {
10268 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
10269 code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
10270 }
10271 this.source.render(code, options);
10272 }
10273 renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
10274 code.overwrite(this.source.start, this.source.end, resolution);
10275 if (namespaceExportName) {
10276 const [left, right] = getDirectReturnFunction(['n'], {
10277 functionReturn: true,
10278 lineBreakIndent: null,
10279 name: null
10280 });
10281 code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
10282 }
10283 }
10284 setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
10285 const { format } = options;
10286 this.inlineNamespace = null;
10287 this.resolution = resolution;
10288 const accessedGlobals = [...(accessedImportGlobals[format] || [])];
10289 let helper;
10290 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
10291 if (helper) {
10292 accessedGlobals.push(helper);
10293 }
10294 if (accessedGlobals.length > 0) {
10295 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10296 }
10297 }
10298 setInternalResolution(inlineNamespace) {
10299 this.inlineNamespace = inlineNamespace;
10300 }
10301 applyDeoptimizations() { }
10302 getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
10303 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
10304 {
10305 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
10306 format,
10307 moduleId: this.context.module.id,
10308 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
10309 }
10310 ]);
10311 if (mechanism) {
10312 return { helper: null, mechanism };
10313 }
10314 const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
10315 switch (format) {
10316 case 'cjs': {
10317 const helper = getInteropHelper(resolution, exportMode, interop);
10318 let left = `require(`;
10319 let right = `)`;
10320 if (helper) {
10321 left = `/*#__PURE__*/${helper}(${left}`;
10322 right += ')';
10323 }
10324 const [functionLeft, functionRight] = getDirectReturnFunction([], {
10325 functionReturn: true,
10326 lineBreakIndent: null,
10327 name: null
10328 });
10329 left = `Promise.resolve().then(${functionLeft}${left}`;
10330 right += `${functionRight})`;
10331 if (!arrowFunctions && hasDynamicTarget) {
10332 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10333 needsArrowReturnParens: false,
10334 needsWrappedFunction: true
10335 });
10336 right = ')';
10337 }
10338 return {
10339 helper,
10340 mechanism: { left, right }
10341 };
10342 }
10343 case 'amd': {
10344 const resolve = compact ? 'c' : 'resolve';
10345 const reject = compact ? 'e' : 'reject';
10346 const helper = getInteropHelper(resolution, exportMode, interop);
10347 const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
10348 functionReturn: false,
10349 lineBreakIndent: null,
10350 name: null
10351 });
10352 const resolveNamespace = helper
10353 ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
10354 : resolve;
10355 const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
10356 functionReturn: false,
10357 lineBreakIndent: null,
10358 name: null
10359 });
10360 let left = `new Promise(${handlerLeft}require([`;
10361 let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
10362 if (!arrowFunctions && hasDynamicTarget) {
10363 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10364 needsArrowReturnParens: false,
10365 needsWrappedFunction: true
10366 });
10367 right = ')';
10368 }
10369 return {
10370 helper,
10371 mechanism: { left, right }
10372 };
10373 }
10374 case 'system':
10375 return {
10376 helper: null,
10377 mechanism: {
10378 left: 'module.import(',
10379 right: ')'
10380 }
10381 };
10382 case 'es':
10383 if (dynamicImportFunction) {
10384 return {
10385 helper: null,
10386 mechanism: {
10387 left: `${dynamicImportFunction}(`,
10388 right: ')'
10389 }
10390 };
10391 }
10392 }
10393 return { helper: null, mechanism: null };
10394 }
10395}
10396function getInteropHelper(resolution, exportMode, interop) {
10397 return exportMode === 'external'
10398 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
10399 : exportMode === 'default'
10400 ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10401 : null;
10402}
10403const accessedImportGlobals = {
10404 amd: ['require'],
10405 cjs: ['require'],
10406 system: ['module']
10407};
10408
10409class ImportNamespaceSpecifier extends NodeBase {
10410 applyDeoptimizations() { }
10411}
10412
10413class ImportSpecifier extends NodeBase {
10414 applyDeoptimizations() { }
10415}
10416
10417class LabeledStatement extends NodeBase {
10418 hasEffects(context) {
10419 const brokenFlow = context.brokenFlow;
10420 context.ignore.labels.add(this.label.name);
10421 if (this.body.hasEffects(context))
10422 return true;
10423 context.ignore.labels.delete(this.label.name);
10424 if (context.includedLabels.has(this.label.name)) {
10425 context.includedLabels.delete(this.label.name);
10426 context.brokenFlow = brokenFlow;
10427 }
10428 return false;
10429 }
10430 include(context, includeChildrenRecursively) {
10431 this.included = true;
10432 const brokenFlow = context.brokenFlow;
10433 this.body.include(context, includeChildrenRecursively);
10434 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
10435 this.label.include();
10436 context.includedLabels.delete(this.label.name);
10437 context.brokenFlow = brokenFlow;
10438 }
10439 }
10440 render(code, options) {
10441 if (this.label.included) {
10442 this.label.render(code, options);
10443 }
10444 else {
10445 code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
10446 }
10447 this.body.render(code, options);
10448 }
10449}
10450
10451class LogicalExpression extends NodeBase {
10452 constructor() {
10453 super(...arguments);
10454 // We collect deoptimization information if usedBranch !== null
10455 this.expressionsToBeDeoptimized = [];
10456 this.isBranchResolutionAnalysed = false;
10457 this.usedBranch = null;
10458 }
10459 deoptimizeCache() {
10460 if (this.usedBranch) {
10461 const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
10462 this.usedBranch = null;
10463 unusedBranch.deoptimizePath(UNKNOWN_PATH);
10464 for (const expression of this.expressionsToBeDeoptimized) {
10465 expression.deoptimizeCache();
10466 }
10467 // Request another pass because we need to ensure "include" runs again if
10468 // it is rendered
10469 this.context.requestTreeshakingPass();
10470 }
10471 }
10472 deoptimizePath(path) {
10473 const usedBranch = this.getUsedBranch();
10474 if (!usedBranch) {
10475 this.left.deoptimizePath(path);
10476 this.right.deoptimizePath(path);
10477 }
10478 else {
10479 usedBranch.deoptimizePath(path);
10480 }
10481 }
10482 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10483 this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10484 this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10485 }
10486 getLiteralValueAtPath(path, recursionTracker, origin) {
10487 const usedBranch = this.getUsedBranch();
10488 if (!usedBranch)
10489 return UnknownValue;
10490 this.expressionsToBeDeoptimized.push(origin);
10491 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
10492 }
10493 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10494 const usedBranch = this.getUsedBranch();
10495 if (!usedBranch)
10496 return new MultiExpression([
10497 this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
10498 this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
10499 ]);
10500 this.expressionsToBeDeoptimized.push(origin);
10501 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10502 }
10503 hasEffects(context) {
10504 if (this.left.hasEffects(context)) {
10505 return true;
10506 }
10507 if (this.getUsedBranch() !== this.left) {
10508 return this.right.hasEffects(context);
10509 }
10510 return false;
10511 }
10512 hasEffectsOnInteractionAtPath(path, interaction, context) {
10513 const usedBranch = this.getUsedBranch();
10514 if (!usedBranch) {
10515 return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
10516 this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
10517 }
10518 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
10519 }
10520 include(context, includeChildrenRecursively) {
10521 this.included = true;
10522 const usedBranch = this.getUsedBranch();
10523 if (includeChildrenRecursively ||
10524 (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
10525 !usedBranch) {
10526 this.left.include(context, includeChildrenRecursively);
10527 this.right.include(context, includeChildrenRecursively);
10528 }
10529 else {
10530 usedBranch.include(context, includeChildrenRecursively);
10531 }
10532 }
10533 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
10534 if (!this.left.included || !this.right.included) {
10535 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
10536 if (this.right.included) {
10537 const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
10538 code.remove(this.start, removePos);
10539 if (preventASI) {
10540 removeLineBreaks(code, removePos, this.right.start);
10541 }
10542 }
10543 else {
10544 code.remove(operatorPos, this.end);
10545 }
10546 removeAnnotations(this, code);
10547 this.getUsedBranch().render(code, options, {
10548 isCalleeOfRenderedParent,
10549 preventASI,
10550 renderedParentType: renderedParentType || this.parent.type,
10551 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
10552 });
10553 }
10554 else {
10555 this.left.render(code, options, {
10556 preventASI,
10557 renderedSurroundingElement
10558 });
10559 this.right.render(code, options);
10560 }
10561 }
10562 getUsedBranch() {
10563 if (!this.isBranchResolutionAnalysed) {
10564 this.isBranchResolutionAnalysed = true;
10565 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10566 if (typeof leftValue === 'symbol') {
10567 return null;
10568 }
10569 else {
10570 this.usedBranch =
10571 (this.operator === '||' && leftValue) ||
10572 (this.operator === '&&' && !leftValue) ||
10573 (this.operator === '??' && leftValue != null)
10574 ? this.left
10575 : this.right;
10576 }
10577 }
10578 return this.usedBranch;
10579 }
10580}
10581
10582const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
10583const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
10584const FILE_PREFIX = 'ROLLUP_FILE_URL_';
10585class MetaProperty extends NodeBase {
10586 addAccessedGlobals(format, accessedGlobalsByScope) {
10587 const metaProperty = this.metaProperty;
10588 const accessedGlobals = (metaProperty &&
10589 (metaProperty.startsWith(FILE_PREFIX) ||
10590 metaProperty.startsWith(ASSET_PREFIX) ||
10591 metaProperty.startsWith(CHUNK_PREFIX))
10592 ? accessedFileUrlGlobals
10593 : accessedMetaUrlGlobals)[format];
10594 if (accessedGlobals.length > 0) {
10595 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10596 }
10597 }
10598 getReferencedFileName(outputPluginDriver) {
10599 const metaProperty = this.metaProperty;
10600 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
10601 return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10602 }
10603 return null;
10604 }
10605 hasEffects() {
10606 return false;
10607 }
10608 hasEffectsOnInteractionAtPath(path, { type }) {
10609 return path.length > 1 || type !== INTERACTION_ACCESSED;
10610 }
10611 include() {
10612 if (!this.included) {
10613 this.included = true;
10614 if (this.meta.name === 'import') {
10615 this.context.addImportMeta(this);
10616 const parent = this.parent;
10617 this.metaProperty =
10618 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
10619 ? parent.propertyKey
10620 : null;
10621 }
10622 }
10623 }
10624 renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
10625 var _a;
10626 const parent = this.parent;
10627 const metaProperty = this.metaProperty;
10628 if (metaProperty &&
10629 (metaProperty.startsWith(FILE_PREFIX) ||
10630 metaProperty.startsWith(ASSET_PREFIX) ||
10631 metaProperty.startsWith(CHUNK_PREFIX))) {
10632 let referenceId = null;
10633 let assetReferenceId = null;
10634 let chunkReferenceId = null;
10635 let fileName;
10636 if (metaProperty.startsWith(FILE_PREFIX)) {
10637 referenceId = metaProperty.substring(FILE_PREFIX.length);
10638 fileName = outputPluginDriver.getFileName(referenceId);
10639 }
10640 else if (metaProperty.startsWith(ASSET_PREFIX)) {
10641 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10642 assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
10643 fileName = outputPluginDriver.getFileName(assetReferenceId);
10644 }
10645 else {
10646 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10647 chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
10648 fileName = outputPluginDriver.getFileName(chunkReferenceId);
10649 }
10650 const relativePath = normalize(relative$1(dirname(chunkId), fileName));
10651 let replacement;
10652 if (assetReferenceId !== null) {
10653 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
10654 {
10655 assetFileName: fileName,
10656 chunkId,
10657 format,
10658 moduleId: this.context.module.id,
10659 relativeAssetPath: relativePath
10660 }
10661 ]);
10662 }
10663 if (!replacement) {
10664 replacement =
10665 outputPluginDriver.hookFirstSync('resolveFileUrl', [
10666 {
10667 assetReferenceId,
10668 chunkId,
10669 chunkReferenceId,
10670 fileName,
10671 format,
10672 moduleId: this.context.module.id,
10673 referenceId: referenceId || assetReferenceId || chunkReferenceId,
10674 relativePath
10675 }
10676 ]) || relativeUrlMechanisms[format](relativePath);
10677 }
10678 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10679 return;
10680 }
10681 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
10682 metaProperty,
10683 {
10684 chunkId,
10685 format,
10686 moduleId: this.context.module.id
10687 }
10688 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
10689 if (typeof replacement === 'string') {
10690 if (parent instanceof MemberExpression) {
10691 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10692 }
10693 else {
10694 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
10695 }
10696 }
10697 }
10698}
10699const accessedMetaUrlGlobals = {
10700 amd: ['document', 'module', 'URL'],
10701 cjs: ['document', 'require', 'URL'],
10702 es: [],
10703 iife: ['document', 'URL'],
10704 system: ['module'],
10705 umd: ['document', 'require', 'URL']
10706};
10707const accessedFileUrlGlobals = {
10708 amd: ['document', 'require', 'URL'],
10709 cjs: ['document', 'require', 'URL'],
10710 es: [],
10711 iife: ['document', 'URL'],
10712 system: ['module', 'URL'],
10713 umd: ['document', 'require', 'URL']
10714};
10715const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
10716const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
10717const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
10718 const urlMechanism = getUrl(chunkId);
10719 return prop === null
10720 ? `({ url: ${urlMechanism} })`
10721 : prop === 'url'
10722 ? urlMechanism
10723 : 'undefined';
10724};
10725const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
10726const relativeUrlMechanisms = {
10727 amd: relativePath => {
10728 if (relativePath[0] !== '.')
10729 relativePath = './' + relativePath;
10730 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
10731 },
10732 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
10733 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
10734 iife: relativePath => getRelativeUrlFromDocument(relativePath),
10735 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
10736 umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
10737};
10738const importMetaMechanisms = {
10739 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
10740 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
10741 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
10742 system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
10743 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
10744};
10745
10746class NewExpression extends NodeBase {
10747 hasEffects(context) {
10748 try {
10749 for (const argument of this.arguments) {
10750 if (argument.hasEffects(context))
10751 return true;
10752 }
10753 if (this.context.options.treeshake.annotations &&
10754 this.annotations) {
10755 return false;
10756 }
10757 return (this.callee.hasEffects(context) ||
10758 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
10759 }
10760 finally {
10761 if (!this.deoptimized)
10762 this.applyDeoptimizations();
10763 }
10764 }
10765 hasEffectsOnInteractionAtPath(path, { type }) {
10766 return path.length > 0 || type !== INTERACTION_ACCESSED;
10767 }
10768 include(context, includeChildrenRecursively) {
10769 if (!this.deoptimized)
10770 this.applyDeoptimizations();
10771 if (includeChildrenRecursively) {
10772 super.include(context, includeChildrenRecursively);
10773 }
10774 else {
10775 this.included = true;
10776 this.callee.include(context, false);
10777 }
10778 this.callee.includeCallArguments(context, this.arguments);
10779 }
10780 initialise() {
10781 this.interaction = {
10782 args: this.arguments,
10783 thisArg: null,
10784 type: INTERACTION_CALLED,
10785 withNew: true
10786 };
10787 }
10788 render(code, options) {
10789 this.callee.render(code, options);
10790 renderCallArguments(code, options, this);
10791 }
10792 applyDeoptimizations() {
10793 this.deoptimized = true;
10794 for (const argument of this.arguments) {
10795 // This will make sure all properties of parameters behave as "unknown"
10796 argument.deoptimizePath(UNKNOWN_PATH);
10797 }
10798 this.context.requestTreeshakingPass();
10799 }
10800}
10801
10802class ObjectExpression extends NodeBase {
10803 constructor() {
10804 super(...arguments);
10805 this.objectEntity = null;
10806 }
10807 deoptimizeCache() {
10808 this.getObjectEntity().deoptimizeAllProperties();
10809 }
10810 deoptimizePath(path) {
10811 this.getObjectEntity().deoptimizePath(path);
10812 }
10813 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10814 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10815 }
10816 getLiteralValueAtPath(path, recursionTracker, origin) {
10817 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
10818 }
10819 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10820 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10821 }
10822 hasEffectsOnInteractionAtPath(path, interaction, context) {
10823 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
10824 }
10825 render(code, options, { renderedSurroundingElement } = BLANK) {
10826 super.render(code, options);
10827 if (renderedSurroundingElement === ExpressionStatement$1 ||
10828 renderedSurroundingElement === ArrowFunctionExpression$1) {
10829 code.appendRight(this.start, '(');
10830 code.prependLeft(this.end, ')');
10831 }
10832 }
10833 applyDeoptimizations() { }
10834 getObjectEntity() {
10835 if (this.objectEntity !== null) {
10836 return this.objectEntity;
10837 }
10838 let prototype = OBJECT_PROTOTYPE;
10839 const properties = [];
10840 for (const property of this.properties) {
10841 if (property instanceof SpreadElement) {
10842 properties.push({ key: UnknownKey, kind: 'init', property });
10843 continue;
10844 }
10845 let key;
10846 if (property.computed) {
10847 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10848 if (typeof keyValue === 'symbol') {
10849 properties.push({ key: UnknownKey, kind: property.kind, property });
10850 continue;
10851 }
10852 else {
10853 key = String(keyValue);
10854 }
10855 }
10856 else {
10857 key =
10858 property.key instanceof Identifier
10859 ? property.key.name
10860 : String(property.key.value);
10861 if (key === '__proto__' && property.kind === 'init') {
10862 prototype =
10863 property.value instanceof Literal && property.value.value === null
10864 ? null
10865 : property.value;
10866 continue;
10867 }
10868 }
10869 properties.push({ key, kind: property.kind, property });
10870 }
10871 return (this.objectEntity = new ObjectEntity(properties, prototype));
10872 }
10873}
10874
10875class PrivateIdentifier extends NodeBase {
10876}
10877
10878class Program extends NodeBase {
10879 constructor() {
10880 super(...arguments);
10881 this.hasCachedEffect = false;
10882 }
10883 hasEffects(context) {
10884 // We are caching here to later more efficiently identify side-effect-free modules
10885 if (this.hasCachedEffect)
10886 return true;
10887 for (const node of this.body) {
10888 if (node.hasEffects(context)) {
10889 return (this.hasCachedEffect = true);
10890 }
10891 }
10892 return false;
10893 }
10894 include(context, includeChildrenRecursively) {
10895 this.included = true;
10896 for (const node of this.body) {
10897 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
10898 node.include(context, includeChildrenRecursively);
10899 }
10900 }
10901 }
10902 render(code, options) {
10903 if (this.body.length) {
10904 renderStatementList(this.body, code, this.start, this.end, options);
10905 }
10906 else {
10907 super.render(code, options);
10908 }
10909 }
10910 applyDeoptimizations() { }
10911}
10912
10913class Property extends MethodBase {
10914 constructor() {
10915 super(...arguments);
10916 this.declarationInit = null;
10917 }
10918 declare(kind, init) {
10919 this.declarationInit = init;
10920 return this.value.declare(kind, UNKNOWN_EXPRESSION);
10921 }
10922 hasEffects(context) {
10923 if (!this.deoptimized)
10924 this.applyDeoptimizations();
10925 const propertyReadSideEffects = this.context.options.treeshake
10926 .propertyReadSideEffects;
10927 return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
10928 this.key.hasEffects(context) ||
10929 this.value.hasEffects(context));
10930 }
10931 markDeclarationReached() {
10932 this.value.markDeclarationReached();
10933 }
10934 render(code, options) {
10935 if (!this.shorthand) {
10936 this.key.render(code, options);
10937 }
10938 this.value.render(code, options, { isShorthandProperty: this.shorthand });
10939 }
10940 applyDeoptimizations() {
10941 this.deoptimized = true;
10942 if (this.declarationInit !== null) {
10943 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
10944 this.context.requestTreeshakingPass();
10945 }
10946 }
10947}
10948
10949class PropertyDefinition extends NodeBase {
10950 deoptimizePath(path) {
10951 var _a;
10952 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
10953 }
10954 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10955 var _a;
10956 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10957 }
10958 getLiteralValueAtPath(path, recursionTracker, origin) {
10959 return this.value
10960 ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
10961 : UnknownValue;
10962 }
10963 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10964 return this.value
10965 ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
10966 : UNKNOWN_EXPRESSION;
10967 }
10968 hasEffects(context) {
10969 var _a;
10970 return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
10971 }
10972 hasEffectsOnInteractionAtPath(path, interaction, context) {
10973 return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
10974 }
10975 applyDeoptimizations() { }
10976}
10977
10978class ReturnStatement extends NodeBase {
10979 hasEffects(context) {
10980 var _a;
10981 if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
10982 return true;
10983 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
10984 return false;
10985 }
10986 include(context, includeChildrenRecursively) {
10987 var _a;
10988 this.included = true;
10989 (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
10990 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
10991 }
10992 initialise() {
10993 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
10994 }
10995 render(code, options) {
10996 if (this.argument) {
10997 this.argument.render(code, options, { preventASI: true });
10998 if (this.argument.start === this.start + 6 /* 'return'.length */) {
10999 code.prependLeft(this.start + 6, ' ');
11000 }
11001 }
11002 }
11003}
11004
11005class SequenceExpression extends NodeBase {
11006 deoptimizePath(path) {
11007 this.expressions[this.expressions.length - 1].deoptimizePath(path);
11008 }
11009 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11010 this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11011 }
11012 getLiteralValueAtPath(path, recursionTracker, origin) {
11013 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
11014 }
11015 hasEffects(context) {
11016 for (const expression of this.expressions) {
11017 if (expression.hasEffects(context))
11018 return true;
11019 }
11020 return false;
11021 }
11022 hasEffectsOnInteractionAtPath(path, interaction, context) {
11023 return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
11024 }
11025 include(context, includeChildrenRecursively) {
11026 this.included = true;
11027 const lastExpression = this.expressions[this.expressions.length - 1];
11028 for (const expression of this.expressions) {
11029 if (includeChildrenRecursively ||
11030 (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
11031 expression.shouldBeIncluded(context))
11032 expression.include(context, includeChildrenRecursively);
11033 }
11034 }
11035 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
11036 let includedNodes = 0;
11037 let lastSeparatorPos = null;
11038 const lastNode = this.expressions[this.expressions.length - 1];
11039 for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
11040 if (!node.included) {
11041 treeshakeNode(node, code, start, end);
11042 continue;
11043 }
11044 includedNodes++;
11045 lastSeparatorPos = separator;
11046 if (includedNodes === 1 && preventASI) {
11047 removeLineBreaks(code, start, node.start);
11048 }
11049 if (includedNodes === 1) {
11050 const parentType = renderedParentType || this.parent.type;
11051 node.render(code, options, {
11052 isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
11053 renderedParentType: parentType,
11054 renderedSurroundingElement: parentType
11055 });
11056 }
11057 else {
11058 node.render(code, options);
11059 }
11060 }
11061 if (lastSeparatorPos) {
11062 code.remove(lastSeparatorPos, this.end);
11063 }
11064 }
11065}
11066
11067class StaticBlock extends NodeBase {
11068 createScope(parentScope) {
11069 this.scope = new BlockScope(parentScope);
11070 }
11071 hasEffects(context) {
11072 for (const node of this.body) {
11073 if (node.hasEffects(context))
11074 return true;
11075 }
11076 return false;
11077 }
11078 include(context, includeChildrenRecursively) {
11079 this.included = true;
11080 for (const node of this.body) {
11081 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11082 node.include(context, includeChildrenRecursively);
11083 }
11084 }
11085 render(code, options) {
11086 if (this.body.length) {
11087 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11088 }
11089 else {
11090 super.render(code, options);
11091 }
11092 }
11093}
11094
11095class Super extends NodeBase {
11096 bind() {
11097 this.variable = this.scope.findVariable('this');
11098 }
11099 deoptimizePath(path) {
11100 this.variable.deoptimizePath(path);
11101 }
11102 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11103 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11104 }
11105 include() {
11106 if (!this.included) {
11107 this.included = true;
11108 this.context.includeVariableInModule(this.variable);
11109 }
11110 }
11111}
11112
11113class SwitchCase extends NodeBase {
11114 hasEffects(context) {
11115 var _a;
11116 if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
11117 return true;
11118 for (const node of this.consequent) {
11119 if (context.brokenFlow)
11120 break;
11121 if (node.hasEffects(context))
11122 return true;
11123 }
11124 return false;
11125 }
11126 include(context, includeChildrenRecursively) {
11127 var _a;
11128 this.included = true;
11129 (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11130 for (const node of this.consequent) {
11131 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11132 node.include(context, includeChildrenRecursively);
11133 }
11134 }
11135 render(code, options, nodeRenderOptions) {
11136 if (this.consequent.length) {
11137 this.test && this.test.render(code, options);
11138 const testEnd = this.test
11139 ? this.test.end
11140 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
11141 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
11142 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
11143 }
11144 else {
11145 super.render(code, options);
11146 }
11147 }
11148}
11149SwitchCase.prototype.needsBoundaries = true;
11150
11151class SwitchStatement extends NodeBase {
11152 createScope(parentScope) {
11153 this.scope = new BlockScope(parentScope);
11154 }
11155 hasEffects(context) {
11156 if (this.discriminant.hasEffects(context))
11157 return true;
11158 const { brokenFlow, ignore: { breaks } } = context;
11159 let minBrokenFlow = Infinity;
11160 context.ignore.breaks = true;
11161 for (const switchCase of this.cases) {
11162 if (switchCase.hasEffects(context))
11163 return true;
11164 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
11165 context.brokenFlow = brokenFlow;
11166 }
11167 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11168 context.brokenFlow = minBrokenFlow;
11169 }
11170 context.ignore.breaks = breaks;
11171 return false;
11172 }
11173 include(context, includeChildrenRecursively) {
11174 this.included = true;
11175 this.discriminant.include(context, includeChildrenRecursively);
11176 const { brokenFlow } = context;
11177 let minBrokenFlow = Infinity;
11178 let isCaseIncluded = includeChildrenRecursively ||
11179 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
11180 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
11181 const switchCase = this.cases[caseIndex];
11182 if (switchCase.included) {
11183 isCaseIncluded = true;
11184 }
11185 if (!isCaseIncluded) {
11186 const hasEffectsContext = createHasEffectsContext();
11187 hasEffectsContext.ignore.breaks = true;
11188 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
11189 }
11190 if (isCaseIncluded) {
11191 switchCase.include(context, includeChildrenRecursively);
11192 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
11193 context.brokenFlow = brokenFlow;
11194 }
11195 else {
11196 minBrokenFlow = brokenFlow;
11197 }
11198 }
11199 if (isCaseIncluded &&
11200 this.defaultCase !== null &&
11201 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11202 context.brokenFlow = minBrokenFlow;
11203 }
11204 }
11205 initialise() {
11206 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
11207 if (this.cases[caseIndex].test === null) {
11208 this.defaultCase = caseIndex;
11209 return;
11210 }
11211 }
11212 this.defaultCase = null;
11213 }
11214 render(code, options) {
11215 this.discriminant.render(code, options);
11216 if (this.cases.length > 0) {
11217 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
11218 }
11219 }
11220}
11221
11222class TaggedTemplateExpression extends CallExpressionBase {
11223 bind() {
11224 super.bind();
11225 if (this.tag.type === Identifier$1) {
11226 const name = this.tag.name;
11227 const variable = this.scope.findVariable(name);
11228 if (variable.isNamespace) {
11229 this.context.warn({
11230 code: 'CANNOT_CALL_NAMESPACE',
11231 message: `Cannot call a namespace ('${name}')`
11232 }, this.start);
11233 }
11234 }
11235 }
11236 hasEffects(context) {
11237 try {
11238 for (const argument of this.quasi.expressions) {
11239 if (argument.hasEffects(context))
11240 return true;
11241 }
11242 return (this.tag.hasEffects(context) ||
11243 this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
11244 }
11245 finally {
11246 if (!this.deoptimized)
11247 this.applyDeoptimizations();
11248 }
11249 }
11250 include(context, includeChildrenRecursively) {
11251 if (!this.deoptimized)
11252 this.applyDeoptimizations();
11253 if (includeChildrenRecursively) {
11254 super.include(context, includeChildrenRecursively);
11255 }
11256 else {
11257 this.included = true;
11258 this.tag.include(context, includeChildrenRecursively);
11259 this.quasi.include(context, includeChildrenRecursively);
11260 }
11261 this.tag.includeCallArguments(context, this.interaction.args);
11262 const returnExpression = this.getReturnExpression();
11263 if (!returnExpression.included) {
11264 returnExpression.include(context, false);
11265 }
11266 }
11267 initialise() {
11268 this.interaction = {
11269 args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
11270 thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
11271 type: INTERACTION_CALLED,
11272 withNew: false
11273 };
11274 }
11275 render(code, options) {
11276 this.tag.render(code, options, { isCalleeOfRenderedParent: true });
11277 this.quasi.render(code, options);
11278 }
11279 applyDeoptimizations() {
11280 this.deoptimized = true;
11281 if (this.interaction.thisArg) {
11282 this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
11283 }
11284 for (const argument of this.quasi.expressions) {
11285 // This will make sure all properties of parameters behave as "unknown"
11286 argument.deoptimizePath(UNKNOWN_PATH);
11287 }
11288 this.context.requestTreeshakingPass();
11289 }
11290 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
11291 if (this.returnExpression === null) {
11292 this.returnExpression = UNKNOWN_EXPRESSION;
11293 return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
11294 }
11295 return this.returnExpression;
11296 }
11297}
11298
11299class TemplateElement extends NodeBase {
11300 // Do not try to bind value
11301 bind() { }
11302 hasEffects() {
11303 return false;
11304 }
11305 include() {
11306 this.included = true;
11307 }
11308 parseNode(esTreeNode) {
11309 this.value = esTreeNode.value;
11310 super.parseNode(esTreeNode);
11311 }
11312 render() { }
11313}
11314
11315class TemplateLiteral extends NodeBase {
11316 deoptimizeThisOnInteractionAtPath() { }
11317 getLiteralValueAtPath(path) {
11318 if (path.length > 0 || this.quasis.length !== 1) {
11319 return UnknownValue;
11320 }
11321 return this.quasis[0].value.cooked;
11322 }
11323 getReturnExpressionWhenCalledAtPath(path) {
11324 if (path.length !== 1) {
11325 return UNKNOWN_EXPRESSION;
11326 }
11327 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
11328 }
11329 hasEffectsOnInteractionAtPath(path, interaction, context) {
11330 if (interaction.type === INTERACTION_ACCESSED) {
11331 return path.length > 1;
11332 }
11333 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
11334 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
11335 }
11336 return true;
11337 }
11338 render(code, options) {
11339 code.indentExclusionRanges.push([this.start, this.end]);
11340 super.render(code, options);
11341 }
11342}
11343
11344class UndefinedVariable extends Variable {
11345 constructor() {
11346 super('undefined');
11347 }
11348 getLiteralValueAtPath() {
11349 return undefined;
11350 }
11351}
11352
11353class ExportDefaultVariable extends LocalVariable {
11354 constructor(name, exportDefaultDeclaration, context) {
11355 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
11356 this.hasId = false;
11357 this.originalId = null;
11358 this.originalVariable = null;
11359 const declaration = exportDefaultDeclaration.declaration;
11360 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
11361 declaration.id) {
11362 this.hasId = true;
11363 this.originalId = declaration.id;
11364 }
11365 else if (declaration instanceof Identifier) {
11366 this.originalId = declaration;
11367 }
11368 }
11369 addReference(identifier) {
11370 if (!this.hasId) {
11371 this.name = identifier.name;
11372 }
11373 }
11374 getAssignedVariableName() {
11375 return (this.originalId && this.originalId.name) || null;
11376 }
11377 getBaseVariableName() {
11378 const original = this.getOriginalVariable();
11379 if (original === this) {
11380 return super.getBaseVariableName();
11381 }
11382 else {
11383 return original.getBaseVariableName();
11384 }
11385 }
11386 getDirectOriginalVariable() {
11387 return this.originalId &&
11388 (this.hasId ||
11389 !(this.originalId.isPossibleTDZ() ||
11390 this.originalId.variable.isReassigned ||
11391 this.originalId.variable instanceof UndefinedVariable ||
11392 // this avoids a circular dependency
11393 'syntheticNamespace' in this.originalId.variable))
11394 ? this.originalId.variable
11395 : null;
11396 }
11397 getName(getPropertyAccess) {
11398 const original = this.getOriginalVariable();
11399 if (original === this) {
11400 return super.getName(getPropertyAccess);
11401 }
11402 else {
11403 return original.getName(getPropertyAccess);
11404 }
11405 }
11406 getOriginalVariable() {
11407 if (this.originalVariable)
11408 return this.originalVariable;
11409 // eslint-disable-next-line @typescript-eslint/no-this-alias
11410 let original = this;
11411 let currentVariable;
11412 const checkedVariables = new Set();
11413 do {
11414 checkedVariables.add(original);
11415 currentVariable = original;
11416 original = currentVariable.getDirectOriginalVariable();
11417 } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
11418 return (this.originalVariable = original || currentVariable);
11419 }
11420}
11421
11422class ModuleScope extends ChildScope {
11423 constructor(parent, context) {
11424 super(parent);
11425 this.context = context;
11426 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
11427 }
11428 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
11429 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
11430 this.variables.set('default', variable);
11431 return variable;
11432 }
11433 addNamespaceMemberAccess() { }
11434 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
11435 // all module level variables are already deconflicted when deconflicting the chunk
11436 for (const scope of this.children)
11437 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
11438 }
11439 findLexicalBoundary() {
11440 return this;
11441 }
11442 findVariable(name) {
11443 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
11444 if (knownVariable) {
11445 return knownVariable;
11446 }
11447 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
11448 if (variable instanceof GlobalVariable) {
11449 this.accessedOutsideVariables.set(name, variable);
11450 }
11451 return variable;
11452 }
11453}
11454
11455class ThisExpression extends NodeBase {
11456 bind() {
11457 this.variable = this.scope.findVariable('this');
11458 }
11459 deoptimizePath(path) {
11460 this.variable.deoptimizePath(path);
11461 }
11462 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11463 // We rewrite the parameter so that a ThisVariable can detect self-mutations
11464 this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
11465 }
11466 hasEffectsOnInteractionAtPath(path, interaction, context) {
11467 if (path.length === 0) {
11468 return interaction.type !== INTERACTION_ACCESSED;
11469 }
11470 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
11471 }
11472 include() {
11473 if (!this.included) {
11474 this.included = true;
11475 this.context.includeVariableInModule(this.variable);
11476 }
11477 }
11478 initialise() {
11479 this.alias =
11480 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
11481 if (this.alias === 'undefined') {
11482 this.context.warn({
11483 code: 'THIS_IS_UNDEFINED',
11484 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
11485 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
11486 }, this.start);
11487 }
11488 }
11489 render(code) {
11490 if (this.alias !== null) {
11491 code.overwrite(this.start, this.end, this.alias, {
11492 contentOnly: false,
11493 storeName: true
11494 });
11495 }
11496 }
11497}
11498
11499class ThrowStatement extends NodeBase {
11500 hasEffects() {
11501 return true;
11502 }
11503 include(context, includeChildrenRecursively) {
11504 this.included = true;
11505 this.argument.include(context, includeChildrenRecursively);
11506 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11507 }
11508 render(code, options) {
11509 this.argument.render(code, options, { preventASI: true });
11510 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
11511 code.prependLeft(this.start + 5, ' ');
11512 }
11513 }
11514}
11515
11516class TryStatement extends NodeBase {
11517 constructor() {
11518 super(...arguments);
11519 this.directlyIncluded = false;
11520 this.includedLabelsAfterBlock = null;
11521 }
11522 hasEffects(context) {
11523 var _a;
11524 return ((this.context.options.treeshake.tryCatchDeoptimization
11525 ? this.block.body.length > 0
11526 : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11527 }
11528 include(context, includeChildrenRecursively) {
11529 var _a, _b;
11530 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
11531 const { brokenFlow } = context;
11532 if (!this.directlyIncluded || !tryCatchDeoptimization) {
11533 this.included = true;
11534 this.directlyIncluded = true;
11535 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
11536 if (context.includedLabels.size > 0) {
11537 this.includedLabelsAfterBlock = [...context.includedLabels];
11538 }
11539 context.brokenFlow = brokenFlow;
11540 }
11541 else if (this.includedLabelsAfterBlock) {
11542 for (const label of this.includedLabelsAfterBlock) {
11543 context.includedLabels.add(label);
11544 }
11545 }
11546 if (this.handler !== null) {
11547 this.handler.include(context, includeChildrenRecursively);
11548 context.brokenFlow = brokenFlow;
11549 }
11550 (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
11551 }
11552}
11553
11554const unaryOperators = {
11555 '!': value => !value,
11556 '+': value => +value,
11557 '-': value => -value,
11558 delete: () => UnknownValue,
11559 typeof: value => typeof value,
11560 void: () => undefined,
11561 '~': value => ~value
11562};
11563class UnaryExpression extends NodeBase {
11564 getLiteralValueAtPath(path, recursionTracker, origin) {
11565 if (path.length > 0)
11566 return UnknownValue;
11567 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11568 if (typeof argumentValue === 'symbol')
11569 return UnknownValue;
11570 return unaryOperators[this.operator](argumentValue);
11571 }
11572 hasEffects(context) {
11573 if (!this.deoptimized)
11574 this.applyDeoptimizations();
11575 if (this.operator === 'typeof' && this.argument instanceof Identifier)
11576 return false;
11577 return (this.argument.hasEffects(context) ||
11578 (this.operator === 'delete' &&
11579 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
11580 }
11581 hasEffectsOnInteractionAtPath(path, { type }) {
11582 return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
11583 }
11584 applyDeoptimizations() {
11585 this.deoptimized = true;
11586 if (this.operator === 'delete') {
11587 this.argument.deoptimizePath(EMPTY_PATH);
11588 this.context.requestTreeshakingPass();
11589 }
11590 }
11591}
11592
11593class UnknownNode extends NodeBase {
11594 hasEffects() {
11595 return true;
11596 }
11597 include(context) {
11598 super.include(context, true);
11599 }
11600}
11601
11602class UpdateExpression extends NodeBase {
11603 hasEffects(context) {
11604 if (!this.deoptimized)
11605 this.applyDeoptimizations();
11606 return this.argument.hasEffectsAsAssignmentTarget(context, true);
11607 }
11608 hasEffectsOnInteractionAtPath(path, { type }) {
11609 return path.length > 1 || type !== INTERACTION_ACCESSED;
11610 }
11611 include(context, includeChildrenRecursively) {
11612 if (!this.deoptimized)
11613 this.applyDeoptimizations();
11614 this.included = true;
11615 this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
11616 }
11617 initialise() {
11618 this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
11619 }
11620 render(code, options) {
11621 const { exportNamesByVariable, format, snippets: { _ } } = options;
11622 this.argument.render(code, options);
11623 if (format === 'system') {
11624 const variable = this.argument.variable;
11625 const exportNames = exportNamesByVariable.get(variable);
11626 if (exportNames) {
11627 if (this.prefix) {
11628 if (exportNames.length === 1) {
11629 renderSystemExportExpression(variable, this.start, this.end, code, options);
11630 }
11631 else {
11632 renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
11633 }
11634 }
11635 else {
11636 const operator = this.operator[0];
11637 renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
11638 }
11639 }
11640 }
11641 }
11642 applyDeoptimizations() {
11643 this.deoptimized = true;
11644 this.argument.deoptimizePath(EMPTY_PATH);
11645 if (this.argument instanceof Identifier) {
11646 const variable = this.scope.findVariable(this.argument.name);
11647 variable.isReassigned = true;
11648 }
11649 this.context.requestTreeshakingPass();
11650 }
11651}
11652
11653function isReassignedExportsMember(variable, exportNamesByVariable) {
11654 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
11655}
11656
11657function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
11658 for (const declarator of declarations) {
11659 if (!declarator.id.included)
11660 return false;
11661 if (declarator.id.type === Identifier$1) {
11662 if (exportNamesByVariable.has(declarator.id.variable))
11663 return false;
11664 }
11665 else {
11666 const exportedVariables = [];
11667 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
11668 if (exportedVariables.length > 0)
11669 return false;
11670 }
11671 }
11672 return true;
11673}
11674class VariableDeclaration extends NodeBase {
11675 deoptimizePath() {
11676 for (const declarator of this.declarations) {
11677 declarator.deoptimizePath(EMPTY_PATH);
11678 }
11679 }
11680 hasEffectsOnInteractionAtPath() {
11681 return false;
11682 }
11683 include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
11684 this.included = true;
11685 for (const declarator of this.declarations) {
11686 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
11687 declarator.include(context, includeChildrenRecursively);
11688 if (asSingleStatement) {
11689 declarator.id.include(context, includeChildrenRecursively);
11690 }
11691 }
11692 }
11693 initialise() {
11694 for (const declarator of this.declarations) {
11695 declarator.declareDeclarator(this.kind);
11696 }
11697 }
11698 render(code, options, nodeRenderOptions = BLANK) {
11699 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
11700 for (const declarator of this.declarations) {
11701 declarator.render(code, options);
11702 }
11703 if (!nodeRenderOptions.isNoStatement &&
11704 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
11705 code.appendLeft(this.end, ';');
11706 }
11707 }
11708 else {
11709 this.renderReplacedDeclarations(code, options);
11710 }
11711 }
11712 applyDeoptimizations() { }
11713 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
11714 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
11715 code.remove(this.end - 1, this.end);
11716 }
11717 separatorString += ';';
11718 if (lastSeparatorPos !== null) {
11719 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
11720 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
11721 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
11722 actualContentEnd--;
11723 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
11724 actualContentEnd--;
11725 }
11726 }
11727 if (actualContentEnd === lastSeparatorPos + 1) {
11728 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
11729 }
11730 else {
11731 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11732 code.remove(actualContentEnd, renderedContentEnd);
11733 }
11734 }
11735 else {
11736 code.appendLeft(renderedContentEnd, separatorString);
11737 }
11738 if (systemPatternExports.length > 0) {
11739 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
11740 }
11741 }
11742 renderReplacedDeclarations(code, options) {
11743 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
11744 let actualContentEnd, renderedContentEnd;
11745 renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
11746 let lastSeparatorPos = renderedContentEnd - 1;
11747 code.remove(this.start, lastSeparatorPos);
11748 let isInDeclaration = false;
11749 let hasRenderedContent = false;
11750 let separatorString = '', leadingString, nextSeparatorString;
11751 const aggregatedSystemExports = [];
11752 const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
11753 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
11754 if (!node.included) {
11755 code.remove(start, end);
11756 continue;
11757 }
11758 node.render(code, options);
11759 leadingString = '';
11760 nextSeparatorString = '';
11761 if (!node.id.included ||
11762 (node.id instanceof Identifier &&
11763 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
11764 if (hasRenderedContent) {
11765 separatorString += ';';
11766 }
11767 isInDeclaration = false;
11768 }
11769 else {
11770 if (singleSystemExport && singleSystemExport === node.id.variable) {
11771 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
11772 renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
11773 }
11774 if (isInDeclaration) {
11775 separatorString += ',';
11776 }
11777 else {
11778 if (hasRenderedContent) {
11779 separatorString += ';';
11780 }
11781 leadingString += `${this.kind} `;
11782 isInDeclaration = true;
11783 }
11784 }
11785 if (renderedContentEnd === lastSeparatorPos + 1) {
11786 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
11787 }
11788 else {
11789 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11790 code.appendLeft(renderedContentEnd, leadingString);
11791 }
11792 actualContentEnd = contentEnd;
11793 renderedContentEnd = end;
11794 hasRenderedContent = true;
11795 lastSeparatorPos = separator;
11796 separatorString = nextSeparatorString;
11797 }
11798 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
11799 }
11800}
11801function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
11802 var _a;
11803 let singleSystemExport = null;
11804 if (options.format === 'system') {
11805 for (const { node } of separatedNodes) {
11806 if (node.id instanceof Identifier &&
11807 node.init &&
11808 aggregatedSystemExports.length === 0 &&
11809 ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
11810 singleSystemExport = node.id.variable;
11811 aggregatedSystemExports.push(singleSystemExport);
11812 }
11813 else {
11814 node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
11815 }
11816 }
11817 if (aggregatedSystemExports.length > 1) {
11818 singleSystemExport = null;
11819 }
11820 else if (singleSystemExport) {
11821 aggregatedSystemExports.length = 0;
11822 }
11823 }
11824 return singleSystemExport;
11825}
11826
11827class VariableDeclarator extends NodeBase {
11828 declareDeclarator(kind) {
11829 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
11830 }
11831 deoptimizePath(path) {
11832 this.id.deoptimizePath(path);
11833 }
11834 hasEffects(context) {
11835 var _a;
11836 const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
11837 this.id.markDeclarationReached();
11838 return initEffect || this.id.hasEffects(context);
11839 }
11840 include(context, includeChildrenRecursively) {
11841 var _a;
11842 this.included = true;
11843 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11844 this.id.markDeclarationReached();
11845 if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
11846 this.id.include(context, includeChildrenRecursively);
11847 }
11848 }
11849 render(code, options) {
11850 const { exportNamesByVariable, snippets: { _ } } = options;
11851 const renderId = this.id.included;
11852 if (renderId) {
11853 this.id.render(code, options);
11854 }
11855 else {
11856 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
11857 code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
11858 }
11859 if (this.init) {
11860 this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
11861 }
11862 else if (this.id instanceof Identifier &&
11863 isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
11864 code.appendLeft(this.end, `${_}=${_}void 0`);
11865 }
11866 }
11867 applyDeoptimizations() { }
11868}
11869
11870class WhileStatement extends NodeBase {
11871 hasEffects(context) {
11872 if (this.test.hasEffects(context))
11873 return true;
11874 const { brokenFlow, ignore: { breaks, continues } } = context;
11875 context.ignore.breaks = true;
11876 context.ignore.continues = true;
11877 if (this.body.hasEffects(context))
11878 return true;
11879 context.ignore.breaks = breaks;
11880 context.ignore.continues = continues;
11881 context.brokenFlow = brokenFlow;
11882 return false;
11883 }
11884 include(context, includeChildrenRecursively) {
11885 this.included = true;
11886 this.test.include(context, includeChildrenRecursively);
11887 const { brokenFlow } = context;
11888 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
11889 context.brokenFlow = brokenFlow;
11890 }
11891}
11892
11893class YieldExpression extends NodeBase {
11894 hasEffects(context) {
11895 var _a;
11896 if (!this.deoptimized)
11897 this.applyDeoptimizations();
11898 return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11899 }
11900 render(code, options) {
11901 if (this.argument) {
11902 this.argument.render(code, options, { preventASI: true });
11903 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
11904 code.prependLeft(this.start + 5, ' ');
11905 }
11906 }
11907 }
11908}
11909
11910const nodeConstructors = {
11911 ArrayExpression,
11912 ArrayPattern,
11913 ArrowFunctionExpression,
11914 AssignmentExpression,
11915 AssignmentPattern,
11916 AwaitExpression,
11917 BinaryExpression,
11918 BlockStatement,
11919 BreakStatement,
11920 CallExpression,
11921 CatchClause,
11922 ChainExpression,
11923 ClassBody,
11924 ClassDeclaration,
11925 ClassExpression,
11926 ConditionalExpression,
11927 ContinueStatement,
11928 DoWhileStatement,
11929 EmptyStatement,
11930 ExportAllDeclaration,
11931 ExportDefaultDeclaration,
11932 ExportNamedDeclaration,
11933 ExportSpecifier,
11934 ExpressionStatement,
11935 ForInStatement,
11936 ForOfStatement,
11937 ForStatement,
11938 FunctionDeclaration,
11939 FunctionExpression,
11940 Identifier,
11941 IfStatement,
11942 ImportDeclaration,
11943 ImportDefaultSpecifier,
11944 ImportExpression,
11945 ImportNamespaceSpecifier,
11946 ImportSpecifier,
11947 LabeledStatement,
11948 Literal,
11949 LogicalExpression,
11950 MemberExpression,
11951 MetaProperty,
11952 MethodDefinition,
11953 NewExpression,
11954 ObjectExpression,
11955 ObjectPattern,
11956 PrivateIdentifier,
11957 Program,
11958 Property,
11959 PropertyDefinition,
11960 RestElement,
11961 ReturnStatement,
11962 SequenceExpression,
11963 SpreadElement,
11964 StaticBlock,
11965 Super,
11966 SwitchCase,
11967 SwitchStatement,
11968 TaggedTemplateExpression,
11969 TemplateElement,
11970 TemplateLiteral,
11971 ThisExpression,
11972 ThrowStatement,
11973 TryStatement,
11974 UnaryExpression,
11975 UnknownNode,
11976 UpdateExpression,
11977 VariableDeclaration,
11978 VariableDeclarator,
11979 WhileStatement,
11980 YieldExpression
11981};
11982
11983const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
11984
11985class ExportShimVariable extends Variable {
11986 constructor(module) {
11987 super(MISSING_EXPORT_SHIM_VARIABLE);
11988 this.module = module;
11989 }
11990 include() {
11991 super.include();
11992 this.module.needsExportShim = true;
11993 }
11994}
11995
11996class NamespaceVariable extends Variable {
11997 constructor(context) {
11998 super(context.getModuleName());
11999 this.memberVariables = null;
12000 this.mergedNamespaces = [];
12001 this.referencedEarly = false;
12002 this.references = [];
12003 this.context = context;
12004 this.module = context.module;
12005 }
12006 addReference(identifier) {
12007 this.references.push(identifier);
12008 this.name = identifier.name;
12009 }
12010 getMemberVariables() {
12011 if (this.memberVariables) {
12012 return this.memberVariables;
12013 }
12014 const memberVariables = Object.create(null);
12015 for (const name of this.context.getExports().concat(this.context.getReexports())) {
12016 if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
12017 const exportedVariable = this.context.traceExport(name);
12018 if (exportedVariable) {
12019 memberVariables[name] = exportedVariable;
12020 }
12021 }
12022 }
12023 return (this.memberVariables = memberVariables);
12024 }
12025 include() {
12026 this.included = true;
12027 this.context.includeAllExports();
12028 }
12029 prepare(accessedGlobalsByScope) {
12030 if (this.mergedNamespaces.length > 0) {
12031 this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
12032 }
12033 }
12034 renderBlock(options) {
12035 const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
12036 const memberVariables = this.getMemberVariables();
12037 const members = Object.entries(memberVariables).map(([name, original]) => {
12038 if (this.referencedEarly || original.isReassigned) {
12039 return [
12040 null,
12041 `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
12042 ];
12043 }
12044 return [name, original.getName(getPropertyAccess)];
12045 });
12046 members.unshift([null, `__proto__:${_}null`]);
12047 let output = getObject(members, { lineBreakIndent: { base: '', t } });
12048 if (this.mergedNamespaces.length > 0) {
12049 const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
12050 output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
12051 }
12052 else {
12053 // The helper to merge namespaces will also take care of freezing and toStringTag
12054 if (namespaceToStringTag) {
12055 output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
12056 }
12057 if (freeze) {
12058 output = `/*#__PURE__*/Object.freeze(${output})`;
12059 }
12060 }
12061 const name = this.getName(getPropertyAccess);
12062 output = `${cnst} ${name}${_}=${_}${output};`;
12063 if (format === 'system' && exportNamesByVariable.has(this)) {
12064 output += `${n}${getSystemExportStatement([this], options)};`;
12065 }
12066 return output;
12067 }
12068 renderFirst() {
12069 return this.referencedEarly;
12070 }
12071 setMergedNamespaces(mergedNamespaces) {
12072 this.mergedNamespaces = mergedNamespaces;
12073 const moduleExecIndex = this.context.getModuleExecIndex();
12074 for (const identifier of this.references) {
12075 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
12076 this.referencedEarly = true;
12077 break;
12078 }
12079 }
12080 }
12081}
12082NamespaceVariable.prototype.isNamespace = true;
12083
12084class SyntheticNamedExportVariable extends Variable {
12085 constructor(context, name, syntheticNamespace) {
12086 super(name);
12087 this.baseVariable = null;
12088 this.context = context;
12089 this.module = context.module;
12090 this.syntheticNamespace = syntheticNamespace;
12091 }
12092 getBaseVariable() {
12093 if (this.baseVariable)
12094 return this.baseVariable;
12095 let baseVariable = this.syntheticNamespace;
12096 while (baseVariable instanceof ExportDefaultVariable ||
12097 baseVariable instanceof SyntheticNamedExportVariable) {
12098 if (baseVariable instanceof ExportDefaultVariable) {
12099 const original = baseVariable.getOriginalVariable();
12100 if (original === baseVariable)
12101 break;
12102 baseVariable = original;
12103 }
12104 if (baseVariable instanceof SyntheticNamedExportVariable) {
12105 baseVariable = baseVariable.syntheticNamespace;
12106 }
12107 }
12108 return (this.baseVariable = baseVariable);
12109 }
12110 getBaseVariableName() {
12111 return this.syntheticNamespace.getBaseVariableName();
12112 }
12113 getName(getPropertyAccess) {
12114 return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
12115 }
12116 include() {
12117 this.included = true;
12118 this.context.includeVariableInModule(this.syntheticNamespace);
12119 }
12120 setRenderNames(baseName, name) {
12121 super.setRenderNames(baseName, name);
12122 }
12123}
12124
12125var BuildPhase;
12126(function (BuildPhase) {
12127 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
12128 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
12129 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
12130})(BuildPhase || (BuildPhase = {}));
12131
12132function getId(m) {
12133 return m.id;
12134}
12135
12136function getOriginalLocation(sourcemapChain, location) {
12137 const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
12138 traceSourcemap: while (filteredSourcemapChain.length > 0) {
12139 const sourcemap = filteredSourcemapChain.pop();
12140 const line = sourcemap.mappings[location.line - 1];
12141 if (line) {
12142 const filteredLine = line.filter((segment) => segment.length > 1);
12143 const lastSegment = filteredLine[filteredLine.length - 1];
12144 for (const segment of filteredLine) {
12145 if (segment[0] >= location.column || segment === lastSegment) {
12146 location = {
12147 column: segment[3],
12148 line: segment[2] + 1
12149 };
12150 continue traceSourcemap;
12151 }
12152 }
12153 }
12154 throw new Error("Can't resolve original location of error.");
12155 }
12156 return location;
12157}
12158
12159const NOOP = () => { };
12160let timers = new Map();
12161function getPersistedLabel(label, level) {
12162 switch (level) {
12163 case 1:
12164 return `# ${label}`;
12165 case 2:
12166 return `## ${label}`;
12167 case 3:
12168 return label;
12169 default:
12170 return `${' '.repeat(level - 4)}- ${label}`;
12171 }
12172}
12173function timeStartImpl(label, level = 3) {
12174 label = getPersistedLabel(label, level);
12175 const startMemory = process$1.memoryUsage().heapUsed;
12176 const startTime = performance.now();
12177 const timer = timers.get(label);
12178 if (timer === undefined) {
12179 timers.set(label, {
12180 memory: 0,
12181 startMemory,
12182 startTime,
12183 time: 0,
12184 totalMemory: 0
12185 });
12186 }
12187 else {
12188 timer.startMemory = startMemory;
12189 timer.startTime = startTime;
12190 }
12191}
12192function timeEndImpl(label, level = 3) {
12193 label = getPersistedLabel(label, level);
12194 const timer = timers.get(label);
12195 if (timer !== undefined) {
12196 const currentMemory = process$1.memoryUsage().heapUsed;
12197 timer.memory += currentMemory - timer.startMemory;
12198 timer.time += performance.now() - timer.startTime;
12199 timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
12200 }
12201}
12202function getTimings() {
12203 const newTimings = {};
12204 for (const [label, { memory, time, totalMemory }] of timers) {
12205 newTimings[label] = [time, memory, totalMemory];
12206 }
12207 return newTimings;
12208}
12209let timeStart = NOOP;
12210let timeEnd = NOOP;
12211const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
12212function getPluginWithTimers(plugin, index) {
12213 for (const hook of TIMED_PLUGIN_HOOKS) {
12214 if (hook in plugin) {
12215 let timerLabel = `plugin ${index}`;
12216 if (plugin.name) {
12217 timerLabel += ` (${plugin.name})`;
12218 }
12219 timerLabel += ` - ${hook}`;
12220 const func = plugin[hook];
12221 plugin[hook] = function (...args) {
12222 timeStart(timerLabel, 4);
12223 const result = func.apply(this, args);
12224 timeEnd(timerLabel, 4);
12225 if (result && typeof result.then === 'function') {
12226 timeStart(`${timerLabel} (async)`, 4);
12227 return result.then((hookResult) => {
12228 timeEnd(`${timerLabel} (async)`, 4);
12229 return hookResult;
12230 });
12231 }
12232 return result;
12233 };
12234 }
12235 }
12236 return plugin;
12237}
12238function initialiseTimers(inputOptions) {
12239 if (inputOptions.perf) {
12240 timers = new Map();
12241 timeStart = timeStartImpl;
12242 timeEnd = timeEndImpl;
12243 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
12244 }
12245 else {
12246 timeStart = NOOP;
12247 timeEnd = NOOP;
12248 }
12249}
12250
12251function markModuleAndImpureDependenciesAsExecuted(baseModule) {
12252 baseModule.isExecuted = true;
12253 const modules = [baseModule];
12254 const visitedModules = new Set();
12255 for (const module of modules) {
12256 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
12257 if (!(dependency instanceof ExternalModule) &&
12258 !dependency.isExecuted &&
12259 (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
12260 !visitedModules.has(dependency.id)) {
12261 dependency.isExecuted = true;
12262 visitedModules.add(dependency.id);
12263 modules.push(dependency);
12264 }
12265 }
12266 }
12267}
12268
12269const MISSING_EXPORT_SHIM_DESCRIPTION = {
12270 identifier: null,
12271 localName: MISSING_EXPORT_SHIM_VARIABLE
12272};
12273function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
12274 const searchedModules = searchedNamesAndModules.get(name);
12275 if (searchedModules) {
12276 if (searchedModules.has(target)) {
12277 return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
12278 }
12279 searchedModules.add(target);
12280 }
12281 else {
12282 searchedNamesAndModules.set(name, new Set([target]));
12283 }
12284 return target.getVariableForExportName(name, {
12285 importerForSideEffects,
12286 isExportAllSearch,
12287 searchedNamesAndModules
12288 });
12289}
12290function getAndExtendSideEffectModules(variable, module) {
12291 const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
12292 let currentVariable = variable;
12293 const referencedVariables = new Set([currentVariable]);
12294 while (true) {
12295 const importingModule = currentVariable.module;
12296 currentVariable =
12297 currentVariable instanceof ExportDefaultVariable
12298 ? currentVariable.getDirectOriginalVariable()
12299 : currentVariable instanceof SyntheticNamedExportVariable
12300 ? currentVariable.syntheticNamespace
12301 : null;
12302 if (!currentVariable || referencedVariables.has(currentVariable)) {
12303 break;
12304 }
12305 referencedVariables.add(currentVariable);
12306 sideEffectModules.add(importingModule);
12307 const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
12308 if (originalSideEffects) {
12309 for (const module of originalSideEffects) {
12310 sideEffectModules.add(module);
12311 }
12312 }
12313 }
12314 return sideEffectModules;
12315}
12316class Module {
12317 constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
12318 this.graph = graph;
12319 this.id = id;
12320 this.options = options;
12321 this.alternativeReexportModules = new Map();
12322 this.chunkFileNames = new Set();
12323 this.chunkNames = [];
12324 this.cycles = new Set();
12325 this.dependencies = new Set();
12326 this.dynamicDependencies = new Set();
12327 this.dynamicImporters = [];
12328 this.dynamicImports = [];
12329 this.execIndex = Infinity;
12330 this.implicitlyLoadedAfter = new Set();
12331 this.implicitlyLoadedBefore = new Set();
12332 this.importDescriptions = new Map();
12333 this.importMetas = [];
12334 this.importedFromNotTreeshaken = false;
12335 this.importers = [];
12336 this.includedDynamicImporters = [];
12337 this.includedImports = new Set();
12338 this.isExecuted = false;
12339 this.isUserDefinedEntryPoint = false;
12340 this.needsExportShim = false;
12341 this.sideEffectDependenciesByVariable = new Map();
12342 this.sources = new Set();
12343 this.usesTopLevelAwait = false;
12344 this.allExportNames = null;
12345 this.ast = null;
12346 this.exportAllModules = [];
12347 this.exportAllSources = new Set();
12348 this.exportNamesByVariable = null;
12349 this.exportShimVariable = new ExportShimVariable(this);
12350 this.exports = new Map();
12351 this.namespaceReexportsByName = new Map();
12352 this.reexportDescriptions = new Map();
12353 this.relevantDependencies = null;
12354 this.syntheticExports = new Map();
12355 this.syntheticNamespace = null;
12356 this.transformDependencies = [];
12357 this.transitiveReexports = null;
12358 this.excludeFromSourcemap = /\0/.test(id);
12359 this.context = options.moduleContext(id);
12360 this.preserveSignature = this.options.preserveEntrySignatures;
12361 // eslint-disable-next-line @typescript-eslint/no-this-alias
12362 const module = this;
12363 const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
12364 this.info = {
12365 ast: null,
12366 code: null,
12367 get dynamicallyImportedIdResolutions() {
12368 return dynamicImports
12369 .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
12370 .filter(Boolean);
12371 },
12372 get dynamicallyImportedIds() {
12373 // We cannot use this.dynamicDependencies because this is needed before
12374 // dynamicDependencies are populated
12375 return dynamicImports.map(({ id }) => id).filter((id) => id != null);
12376 },
12377 get dynamicImporters() {
12378 return dynamicImporters.sort();
12379 },
12380 get hasDefaultExport() {
12381 // This information is only valid after parsing
12382 if (!module.ast) {
12383 return null;
12384 }
12385 return module.exports.has('default') || reexportDescriptions.has('default');
12386 },
12387 get hasModuleSideEffects() {
12388 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
12389 return this.moduleSideEffects;
12390 },
12391 id,
12392 get implicitlyLoadedAfterOneOf() {
12393 return Array.from(implicitlyLoadedAfter, getId).sort();
12394 },
12395 get implicitlyLoadedBefore() {
12396 return Array.from(implicitlyLoadedBefore, getId).sort();
12397 },
12398 get importedIdResolutions() {
12399 return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
12400 },
12401 get importedIds() {
12402 // We cannot use this.dependencies because this is needed before
12403 // dependencies are populated
12404 return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
12405 },
12406 get importers() {
12407 return importers.sort();
12408 },
12409 isEntry,
12410 isExternal: false,
12411 get isIncluded() {
12412 if (graph.phase !== BuildPhase.GENERATE) {
12413 return null;
12414 }
12415 return module.isIncluded();
12416 },
12417 meta: { ...meta },
12418 moduleSideEffects,
12419 syntheticNamedExports
12420 };
12421 // Hide the deprecated key so that it only warns when accessed explicitly
12422 Object.defineProperty(this.info, 'hasModuleSideEffects', {
12423 enumerable: false
12424 });
12425 }
12426 basename() {
12427 const base = basename(this.id);
12428 const ext = extname(this.id);
12429 return makeLegal(ext ? base.slice(0, -ext.length) : base);
12430 }
12431 bindReferences() {
12432 this.ast.bind();
12433 }
12434 error(props, pos) {
12435 this.addLocationToLogProps(props, pos);
12436 return error(props);
12437 }
12438 getAllExportNames() {
12439 if (this.allExportNames) {
12440 return this.allExportNames;
12441 }
12442 this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
12443 for (const module of this.exportAllModules) {
12444 if (module instanceof ExternalModule) {
12445 this.allExportNames.add(`*${module.id}`);
12446 continue;
12447 }
12448 for (const name of module.getAllExportNames()) {
12449 if (name !== 'default')
12450 this.allExportNames.add(name);
12451 }
12452 }
12453 // We do not count the synthetic namespace as a regular export to hide it
12454 // from entry signatures and namespace objects
12455 if (typeof this.info.syntheticNamedExports === 'string') {
12456 this.allExportNames.delete(this.info.syntheticNamedExports);
12457 }
12458 return this.allExportNames;
12459 }
12460 getDependenciesToBeIncluded() {
12461 if (this.relevantDependencies)
12462 return this.relevantDependencies;
12463 this.relevantDependencies = new Set();
12464 const necessaryDependencies = new Set();
12465 const alwaysCheckedDependencies = new Set();
12466 const dependencyVariables = new Set(this.includedImports);
12467 if (this.info.isEntry ||
12468 this.includedDynamicImporters.length > 0 ||
12469 this.namespace.included ||
12470 this.implicitlyLoadedAfter.size > 0) {
12471 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
12472 const [exportedVariable] = this.getVariableForExportName(exportName);
12473 if (exportedVariable) {
12474 dependencyVariables.add(exportedVariable);
12475 }
12476 }
12477 }
12478 for (let variable of dependencyVariables) {
12479 const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
12480 if (sideEffectDependencies) {
12481 for (const module of sideEffectDependencies) {
12482 alwaysCheckedDependencies.add(module);
12483 }
12484 }
12485 if (variable instanceof SyntheticNamedExportVariable) {
12486 variable = variable.getBaseVariable();
12487 }
12488 else if (variable instanceof ExportDefaultVariable) {
12489 variable = variable.getOriginalVariable();
12490 }
12491 necessaryDependencies.add(variable.module);
12492 }
12493 if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
12494 for (const dependency of this.dependencies) {
12495 this.relevantDependencies.add(dependency);
12496 }
12497 }
12498 else {
12499 this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
12500 }
12501 for (const dependency of necessaryDependencies) {
12502 this.relevantDependencies.add(dependency);
12503 }
12504 return this.relevantDependencies;
12505 }
12506 getExportNamesByVariable() {
12507 if (this.exportNamesByVariable) {
12508 return this.exportNamesByVariable;
12509 }
12510 const exportNamesByVariable = new Map();
12511 for (const exportName of this.getAllExportNames()) {
12512 let [tracedVariable] = this.getVariableForExportName(exportName);
12513 if (tracedVariable instanceof ExportDefaultVariable) {
12514 tracedVariable = tracedVariable.getOriginalVariable();
12515 }
12516 if (!tracedVariable ||
12517 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
12518 continue;
12519 }
12520 const existingExportNames = exportNamesByVariable.get(tracedVariable);
12521 if (existingExportNames) {
12522 existingExportNames.push(exportName);
12523 }
12524 else {
12525 exportNamesByVariable.set(tracedVariable, [exportName]);
12526 }
12527 }
12528 return (this.exportNamesByVariable = exportNamesByVariable);
12529 }
12530 getExports() {
12531 return Array.from(this.exports.keys());
12532 }
12533 getReexports() {
12534 if (this.transitiveReexports) {
12535 return this.transitiveReexports;
12536 }
12537 // to avoid infinite recursion when using circular `export * from X`
12538 this.transitiveReexports = [];
12539 const reexports = new Set(this.reexportDescriptions.keys());
12540 for (const module of this.exportAllModules) {
12541 if (module instanceof ExternalModule) {
12542 reexports.add(`*${module.id}`);
12543 }
12544 else {
12545 for (const name of [...module.getReexports(), ...module.getExports()]) {
12546 if (name !== 'default')
12547 reexports.add(name);
12548 }
12549 }
12550 }
12551 return (this.transitiveReexports = [...reexports]);
12552 }
12553 getRenderedExports() {
12554 // only direct exports are counted here, not reexports at all
12555 const renderedExports = [];
12556 const removedExports = [];
12557 for (const exportName of this.exports.keys()) {
12558 const [variable] = this.getVariableForExportName(exportName);
12559 (variable && variable.included ? renderedExports : removedExports).push(exportName);
12560 }
12561 return { removedExports, renderedExports };
12562 }
12563 getSyntheticNamespace() {
12564 if (this.syntheticNamespace === null) {
12565 this.syntheticNamespace = undefined;
12566 [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
12567 ? this.info.syntheticNamedExports
12568 : 'default', { onlyExplicit: true });
12569 }
12570 if (!this.syntheticNamespace) {
12571 return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
12572 }
12573 return this.syntheticNamespace;
12574 }
12575 getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
12576 var _a;
12577 if (name[0] === '*') {
12578 if (name.length === 1) {
12579 // export * from './other'
12580 return [this.namespace];
12581 }
12582 // export * from 'external'
12583 const module = this.graph.modulesById.get(name.slice(1));
12584 return module.getVariableForExportName('*');
12585 }
12586 // export { foo } from './other'
12587 const reexportDeclaration = this.reexportDescriptions.get(name);
12588 if (reexportDeclaration) {
12589 const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
12590 if (!variable) {
12591 return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
12592 }
12593 if (importerForSideEffects) {
12594 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12595 }
12596 return [variable];
12597 }
12598 const exportDeclaration = this.exports.get(name);
12599 if (exportDeclaration) {
12600 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
12601 return [this.exportShimVariable];
12602 }
12603 const name = exportDeclaration.localName;
12604 const variable = this.traceVariable(name, {
12605 importerForSideEffects,
12606 searchedNamesAndModules
12607 });
12608 if (importerForSideEffects) {
12609 getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
12610 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12611 }
12612 return [variable];
12613 }
12614 if (onlyExplicit) {
12615 return [null];
12616 }
12617 if (name !== 'default') {
12618 const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
12619 this.namespaceReexportsByName.set(name, foundNamespaceReexport);
12620 if (foundNamespaceReexport[0]) {
12621 return foundNamespaceReexport;
12622 }
12623 }
12624 if (this.info.syntheticNamedExports) {
12625 return [
12626 getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
12627 ];
12628 }
12629 // we don't want to create shims when we are just
12630 // probing export * modules for exports
12631 if (!isExportAllSearch) {
12632 if (this.options.shimMissingExports) {
12633 this.shimMissingExport(name);
12634 return [this.exportShimVariable];
12635 }
12636 }
12637 return [null];
12638 }
12639 hasEffects() {
12640 return (this.info.moduleSideEffects === 'no-treeshake' ||
12641 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
12642 }
12643 include() {
12644 const context = createInclusionContext();
12645 if (this.ast.shouldBeIncluded(context))
12646 this.ast.include(context, false);
12647 }
12648 includeAllExports(includeNamespaceMembers) {
12649 if (!this.isExecuted) {
12650 markModuleAndImpureDependenciesAsExecuted(this);
12651 this.graph.needsTreeshakingPass = true;
12652 }
12653 for (const exportName of this.exports.keys()) {
12654 if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
12655 const variable = this.getVariableForExportName(exportName)[0];
12656 variable.deoptimizePath(UNKNOWN_PATH);
12657 if (!variable.included) {
12658 this.includeVariable(variable);
12659 }
12660 }
12661 }
12662 for (const name of this.getReexports()) {
12663 const [variable] = this.getVariableForExportName(name);
12664 if (variable) {
12665 variable.deoptimizePath(UNKNOWN_PATH);
12666 if (!variable.included) {
12667 this.includeVariable(variable);
12668 }
12669 if (variable instanceof ExternalVariable) {
12670 variable.module.reexported = true;
12671 }
12672 }
12673 }
12674 if (includeNamespaceMembers) {
12675 this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
12676 }
12677 }
12678 includeAllInBundle() {
12679 this.ast.include(createInclusionContext(), true);
12680 this.includeAllExports(false);
12681 }
12682 isIncluded() {
12683 return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
12684 }
12685 linkImports() {
12686 this.addModulesToImportDescriptions(this.importDescriptions);
12687 this.addModulesToImportDescriptions(this.reexportDescriptions);
12688 const externalExportAllModules = [];
12689 for (const source of this.exportAllSources) {
12690 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
12691 if (module instanceof ExternalModule) {
12692 externalExportAllModules.push(module);
12693 continue;
12694 }
12695 this.exportAllModules.push(module);
12696 }
12697 this.exportAllModules.push(...externalExportAllModules);
12698 }
12699 render(options) {
12700 const magicString = this.magicString.clone();
12701 this.ast.render(magicString, options);
12702 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
12703 return magicString;
12704 }
12705 setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
12706 this.info.code = code;
12707 this.originalCode = originalCode;
12708 this.originalSourcemap = originalSourcemap;
12709 this.sourcemapChain = sourcemapChain;
12710 if (transformFiles) {
12711 this.transformFiles = transformFiles;
12712 }
12713 this.transformDependencies = transformDependencies;
12714 this.customTransformCache = customTransformCache;
12715 this.updateOptions(moduleOptions);
12716 timeStart('generate ast', 3);
12717 if (!ast) {
12718 ast = this.tryParse();
12719 }
12720 timeEnd('generate ast', 3);
12721 this.resolvedIds = resolvedIds || Object.create(null);
12722 // By default, `id` is the file name. Custom resolvers and loaders
12723 // can change that, but it makes sense to use it for the source file name
12724 const fileName = this.id;
12725 this.magicString = new MagicString(code, {
12726 filename: (this.excludeFromSourcemap ? null : fileName),
12727 indentExclusionRanges: []
12728 });
12729 timeStart('analyse ast', 3);
12730 this.astContext = {
12731 addDynamicImport: this.addDynamicImport.bind(this),
12732 addExport: this.addExport.bind(this),
12733 addImport: this.addImport.bind(this),
12734 addImportMeta: this.addImportMeta.bind(this),
12735 code,
12736 deoptimizationTracker: this.graph.deoptimizationTracker,
12737 error: this.error.bind(this),
12738 fileName,
12739 getExports: this.getExports.bind(this),
12740 getModuleExecIndex: () => this.execIndex,
12741 getModuleName: this.basename.bind(this),
12742 getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
12743 getReexports: this.getReexports.bind(this),
12744 importDescriptions: this.importDescriptions,
12745 includeAllExports: () => this.includeAllExports(true),
12746 includeDynamicImport: this.includeDynamicImport.bind(this),
12747 includeVariableInModule: this.includeVariableInModule.bind(this),
12748 magicString: this.magicString,
12749 module: this,
12750 moduleContext: this.context,
12751 options: this.options,
12752 requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
12753 traceExport: (name) => this.getVariableForExportName(name)[0],
12754 traceVariable: this.traceVariable.bind(this),
12755 usesTopLevelAwait: false,
12756 warn: this.warn.bind(this)
12757 };
12758 this.scope = new ModuleScope(this.graph.scope, this.astContext);
12759 this.namespace = new NamespaceVariable(this.astContext);
12760 this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
12761 this.info.ast = ast;
12762 timeEnd('analyse ast', 3);
12763 }
12764 toJSON() {
12765 return {
12766 ast: this.ast.esTreeNode,
12767 code: this.info.code,
12768 customTransformCache: this.customTransformCache,
12769 dependencies: Array.from(this.dependencies, getId),
12770 id: this.id,
12771 meta: this.info.meta,
12772 moduleSideEffects: this.info.moduleSideEffects,
12773 originalCode: this.originalCode,
12774 originalSourcemap: this.originalSourcemap,
12775 resolvedIds: this.resolvedIds,
12776 sourcemapChain: this.sourcemapChain,
12777 syntheticNamedExports: this.info.syntheticNamedExports,
12778 transformDependencies: this.transformDependencies,
12779 transformFiles: this.transformFiles
12780 };
12781 }
12782 traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
12783 const localVariable = this.scope.variables.get(name);
12784 if (localVariable) {
12785 return localVariable;
12786 }
12787 const importDeclaration = this.importDescriptions.get(name);
12788 if (importDeclaration) {
12789 const otherModule = importDeclaration.module;
12790 if (otherModule instanceof Module && importDeclaration.name === '*') {
12791 return otherModule.namespace;
12792 }
12793 const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
12794 if (!declaration) {
12795 return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
12796 }
12797 return declaration;
12798 }
12799 return null;
12800 }
12801 tryParse() {
12802 try {
12803 return this.graph.contextParse(this.info.code);
12804 }
12805 catch (err) {
12806 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
12807 if (this.id.endsWith('.json')) {
12808 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
12809 }
12810 else if (!this.id.endsWith('.js')) {
12811 message += ' (Note that you need plugins to import files that are not JavaScript)';
12812 }
12813 return this.error({
12814 code: 'PARSE_ERROR',
12815 message,
12816 parserError: err
12817 }, err.pos);
12818 }
12819 }
12820 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
12821 if (moduleSideEffects != null) {
12822 this.info.moduleSideEffects = moduleSideEffects;
12823 }
12824 if (syntheticNamedExports != null) {
12825 this.info.syntheticNamedExports = syntheticNamedExports;
12826 }
12827 if (meta != null) {
12828 Object.assign(this.info.meta, meta);
12829 }
12830 }
12831 warn(props, pos) {
12832 this.addLocationToLogProps(props, pos);
12833 this.options.onwarn(props);
12834 }
12835 addDynamicImport(node) {
12836 let argument = node.source;
12837 if (argument instanceof TemplateLiteral) {
12838 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
12839 argument = argument.quasis[0].value.cooked;
12840 }
12841 }
12842 else if (argument instanceof Literal && typeof argument.value === 'string') {
12843 argument = argument.value;
12844 }
12845 this.dynamicImports.push({ argument, id: null, node, resolution: null });
12846 }
12847 addExport(node) {
12848 if (node instanceof ExportDefaultDeclaration) {
12849 // export default foo;
12850 this.exports.set('default', {
12851 identifier: node.variable.getAssignedVariableName(),
12852 localName: 'default'
12853 });
12854 }
12855 else if (node instanceof ExportAllDeclaration) {
12856 const source = node.source.value;
12857 this.sources.add(source);
12858 if (node.exported) {
12859 // export * as name from './other'
12860 const name = node.exported.name;
12861 this.reexportDescriptions.set(name, {
12862 localName: '*',
12863 module: null,
12864 source,
12865 start: node.start
12866 });
12867 }
12868 else {
12869 // export * from './other'
12870 this.exportAllSources.add(source);
12871 }
12872 }
12873 else if (node.source instanceof Literal) {
12874 // export { name } from './other'
12875 const source = node.source.value;
12876 this.sources.add(source);
12877 for (const specifier of node.specifiers) {
12878 const name = specifier.exported.name;
12879 this.reexportDescriptions.set(name, {
12880 localName: specifier.local.name,
12881 module: null,
12882 source,
12883 start: specifier.start
12884 });
12885 }
12886 }
12887 else if (node.declaration) {
12888 const declaration = node.declaration;
12889 if (declaration instanceof VariableDeclaration) {
12890 // export var { foo, bar } = ...
12891 // export var foo = 1, bar = 2;
12892 for (const declarator of declaration.declarations) {
12893 for (const localName of extractAssignedNames(declarator.id)) {
12894 this.exports.set(localName, { identifier: null, localName });
12895 }
12896 }
12897 }
12898 else {
12899 // export function foo () {}
12900 const localName = declaration.id.name;
12901 this.exports.set(localName, { identifier: null, localName });
12902 }
12903 }
12904 else {
12905 // export { foo, bar, baz }
12906 for (const specifier of node.specifiers) {
12907 const localName = specifier.local.name;
12908 const exportedName = specifier.exported.name;
12909 this.exports.set(exportedName, { identifier: null, localName });
12910 }
12911 }
12912 }
12913 addImport(node) {
12914 const source = node.source.value;
12915 this.sources.add(source);
12916 for (const specifier of node.specifiers) {
12917 const isDefault = specifier.type === ImportDefaultSpecifier$1;
12918 const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
12919 const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
12920 this.importDescriptions.set(specifier.local.name, {
12921 module: null,
12922 name,
12923 source,
12924 start: specifier.start
12925 });
12926 }
12927 }
12928 addImportMeta(node) {
12929 this.importMetas.push(node);
12930 }
12931 addLocationToLogProps(props, pos) {
12932 props.id = this.id;
12933 props.pos = pos;
12934 let code = this.info.code;
12935 const location = locate(code, pos, { offsetLine: 1 });
12936 if (location) {
12937 let { column, line } = location;
12938 try {
12939 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
12940 code = this.originalCode;
12941 }
12942 catch (err) {
12943 this.options.onwarn({
12944 code: 'SOURCEMAP_ERROR',
12945 id: this.id,
12946 loc: {
12947 column,
12948 file: this.id,
12949 line
12950 },
12951 message: `Error when using sourcemap for reporting an error: ${err.message}`,
12952 pos
12953 });
12954 }
12955 augmentCodeLocation(props, { column, line }, code, this.id);
12956 }
12957 }
12958 addModulesToImportDescriptions(importDescription) {
12959 for (const specifier of importDescription.values()) {
12960 const { id } = this.resolvedIds[specifier.source];
12961 specifier.module = this.graph.modulesById.get(id);
12962 }
12963 }
12964 addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
12965 const handledDependencies = new Set();
12966 const addSideEffectDependencies = (possibleDependencies) => {
12967 for (const dependency of possibleDependencies) {
12968 if (handledDependencies.has(dependency)) {
12969 continue;
12970 }
12971 handledDependencies.add(dependency);
12972 if (necessaryDependencies.has(dependency)) {
12973 relevantDependencies.add(dependency);
12974 continue;
12975 }
12976 if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
12977 continue;
12978 }
12979 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
12980 relevantDependencies.add(dependency);
12981 continue;
12982 }
12983 addSideEffectDependencies(dependency.dependencies);
12984 }
12985 };
12986 addSideEffectDependencies(this.dependencies);
12987 addSideEffectDependencies(alwaysCheckedDependencies);
12988 }
12989 getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
12990 let foundSyntheticDeclaration = null;
12991 const foundInternalDeclarations = new Map();
12992 const foundExternalDeclarations = new Set();
12993 for (const module of this.exportAllModules) {
12994 // Synthetic namespaces should not hide "regular" exports of the same name
12995 if (module.info.syntheticNamedExports === name) {
12996 continue;
12997 }
12998 const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
12999 // We are creating a copy to handle the case where the same binding is
13000 // imported through different namespace reexports gracefully
13001 copyNameToModulesMap(searchedNamesAndModules));
13002 if (module instanceof ExternalModule || indirectExternal) {
13003 foundExternalDeclarations.add(variable);
13004 }
13005 else if (variable instanceof SyntheticNamedExportVariable) {
13006 if (!foundSyntheticDeclaration) {
13007 foundSyntheticDeclaration = variable;
13008 }
13009 }
13010 else if (variable) {
13011 foundInternalDeclarations.set(variable, module);
13012 }
13013 }
13014 if (foundInternalDeclarations.size > 0) {
13015 const foundDeclarationList = [...foundInternalDeclarations];
13016 const usedDeclaration = foundDeclarationList[0][0];
13017 if (foundDeclarationList.length === 1) {
13018 return [usedDeclaration];
13019 }
13020 this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
13021 // TODO we are pretending it was not found while it should behave like "undefined"
13022 return [null];
13023 }
13024 if (foundExternalDeclarations.size > 0) {
13025 const foundDeclarationList = [...foundExternalDeclarations];
13026 const usedDeclaration = foundDeclarationList[0];
13027 if (foundDeclarationList.length > 1) {
13028 this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
13029 }
13030 return [usedDeclaration, true];
13031 }
13032 if (foundSyntheticDeclaration) {
13033 return [foundSyntheticDeclaration];
13034 }
13035 return [null];
13036 }
13037 includeAndGetAdditionalMergedNamespaces() {
13038 const externalNamespaces = new Set();
13039 const syntheticNamespaces = new Set();
13040 for (const module of [this, ...this.exportAllModules]) {
13041 if (module instanceof ExternalModule) {
13042 const [externalVariable] = module.getVariableForExportName('*');
13043 externalVariable.include();
13044 this.includedImports.add(externalVariable);
13045 externalNamespaces.add(externalVariable);
13046 }
13047 else if (module.info.syntheticNamedExports) {
13048 const syntheticNamespace = module.getSyntheticNamespace();
13049 syntheticNamespace.include();
13050 this.includedImports.add(syntheticNamespace);
13051 syntheticNamespaces.add(syntheticNamespace);
13052 }
13053 }
13054 return [...syntheticNamespaces, ...externalNamespaces];
13055 }
13056 includeDynamicImport(node) {
13057 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
13058 if (resolution instanceof Module) {
13059 resolution.includedDynamicImporters.push(this);
13060 resolution.includeAllExports(true);
13061 }
13062 }
13063 includeVariable(variable) {
13064 if (!variable.included) {
13065 variable.include();
13066 this.graph.needsTreeshakingPass = true;
13067 const variableModule = variable.module;
13068 if (variableModule instanceof Module) {
13069 if (!variableModule.isExecuted) {
13070 markModuleAndImpureDependenciesAsExecuted(variableModule);
13071 }
13072 if (variableModule !== this) {
13073 const sideEffectModules = getAndExtendSideEffectModules(variable, this);
13074 for (const module of sideEffectModules) {
13075 if (!module.isExecuted) {
13076 markModuleAndImpureDependenciesAsExecuted(module);
13077 }
13078 }
13079 }
13080 }
13081 }
13082 }
13083 includeVariableInModule(variable) {
13084 this.includeVariable(variable);
13085 const variableModule = variable.module;
13086 if (variableModule && variableModule !== this) {
13087 this.includedImports.add(variable);
13088 }
13089 }
13090 shimMissingExport(name) {
13091 this.options.onwarn({
13092 code: 'SHIMMED_EXPORT',
13093 exporter: relativeId(this.id),
13094 exportName: name,
13095 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
13096 });
13097 this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
13098 }
13099}
13100// if there is a cyclic import in the reexport chain, we should not
13101// import from the original module but from the cyclic module to not
13102// mess up execution order.
13103function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
13104 if (variable.module instanceof Module && variable.module !== reexporter) {
13105 const exporterCycles = variable.module.cycles;
13106 if (exporterCycles.size > 0) {
13107 const importerCycles = reexporter.cycles;
13108 for (const cycleSymbol of importerCycles) {
13109 if (exporterCycles.has(cycleSymbol)) {
13110 importer.alternativeReexportModules.set(variable, reexporter);
13111 break;
13112 }
13113 }
13114 }
13115 }
13116}
13117const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
13118 new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
13119
13120function removeJsExtension(name) {
13121 return name.endsWith('.js') ? name.slice(0, -3) : name;
13122}
13123
13124function getCompleteAmdId(options, chunkId) {
13125 if (options.autoId) {
13126 return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
13127 }
13128 return options.id || '';
13129}
13130
13131function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
13132 const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
13133 if (!namedExportsMode) {
13134 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
13135 }
13136 let exportBlock = '';
13137 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13138 if (reexports && namedExportsMode) {
13139 for (const specifier of reexports) {
13140 if (specifier.reexported !== '*') {
13141 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13142 if (exportBlock)
13143 exportBlock += n;
13144 if (specifier.imported !== '*' && specifier.needsLiveBinding) {
13145 const [left, right] = getDirectReturnFunction([], {
13146 functionReturn: true,
13147 lineBreakIndent: null,
13148 name: null
13149 });
13150 exportBlock +=
13151 `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
13152 `${t}enumerable:${_}true,${n}` +
13153 `${t}get:${_}${left}${importName}${right}${n}});`;
13154 }
13155 else {
13156 exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
13157 }
13158 }
13159 }
13160 }
13161 }
13162 for (const { exported, local } of exports) {
13163 const lhs = `exports${getPropertyAccess(exported)}`;
13164 const rhs = local;
13165 if (lhs !== rhs) {
13166 if (exportBlock)
13167 exportBlock += n;
13168 exportBlock += `${lhs}${_}=${_}${rhs};`;
13169 }
13170 }
13171 for (const { name, reexports } of dependencies) {
13172 if (reexports && namedExportsMode) {
13173 for (const specifier of reexports) {
13174 if (specifier.reexported === '*') {
13175 if (exportBlock)
13176 exportBlock += n;
13177 const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
13178 exportBlock +=
13179 cnst === 'var' && specifier.needsLiveBinding
13180 ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
13181 isAsync: false,
13182 name: null
13183 })}${copyPropertyIfNecessary});`
13184 : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
13185 }
13186 }
13187 }
13188 }
13189 if (exportBlock) {
13190 return `${n}${n}${exportBlock}`;
13191 }
13192 return '';
13193}
13194function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
13195 if (exports.length > 0) {
13196 return exports[0].local;
13197 }
13198 else {
13199 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13200 if (reexports) {
13201 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13202 }
13203 }
13204 }
13205}
13206function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
13207 if (imported === 'default') {
13208 if (!isChunk) {
13209 const moduleInterop = String(interop(moduleId));
13210 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
13211 ? defaultVariableName
13212 : moduleVariableName;
13213 return isDefaultAProperty(moduleInterop, externalLiveBindings)
13214 ? `${variableName}${getPropertyAccess('default')}`
13215 : variableName;
13216 }
13217 return depNamedExportsMode
13218 ? `${moduleVariableName}${getPropertyAccess('default')}`
13219 : moduleVariableName;
13220 }
13221 if (imported === '*') {
13222 return (isChunk
13223 ? !depNamedExportsMode
13224 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
13225 ? namespaceVariableName
13226 : moduleVariableName;
13227 }
13228 return `${moduleVariableName}${getPropertyAccess(imported)}`;
13229}
13230function getEsModuleValue(getObject) {
13231 return getObject([['value', 'true']], {
13232 lineBreakIndent: null
13233 });
13234}
13235function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
13236 if (hasNamedExports) {
13237 if (addEsModule) {
13238 if (addNamespaceToStringTag) {
13239 return `Object.defineProperties(exports,${_}${getObject([
13240 ['__esModule', getEsModuleValue(getObject)],
13241 [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
13242 ], {
13243 lineBreakIndent: null
13244 })});`;
13245 }
13246 return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
13247 }
13248 if (addNamespaceToStringTag) {
13249 return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
13250 }
13251 }
13252 return '';
13253}
13254const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
13255 if (needsLiveBinding) {
13256 const [left, right] = getDirectReturnFunction([], {
13257 functionReturn: true,
13258 lineBreakIndent: null,
13259 name: null
13260 });
13261 return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
13262 `${t}${t}enumerable:${_}true,${n}` +
13263 `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
13264 }
13265 return `exports[k]${_}=${_}${name}[k]`;
13266};
13267
13268function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
13269 const { _, cnst, n } = snippets;
13270 const neededInteropHelpers = new Set();
13271 const interopStatements = [];
13272 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
13273 neededInteropHelpers.add(helper);
13274 interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
13275 };
13276 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13277 if (isChunk) {
13278 for (const { imported, reexported } of [
13279 ...(imports || []),
13280 ...(reexports || [])
13281 ]) {
13282 if (imported === '*' && reexported !== '*') {
13283 if (!namedExportsMode) {
13284 addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
13285 }
13286 break;
13287 }
13288 }
13289 }
13290 else {
13291 const moduleInterop = String(interop(id));
13292 let hasDefault = false;
13293 let hasNamespace = false;
13294 for (const { imported, reexported } of [
13295 ...(imports || []),
13296 ...(reexports || [])
13297 ]) {
13298 let helper;
13299 let variableName;
13300 if (imported === 'default') {
13301 if (!hasDefault) {
13302 hasDefault = true;
13303 if (defaultVariableName !== namespaceVariableName) {
13304 variableName = defaultVariableName;
13305 helper = defaultInteropHelpersByInteropType[moduleInterop];
13306 }
13307 }
13308 }
13309 else if (imported === '*' && reexported !== '*') {
13310 if (!hasNamespace) {
13311 hasNamespace = true;
13312 helper = namespaceInteropHelpersByInteropType[moduleInterop];
13313 variableName = namespaceVariableName;
13314 }
13315 }
13316 if (helper) {
13317 addInteropStatement(variableName, helper, name);
13318 }
13319 }
13320 }
13321 }
13322 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
13323}
13324
13325function addJsExtension(name) {
13326 return name.endsWith('.js') ? name : name + '.js';
13327}
13328
13329// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
13330// The assumption is that this makes sense for all relative ids:
13331// https://requirejs.org/docs/api.html#jsfiles
13332function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
13333 if (id[0] !== '.') {
13334 return id;
13335 }
13336 return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
13337}
13338
13339const builtins = {
13340 assert: true,
13341 buffer: true,
13342 console: true,
13343 constants: true,
13344 domain: true,
13345 events: true,
13346 http: true,
13347 https: true,
13348 os: true,
13349 path: true,
13350 process: true,
13351 punycode: true,
13352 querystring: true,
13353 stream: true,
13354 string_decoder: true,
13355 timers: true,
13356 tty: true,
13357 url: true,
13358 util: true,
13359 vm: true,
13360 zlib: true
13361};
13362function warnOnBuiltins(warn, dependencies) {
13363 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
13364 if (!externalBuiltins.length)
13365 return;
13366 warn({
13367 code: 'MISSING_NODE_BUILTINS',
13368 message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`,
13369 modules: externalBuiltins
13370 });
13371}
13372
13373function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13374 warnOnBuiltins(warn, dependencies);
13375 const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
13376 const args = dependencies.map(m => m.name);
13377 const { n, getNonArrowFunctionIntro, _ } = snippets;
13378 if (namedExportsMode && hasExports) {
13379 args.unshift(`exports`);
13380 deps.unshift(`'exports'`);
13381 }
13382 if (accessedGlobals.has('require')) {
13383 args.unshift('require');
13384 deps.unshift(`'require'`);
13385 }
13386 if (accessedGlobals.has('module')) {
13387 args.unshift('module');
13388 deps.unshift(`'module'`);
13389 }
13390 const completeAmdId = getCompleteAmdId(amd, id);
13391 const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13392 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
13393 const useStrict = strict ? `${_}'use strict';` : '';
13394 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
13395 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13396 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13397 if (namespaceMarkers) {
13398 namespaceMarkers = n + n + namespaceMarkers;
13399 }
13400 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13401 return (magicString
13402 .indent(t)
13403 // factory function should be wrapped by parentheses to avoid lazy parsing,
13404 // cf. https://v8.dev/blog/preparser#pife
13405 .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
13406 isAsync: false,
13407 name: null
13408 })}{${useStrict}${n}${n}`)
13409 .append(`${n}${n}}));`));
13410}
13411
13412function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13413 const { _, n } = snippets;
13414 const useStrict = strict ? `'use strict';${n}${n}` : '';
13415 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13416 if (namespaceMarkers) {
13417 namespaceMarkers += n + n;
13418 }
13419 const importBlock = getImportBlock$1(dependencies, snippets, compact);
13420 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13421 magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
13422 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
13423 return magicString.append(`${exportBlock}${outro}`);
13424}
13425function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
13426 let importBlock = '';
13427 let definingVariable = false;
13428 for (const { id, name, reexports, imports } of dependencies) {
13429 if (!reexports && !imports) {
13430 if (importBlock) {
13431 importBlock += compact && !definingVariable ? ',' : `;${n}`;
13432 }
13433 definingVariable = false;
13434 importBlock += `require('${id}')`;
13435 }
13436 else {
13437 importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
13438 definingVariable = true;
13439 importBlock += `${name}${_}=${_}require('${id}')`;
13440 }
13441 }
13442 if (importBlock) {
13443 return `${importBlock};${n}${n}`;
13444 }
13445 return '';
13446}
13447
13448function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
13449 const { _, n } = snippets;
13450 const importBlock = getImportBlock(dependencies, _);
13451 if (importBlock.length > 0)
13452 intro += importBlock.join(n) + n + n;
13453 intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
13454 if (intro)
13455 magicString.prepend(intro);
13456 const exportBlock = getExportBlock(exports, snippets);
13457 if (exportBlock.length)
13458 magicString.append(n + n + exportBlock.join(n).trim());
13459 if (outro)
13460 magicString.append(outro);
13461 return magicString.trim();
13462}
13463function getImportBlock(dependencies, _) {
13464 const importBlock = [];
13465 for (const { id, reexports, imports, name } of dependencies) {
13466 if (!reexports && !imports) {
13467 importBlock.push(`import${_}'${id}';`);
13468 continue;
13469 }
13470 if (imports) {
13471 let defaultImport = null;
13472 let starImport = null;
13473 const importedNames = [];
13474 for (const specifier of imports) {
13475 if (specifier.imported === 'default') {
13476 defaultImport = specifier;
13477 }
13478 else if (specifier.imported === '*') {
13479 starImport = specifier;
13480 }
13481 else {
13482 importedNames.push(specifier);
13483 }
13484 }
13485 if (starImport) {
13486 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
13487 }
13488 if (defaultImport && importedNames.length === 0) {
13489 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
13490 }
13491 else if (importedNames.length > 0) {
13492 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
13493 .map(specifier => {
13494 if (specifier.imported === specifier.local) {
13495 return specifier.imported;
13496 }
13497 else {
13498 return `${specifier.imported} as ${specifier.local}`;
13499 }
13500 })
13501 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13502 }
13503 }
13504 if (reexports) {
13505 let starExport = null;
13506 const namespaceReexports = [];
13507 const namedReexports = [];
13508 for (const specifier of reexports) {
13509 if (specifier.reexported === '*') {
13510 starExport = specifier;
13511 }
13512 else if (specifier.imported === '*') {
13513 namespaceReexports.push(specifier);
13514 }
13515 else {
13516 namedReexports.push(specifier);
13517 }
13518 }
13519 if (starExport) {
13520 importBlock.push(`export${_}*${_}from${_}'${id}';`);
13521 }
13522 if (namespaceReexports.length > 0) {
13523 if (!imports ||
13524 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
13525 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
13526 }
13527 for (const specifier of namespaceReexports) {
13528 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
13529 }
13530 }
13531 if (namedReexports.length > 0) {
13532 importBlock.push(`export${_}{${_}${namedReexports
13533 .map(specifier => {
13534 if (specifier.imported === specifier.reexported) {
13535 return specifier.imported;
13536 }
13537 else {
13538 return `${specifier.imported} as ${specifier.reexported}`;
13539 }
13540 })
13541 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13542 }
13543 }
13544 }
13545 return importBlock;
13546}
13547function getExportBlock(exports, { _, cnst }) {
13548 const exportBlock = [];
13549 const exportDeclaration = [];
13550 for (const specifier of exports) {
13551 if (specifier.expression) {
13552 exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
13553 }
13554 exportDeclaration.push(specifier.exported === specifier.local
13555 ? specifier.local
13556 : `${specifier.local} as ${specifier.exported}`);
13557 }
13558 if (exportDeclaration.length) {
13559 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
13560 }
13561 return exportBlock;
13562}
13563
13564const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
13565
13566function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
13567 const parts = name.split('.');
13568 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13569 parts.pop();
13570 let propertyPath = root;
13571 return (parts
13572 .map(part => {
13573 propertyPath += getPropertyAccess(part);
13574 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
13575 })
13576 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
13577}
13578function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
13579 const parts = deepName.split('.');
13580 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13581 const last = parts.pop();
13582 let propertyPath = root;
13583 let deepAssignment = parts
13584 .map(part => {
13585 propertyPath += getPropertyAccess(part);
13586 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
13587 })
13588 .concat(`${propertyPath}${getPropertyAccess(last)}`)
13589 .join(`,${_}`) + `${_}=${_}${assignment}`;
13590 if (parts.length > 0) {
13591 deepAssignment = `(${deepAssignment})`;
13592 }
13593 return deepAssignment;
13594}
13595
13596function trimEmptyImports(dependencies) {
13597 let i = dependencies.length;
13598 while (i--) {
13599 const { imports, reexports } = dependencies[i];
13600 if (imports || reexports) {
13601 return dependencies.slice(0, i + 1);
13602 }
13603 }
13604 return [];
13605}
13606
13607function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13608 const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
13609 const isNamespaced = name && name.includes('.');
13610 const useVariableAssignment = !extend && !isNamespaced;
13611 if (name && useVariableAssignment && !isLegal(name)) {
13612 return error({
13613 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
13614 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
13615 });
13616 }
13617 warnOnBuiltins(warn, dependencies);
13618 const external = trimEmptyImports(dependencies);
13619 const deps = external.map(dep => dep.globalName || 'null');
13620 const args = external.map(m => m.name);
13621 if (hasExports && !name) {
13622 warn({
13623 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13624 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
13625 });
13626 }
13627 if (namedExportsMode && hasExports) {
13628 if (extend) {
13629 deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
13630 args.unshift('exports');
13631 }
13632 else {
13633 deps.unshift('{}');
13634 args.unshift('exports');
13635 }
13636 }
13637 const useStrict = strict ? `${t}'use strict';${n}` : '';
13638 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13639 magicString.prepend(`${intro}${interopBlock}`);
13640 let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
13641 isAsync: false,
13642 name: null
13643 })}{${n}${useStrict}${n}`;
13644 if (hasExports) {
13645 if (name && !(extend && namedExportsMode)) {
13646 wrapperIntro =
13647 (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
13648 `${_}=${_}${wrapperIntro}`;
13649 }
13650 if (isNamespaced) {
13651 wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
13652 }
13653 }
13654 let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
13655 if (hasExports && !extend && namedExportsMode) {
13656 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
13657 }
13658 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13659 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
13660 if (namespaceMarkers) {
13661 namespaceMarkers = n + n + namespaceMarkers;
13662 }
13663 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13664 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
13665}
13666
13667function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
13668 const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
13669 const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
13670 const registeredName = name ? `'${name}',${_}` : '';
13671 const wrapperParams = accessedGlobals.has('module')
13672 ? ['exports', 'module']
13673 : hasExports
13674 ? ['exports']
13675 : [];
13676 // factory function should be wrapped by parentheses to avoid lazy parsing,
13677 // cf. https://v8.dev/blog/preparser#pife
13678 let wrapperStart = `System.register(${registeredName}[` +
13679 dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
13680 `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13681 getStarExcludesBlock(starExcludes, t, snippets) +
13682 getImportBindingsBlock(importBindings, t, snippets) +
13683 `${n}${t}return${_}{${setters.length
13684 ? `${n}${t}${t}setters:${_}[${setters
13685 .map(setter => setter
13686 ? `${getFunctionIntro(['module'], {
13687 isAsync: false,
13688 name: null
13689 })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
13690 : systemNullSetters
13691 ? `null`
13692 : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
13693 .join(`,${_}`)}],`
13694 : ''}${n}`;
13695 wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
13696 isAsync: usesTopLevelAwait,
13697 name: null
13698 })}{${n}${n}`;
13699 const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
13700 magicString.prepend(intro +
13701 getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
13702 getHoistedExportsBlock(exports, t, snippets));
13703 magicString.append(`${outro}${n}${n}` +
13704 getSyntheticExportsBlock(exports, t, snippets) +
13705 getMissingExportsBlock(exports, t, snippets));
13706 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
13707}
13708function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
13709 const importBindings = [];
13710 const setters = [];
13711 let starExcludes = null;
13712 for (const { imports, reexports } of dependencies) {
13713 const setter = [];
13714 if (imports) {
13715 for (const specifier of imports) {
13716 importBindings.push(specifier.local);
13717 if (specifier.imported === '*') {
13718 setter.push(`${specifier.local}${_}=${_}module;`);
13719 }
13720 else {
13721 setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
13722 }
13723 }
13724 }
13725 if (reexports) {
13726 const reexportedNames = [];
13727 let hasStarReexport = false;
13728 for (const { imported, reexported } of reexports) {
13729 if (reexported === '*') {
13730 hasStarReexport = true;
13731 }
13732 else {
13733 reexportedNames.push([
13734 reexported,
13735 imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
13736 ]);
13737 }
13738 }
13739 if (reexportedNames.length > 1 || hasStarReexport) {
13740 const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
13741 if (hasStarReexport) {
13742 if (!starExcludes) {
13743 starExcludes = getStarExcludes({ dependencies, exports });
13744 }
13745 setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
13746 }
13747 else {
13748 setter.push(`exports(${exportMapping});`);
13749 }
13750 }
13751 else {
13752 const [key, value] = reexportedNames[0];
13753 setter.push(`exports('${key}',${_}${value});`);
13754 }
13755 }
13756 setters.push(setter.join(`${n}${t}${t}${t}`));
13757 }
13758 return { importBindings, setters, starExcludes };
13759}
13760const getStarExcludes = ({ dependencies, exports }) => {
13761 const starExcludes = new Set(exports.map(expt => expt.exported));
13762 starExcludes.add('default');
13763 for (const { reexports } of dependencies) {
13764 if (reexports) {
13765 for (const reexport of reexports) {
13766 if (reexport.reexported !== '*')
13767 starExcludes.add(reexport.reexported);
13768 }
13769 }
13770 }
13771 return starExcludes;
13772};
13773const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
13774 ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
13775 : '';
13776const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
13777const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13778function getExportsBlock(exports, t, { _, n }) {
13779 if (exports.length === 0) {
13780 return '';
13781 }
13782 if (exports.length === 1) {
13783 return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
13784 }
13785 return (`exports({${n}` +
13786 exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
13787 `${n}});${n}${n}`);
13788}
13789const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13790 .filter(expt => expt.expression)
13791 .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13792const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13793 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
13794 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
13795
13796function globalProp(name, globalVar, getPropertyAccess) {
13797 if (!name)
13798 return 'null';
13799 return `${globalVar}${keypath(name, getPropertyAccess)}`;
13800}
13801function safeAccess(name, globalVar, { _, getPropertyAccess }) {
13802 let propertyPath = globalVar;
13803 return name
13804 .split('.')
13805 .map(part => (propertyPath += getPropertyAccess(part)))
13806 .join(`${_}&&${_}`);
13807}
13808function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
13809 const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
13810 const factoryVar = compact ? 'f' : 'factory';
13811 const globalVar = compact ? 'g' : 'global';
13812 if (hasExports && !name) {
13813 return error({
13814 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13815 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
13816 });
13817 }
13818 warnOnBuiltins(warn, dependencies);
13819 const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
13820 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
13821 const trimmedImports = trimEmptyImports(dependencies);
13822 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
13823 const factoryParams = trimmedImports.map(m => m.name);
13824 if (namedExportsMode && (hasExports || noConflict)) {
13825 amdDeps.unshift(`'exports'`);
13826 cjsDeps.unshift(`exports`);
13827 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
13828 factoryParams.unshift('exports');
13829 }
13830 const completeAmdId = getCompleteAmdId(amd, id);
13831 const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13832 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
13833 const define = amd.define;
13834 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
13835 const useStrict = strict ? `${_}'use strict';${n}` : ``;
13836 let iifeExport;
13837 if (noConflict) {
13838 const noConflictExportsVar = compact ? 'e' : 'exports';
13839 let factory;
13840 if (!namedExportsMode && hasExports) {
13841 factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
13842 }
13843 else {
13844 const module = globalDeps.shift();
13845 factory =
13846 `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
13847 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
13848 }
13849 iifeExport =
13850 `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
13851 `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
13852 `${t}${t}${factory}${n}` +
13853 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
13854 isAsync: false,
13855 name: null
13856 })}{${_}` +
13857 `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
13858 `${t}})()`;
13859 }
13860 else {
13861 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
13862 if (!namedExportsMode && hasExports) {
13863 iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
13864 }
13865 }
13866 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
13867 const wrapperParams = [factoryVar];
13868 if (iifeNeedsGlobal) {
13869 wrapperParams.unshift(globalVar);
13870 }
13871 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
13872 const iifeStart = iifeNeedsGlobal
13873 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
13874 : '';
13875 const iifeEnd = iifeNeedsGlobal ? ')' : '';
13876 const cjsIntro = iifeNeedsGlobal
13877 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
13878 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
13879 : '';
13880 const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
13881 cjsIntro +
13882 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
13883 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
13884 // factory function should be wrapped by parentheses to avoid lazy parsing,
13885 // cf. https://v8.dev/blog/preparser#pife
13886 `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
13887 isAsync: false,
13888 name: null
13889 })}{${useStrict}${n}`;
13890 const wrapperOutro = n + n + '}));';
13891 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
13892 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13893 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
13894 if (namespaceMarkers) {
13895 namespaceMarkers = n + n + namespaceMarkers;
13896 }
13897 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13898 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
13899}
13900
13901const finalisers = { amd, cjs, es, iife, system, umd };
13902
13903class Source {
13904 constructor(filename, content) {
13905 this.isOriginal = true;
13906 this.filename = filename;
13907 this.content = content;
13908 }
13909 traceSegment(line, column, name) {
13910 return { column, line, name, source: this };
13911 }
13912}
13913class Link {
13914 constructor(map, sources) {
13915 this.sources = sources;
13916 this.names = map.names;
13917 this.mappings = map.mappings;
13918 }
13919 traceMappings() {
13920 const sources = [];
13921 const sourceIndexMap = new Map();
13922 const sourcesContent = [];
13923 const names = [];
13924 const nameIndexMap = new Map();
13925 const mappings = [];
13926 for (const line of this.mappings) {
13927 const tracedLine = [];
13928 for (const segment of line) {
13929 if (segment.length === 1)
13930 continue;
13931 const source = this.sources[segment[1]];
13932 if (!source)
13933 continue;
13934 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
13935 if (traced) {
13936 const { column, line, name, source: { content, filename } } = traced;
13937 let sourceIndex = sourceIndexMap.get(filename);
13938 if (sourceIndex === undefined) {
13939 sourceIndex = sources.length;
13940 sources.push(filename);
13941 sourceIndexMap.set(filename, sourceIndex);
13942 sourcesContent[sourceIndex] = content;
13943 }
13944 else if (sourcesContent[sourceIndex] == null) {
13945 sourcesContent[sourceIndex] = content;
13946 }
13947 else if (content != null && sourcesContent[sourceIndex] !== content) {
13948 return error({
13949 message: `Multiple conflicting contents for sourcemap source ${filename}`
13950 });
13951 }
13952 const tracedSegment = [segment[0], sourceIndex, line, column];
13953 if (name) {
13954 let nameIndex = nameIndexMap.get(name);
13955 if (nameIndex === undefined) {
13956 nameIndex = names.length;
13957 names.push(name);
13958 nameIndexMap.set(name, nameIndex);
13959 }
13960 tracedSegment[4] = nameIndex;
13961 }
13962 tracedLine.push(tracedSegment);
13963 }
13964 }
13965 mappings.push(tracedLine);
13966 }
13967 return { mappings, names, sources, sourcesContent };
13968 }
13969 traceSegment(line, column, name) {
13970 const segments = this.mappings[line];
13971 if (!segments)
13972 return null;
13973 // binary search through segments for the given column
13974 let searchStart = 0;
13975 let searchEnd = segments.length - 1;
13976 while (searchStart <= searchEnd) {
13977 const m = (searchStart + searchEnd) >> 1;
13978 const segment = segments[m];
13979 // If a sourcemap does not have sufficient resolution to contain a
13980 // necessary mapping, e.g. because it only contains line information, we
13981 // use the best approximation we could find
13982 if (segment[0] === column || searchStart === searchEnd) {
13983 if (segment.length == 1)
13984 return null;
13985 const source = this.sources[segment[1]];
13986 if (!source)
13987 return null;
13988 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
13989 }
13990 if (segment[0] > column) {
13991 searchEnd = m - 1;
13992 }
13993 else {
13994 searchStart = m + 1;
13995 }
13996 }
13997 return null;
13998 }
13999}
14000function getLinkMap(warn) {
14001 return function linkMap(source, map) {
14002 if (map.mappings) {
14003 return new Link(map, [source]);
14004 }
14005 warn({
14006 code: 'SOURCEMAP_BROKEN',
14007 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
14008 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
14009 'documentation for help',
14010 plugin: map.plugin,
14011 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
14012 });
14013 return new Link({
14014 mappings: [],
14015 names: []
14016 }, [source]);
14017 };
14018}
14019function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
14020 let source;
14021 if (!originalSourcemap) {
14022 source = new Source(id, originalCode);
14023 }
14024 else {
14025 const sources = originalSourcemap.sources;
14026 const sourcesContent = originalSourcemap.sourcesContent || [];
14027 const directory = dirname(id) || '.';
14028 const sourceRoot = originalSourcemap.sourceRoot || '.';
14029 const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
14030 source = new Link(originalSourcemap, baseSources);
14031 }
14032 return sourcemapChain.reduce(linkMap, source);
14033}
14034function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
14035 const linkMap = getLinkMap(warn);
14036 const moduleSources = modules
14037 .filter(module => !module.excludeFromSourcemap)
14038 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
14039 const link = new Link(map, moduleSources);
14040 const source = bundleSourcemapChain.reduce(linkMap, link);
14041 let { sources, sourcesContent, names, mappings } = source.traceMappings();
14042 if (file) {
14043 const directory = dirname(file);
14044 sources = sources.map((source) => relative$1(directory, source));
14045 file = basename(file);
14046 }
14047 sourcesContent = (excludeContent ? null : sourcesContent);
14048 return new SourceMap({ file, mappings, names, sources, sourcesContent });
14049}
14050function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
14051 if (!sourcemapChain.length) {
14052 return originalSourcemap;
14053 }
14054 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
14055 const map = source.traceMappings();
14056 return { version: 3, ...map };
14057}
14058
14059const createHash = () => createHash$1('sha256');
14060
14061const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14062 amd: deconflictImportsOther,
14063 cjs: deconflictImportsOther,
14064 es: deconflictImportsEsmOrSystem,
14065 iife: deconflictImportsOther,
14066 system: deconflictImportsEsmOrSystem,
14067 umd: deconflictImportsOther
14068};
14069function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14070 const reversedModules = modules.slice().reverse();
14071 for (const module of reversedModules) {
14072 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14073 }
14074 deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
14075 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
14076 for (const module of reversedModules) {
14077 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
14078 }
14079}
14080function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
14081 // This is needed for namespace reexports
14082 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
14083 if (preserveModules || dependency instanceof ExternalModule) {
14084 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
14085 }
14086 }
14087 for (const variable of imports) {
14088 const module = variable.module;
14089 const name = variable.name;
14090 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
14091 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
14092 }
14093 else if (module instanceof ExternalModule && name === 'default') {
14094 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
14095 ? module.suggestedVariableName + '__default'
14096 : module.suggestedVariableName, usedNames));
14097 }
14098 else {
14099 variable.setRenderNames(null, getSafeName(name, usedNames));
14100 }
14101 }
14102 for (const variable of syntheticExports) {
14103 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14104 }
14105}
14106function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
14107 for (const chunkOrExternalModule of dependencies) {
14108 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
14109 }
14110 for (const externalModuleOrChunk of deconflictedNamespace) {
14111 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
14112 }
14113 for (const externalModule of deconflictedDefault) {
14114 if (deconflictedNamespace.has(externalModule) &&
14115 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
14116 externalModule.defaultVariableName = externalModule.namespaceVariableName;
14117 }
14118 else {
14119 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
14120 }
14121 }
14122 for (const variable of imports) {
14123 const module = variable.module;
14124 if (module instanceof ExternalModule) {
14125 const name = variable.name;
14126 if (name === 'default') {
14127 const moduleInterop = String(interop(module.id));
14128 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
14129 ? module.defaultVariableName
14130 : module.variableName;
14131 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
14132 variable.setRenderNames(variableName, 'default');
14133 }
14134 else {
14135 variable.setRenderNames(null, variableName);
14136 }
14137 }
14138 else if (name === '*') {
14139 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
14140 ? module.namespaceVariableName
14141 : module.variableName);
14142 }
14143 else {
14144 // if the second parameter is `null`, it uses its "name" for the property name
14145 variable.setRenderNames(module.variableName, null);
14146 }
14147 }
14148 else {
14149 const chunk = chunkByModule.get(module);
14150 if (preserveModules && variable.isNamespace) {
14151 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
14152 }
14153 else if (chunk.exportMode === 'default') {
14154 variable.setRenderNames(null, chunk.variableName);
14155 }
14156 else {
14157 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
14158 }
14159 }
14160 }
14161}
14162function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
14163 for (const module of modules) {
14164 for (const variable of module.scope.variables.values()) {
14165 if (variable.included &&
14166 // this will only happen for exports in some formats
14167 !(variable.renderBaseName ||
14168 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
14169 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14170 }
14171 }
14172 if (includedNamespaces.has(module)) {
14173 const namespace = module.namespace;
14174 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
14175 }
14176 }
14177}
14178
14179const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
14180const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
14181const backSlashRegEx = /\\/g;
14182function escapeId(id) {
14183 if (!id.match(needsEscapeRegEx))
14184 return id;
14185 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
14186}
14187
14188function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
14189 let nameIndex = 0;
14190 for (const variable of exports) {
14191 let [exportName] = variable.name;
14192 if (exportsByName.has(exportName)) {
14193 do {
14194 exportName = toBase64(++nameIndex);
14195 // skip past leading number identifiers
14196 if (exportName.charCodeAt(0) === 49 /* '1' */) {
14197 nameIndex += 9 * 64 ** (exportName.length - 1);
14198 exportName = toBase64(nameIndex);
14199 }
14200 } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
14201 }
14202 exportsByName.set(exportName, variable);
14203 exportNamesByVariable.set(variable, [exportName]);
14204 }
14205}
14206function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
14207 for (const variable of exports) {
14208 let nameIndex = 0;
14209 let exportName = variable.name;
14210 while (exportsByName.has(exportName)) {
14211 exportName = variable.name + '$' + ++nameIndex;
14212 }
14213 exportsByName.set(exportName, variable);
14214 exportNamesByVariable.set(variable, [exportName]);
14215 }
14216}
14217
14218function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
14219 const exportKeys = chunk.getExportNames();
14220 if (exportMode === 'default') {
14221 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
14222 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
14223 }
14224 }
14225 else if (exportMode === 'none' && exportKeys.length) {
14226 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
14227 }
14228 if (exportMode === 'auto') {
14229 if (exportKeys.length === 0) {
14230 exportMode = 'none';
14231 }
14232 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
14233 if (format === 'cjs' && unsetOptions.has('exports')) {
14234 warn(errPreferNamedExports(facadeModuleId));
14235 }
14236 exportMode = 'default';
14237 }
14238 else {
14239 if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
14240 warn(errMixedExport(facadeModuleId, name));
14241 }
14242 exportMode = 'named';
14243 }
14244 }
14245 return exportMode;
14246}
14247
14248function guessIndentString(code) {
14249 const lines = code.split('\n');
14250 const tabbed = lines.filter(line => /^\t+/.test(line));
14251 const spaced = lines.filter(line => /^ {2,}/.test(line));
14252 if (tabbed.length === 0 && spaced.length === 0) {
14253 return null;
14254 }
14255 // More lines tabbed than spaced? Assume tabs, and
14256 // default to tabs in the case of a tie (or nothing
14257 // to go on)
14258 if (tabbed.length >= spaced.length) {
14259 return '\t';
14260 }
14261 // Otherwise, we need to guess the multiple
14262 const min = spaced.reduce((previous, current) => {
14263 const numSpaces = /^ +/.exec(current)[0].length;
14264 return Math.min(numSpaces, previous);
14265 }, Infinity);
14266 return new Array(min + 1).join(' ');
14267}
14268function getIndentString(modules, options) {
14269 if (options.indent !== true)
14270 return options.indent;
14271 for (const module of modules) {
14272 const indent = guessIndentString(module.originalCode);
14273 if (indent !== null)
14274 return indent;
14275 }
14276 return '\t';
14277}
14278
14279function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14280 const staticDependencyBlocks = [];
14281 const handledDependencies = new Set();
14282 for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
14283 const module = orderedModules[modulePos];
14284 if (!handledDependencies.has(module)) {
14285 const staticDependencies = [];
14286 addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
14287 staticDependencyBlocks.unshift(staticDependencies);
14288 }
14289 }
14290 const dependencies = new Set();
14291 for (const block of staticDependencyBlocks) {
14292 for (const dependency of block) {
14293 dependencies.add(dependency);
14294 }
14295 }
14296 return dependencies;
14297}
14298function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
14299 const dependencies = module.getDependenciesToBeIncluded();
14300 for (const dependency of dependencies) {
14301 if (dependency instanceof ExternalModule) {
14302 staticDependencies.push(dependency);
14303 continue;
14304 }
14305 const dependencyChunk = chunkByModule.get(dependency);
14306 if (dependencyChunk !== chunk) {
14307 staticDependencies.push(dependencyChunk);
14308 continue;
14309 }
14310 if (!handledModules.has(dependency)) {
14311 handledModules.add(dependency);
14312 addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
14313 }
14314 }
14315}
14316
14317function decodedSourcemap(map) {
14318 if (!map)
14319 return null;
14320 if (typeof map === 'string') {
14321 map = JSON.parse(map);
14322 }
14323 if (map.mappings === '') {
14324 return {
14325 mappings: [],
14326 names: [],
14327 sources: [],
14328 version: 3
14329 };
14330 }
14331 const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
14332 return { ...map, mappings };
14333}
14334
14335function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
14336 const renderChunkReducer = (code, result, plugin) => {
14337 if (result == null)
14338 return code;
14339 if (typeof result === 'string')
14340 result = {
14341 code: result,
14342 map: undefined
14343 };
14344 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14345 if (result.map !== null) {
14346 const map = decodedSourcemap(result.map);
14347 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14348 }
14349 return result.code;
14350 };
14351 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
14352}
14353
14354const lowercaseBundleKeys = Symbol('bundleKeys');
14355const FILE_PLACEHOLDER = {
14356 type: 'placeholder'
14357};
14358const getOutputBundle = (outputBundleBase) => {
14359 const reservedLowercaseBundleKeys = new Set();
14360 return new Proxy(outputBundleBase, {
14361 deleteProperty(target, key) {
14362 if (typeof key === 'string') {
14363 reservedLowercaseBundleKeys.delete(key.toLowerCase());
14364 }
14365 return Reflect.deleteProperty(target, key);
14366 },
14367 get(target, key) {
14368 if (key === lowercaseBundleKeys) {
14369 return reservedLowercaseBundleKeys;
14370 }
14371 return Reflect.get(target, key);
14372 },
14373 set(target, key, value) {
14374 if (typeof key === 'string') {
14375 reservedLowercaseBundleKeys.add(key.toLowerCase());
14376 }
14377 return Reflect.set(target, key, value);
14378 }
14379 });
14380};
14381
14382function renderNamePattern(pattern, patternName, replacements) {
14383 if (isPathFragment(pattern))
14384 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
14385 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14386 if (!replacements.hasOwnProperty(type)) {
14387 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14388 }
14389 const replacement = replacements[type]();
14390 if (isPathFragment(replacement))
14391 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14392 return replacement;
14393 });
14394}
14395function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
14396 if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
14397 return name;
14398 const ext = extname(name);
14399 name = name.substring(0, name.length - ext.length);
14400 let uniqueName, uniqueIndex = 1;
14401 while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14402 ;
14403 return uniqueName;
14404}
14405
14406const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
14407function getGlobalName(module, globals, hasExports, warn) {
14408 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
14409 if (globalName) {
14410 return globalName;
14411 }
14412 if (hasExports) {
14413 warn({
14414 code: 'MISSING_GLOBAL_NAME',
14415 guess: module.variableName,
14416 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14417 source: module.id
14418 });
14419 return module.variableName;
14420 }
14421}
14422class Chunk {
14423 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
14424 this.orderedModules = orderedModules;
14425 this.inputOptions = inputOptions;
14426 this.outputOptions = outputOptions;
14427 this.unsetOptions = unsetOptions;
14428 this.pluginDriver = pluginDriver;
14429 this.modulesById = modulesById;
14430 this.chunkByModule = chunkByModule;
14431 this.facadeChunkByModule = facadeChunkByModule;
14432 this.includedNamespaces = includedNamespaces;
14433 this.manualChunkAlias = manualChunkAlias;
14434 this.entryModules = [];
14435 this.exportMode = 'named';
14436 this.facadeModule = null;
14437 this.id = null;
14438 this.namespaceVariableName = '';
14439 this.needsExportsShim = false;
14440 this.variableName = '';
14441 this.accessedGlobalsByScope = new Map();
14442 this.dependencies = new Set();
14443 this.dynamicDependencies = new Set();
14444 this.dynamicEntryModules = [];
14445 this.dynamicName = null;
14446 this.exportNamesByVariable = new Map();
14447 this.exports = new Set();
14448 this.exportsByName = new Map();
14449 this.fileName = null;
14450 this.implicitEntryModules = [];
14451 this.implicitlyLoadedBefore = new Set();
14452 this.imports = new Set();
14453 this.includedReexportsByModule = new Map();
14454 this.indentString = undefined;
14455 // This may only be updated in the constructor
14456 this.isEmpty = true;
14457 this.name = null;
14458 this.renderedDependencies = null;
14459 this.renderedExports = null;
14460 this.renderedHash = undefined;
14461 this.renderedModuleSources = new Map();
14462 this.renderedModules = Object.create(null);
14463 this.renderedSource = null;
14464 this.sortedExportNames = null;
14465 this.strictFacade = false;
14466 this.usedModules = undefined;
14467 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14468 const chunkModules = new Set(orderedModules);
14469 for (const module of orderedModules) {
14470 if (module.namespace.included) {
14471 includedNamespaces.add(module);
14472 }
14473 if (this.isEmpty && module.isIncluded()) {
14474 this.isEmpty = false;
14475 }
14476 if (module.info.isEntry || outputOptions.preserveModules) {
14477 this.entryModules.push(module);
14478 }
14479 for (const importer of module.includedDynamicImporters) {
14480 if (!chunkModules.has(importer)) {
14481 this.dynamicEntryModules.push(module);
14482 // Modules with synthetic exports need an artificial namespace for dynamic imports
14483 if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
14484 includedNamespaces.add(module);
14485 this.exports.add(module.namespace);
14486 }
14487 }
14488 }
14489 if (module.implicitlyLoadedAfter.size > 0) {
14490 this.implicitEntryModules.push(module);
14491 }
14492 }
14493 this.suggestedVariableName = makeLegal(this.generateVariableName());
14494 }
14495 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
14496 const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
14497 chunk.assignFacadeName(facadeName, facadedModule);
14498 if (!facadeChunkByModule.has(facadedModule)) {
14499 facadeChunkByModule.set(facadedModule, chunk);
14500 }
14501 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
14502 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
14503 }
14504 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
14505 facadedModule.info.moduleSideEffects &&
14506 facadedModule.hasEffects()) {
14507 chunk.dependencies.add(chunkByModule.get(facadedModule));
14508 }
14509 chunk.ensureReexportsAreAvailableForModule(facadedModule);
14510 chunk.facadeModule = facadedModule;
14511 chunk.strictFacade = true;
14512 return chunk;
14513 }
14514 canModuleBeFacade(module, exposedVariables) {
14515 const moduleExportNamesByVariable = module.getExportNamesByVariable();
14516 for (const exposedVariable of this.exports) {
14517 if (!moduleExportNamesByVariable.has(exposedVariable)) {
14518 if (moduleExportNamesByVariable.size === 0 &&
14519 module.isUserDefinedEntryPoint &&
14520 module.preserveSignature === 'strict' &&
14521 this.unsetOptions.has('preserveEntrySignatures')) {
14522 this.inputOptions.onwarn({
14523 code: 'EMPTY_FACADE',
14524 id: module.id,
14525 message: `To preserve the export signature of the entry module "${relativeId(module.id)}", an empty facade chunk was created. This often happens when creating a bundle for a web app where chunks are placed in script tags and exports are ignored. In this case it is recommended to set "preserveEntrySignatures: false" to avoid this and reduce the number of chunks. Otherwise if this is intentional, set "preserveEntrySignatures: 'strict'" explicitly to silence this warning.`,
14526 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
14527 });
14528 }
14529 return false;
14530 }
14531 }
14532 for (const exposedVariable of exposedVariables) {
14533 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
14534 return false;
14535 }
14536 }
14537 return true;
14538 }
14539 generateExports() {
14540 this.sortedExportNames = null;
14541 const remainingExports = new Set(this.exports);
14542 if (this.facadeModule !== null &&
14543 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
14544 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
14545 for (const [variable, exportNames] of exportNamesByVariable) {
14546 this.exportNamesByVariable.set(variable, [...exportNames]);
14547 for (const exportName of exportNames) {
14548 this.exportsByName.set(exportName, variable);
14549 }
14550 remainingExports.delete(variable);
14551 }
14552 }
14553 if (this.outputOptions.minifyInternalExports) {
14554 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14555 }
14556 else {
14557 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14558 }
14559 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
14560 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
14561 }
14562 generateFacades() {
14563 var _a;
14564 const facades = [];
14565 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
14566 const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
14567 for (const module of entryModules) {
14568 if (module.preserveSignature) {
14569 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
14570 exposedVariables.add(exportedVariable);
14571 }
14572 }
14573 }
14574 for (const module of entryModules) {
14575 const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
14576 // mapping must run after Set 'name' dedupe
14577 name => ({
14578 name
14579 }));
14580 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
14581 requiredFacades.push({});
14582 }
14583 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
14584 if (requiredFacades.length === 0) {
14585 requiredFacades.push({});
14586 }
14587 if (!this.facadeModule) {
14588 const needsStrictFacade = module.preserveSignature === 'strict' ||
14589 (module.preserveSignature === 'exports-only' &&
14590 module.getExportNamesByVariable().size !== 0);
14591 if (!needsStrictFacade ||
14592 this.outputOptions.preserveModules ||
14593 this.canModuleBeFacade(module, exposedVariables)) {
14594 this.facadeModule = module;
14595 this.facadeChunkByModule.set(module, this);
14596 if (module.preserveSignature) {
14597 this.strictFacade = needsStrictFacade;
14598 }
14599 this.assignFacadeName(requiredFacades.shift(), module);
14600 }
14601 }
14602 for (const facadeName of requiredFacades) {
14603 facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
14604 }
14605 }
14606 for (const module of this.dynamicEntryModules) {
14607 if (module.info.syntheticNamedExports)
14608 continue;
14609 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
14610 this.facadeModule = module;
14611 this.facadeChunkByModule.set(module, this);
14612 this.strictFacade = true;
14613 this.dynamicName = getChunkNameFromModule(module);
14614 }
14615 else if (this.facadeModule === module &&
14616 !this.strictFacade &&
14617 this.canModuleBeFacade(module, exposedVariables)) {
14618 this.strictFacade = true;
14619 }
14620 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
14621 this.includedNamespaces.add(module);
14622 this.exports.add(module.namespace);
14623 }
14624 }
14625 if (!this.outputOptions.preserveModules) {
14626 this.addNecessaryImportsForFacades();
14627 }
14628 return facades;
14629 }
14630 generateId(addons, options, bundle, includeHash) {
14631 if (this.fileName !== null) {
14632 return this.fileName;
14633 }
14634 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14635 ? [options.entryFileNames, 'output.entryFileNames']
14636 : [options.chunkFileNames, 'output.chunkFileNames'];
14637 return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
14638 format: () => options.format,
14639 hash: () => includeHash
14640 ? this.computeContentHashWithDependencies(addons, options, bundle)
14641 : '[hash]',
14642 name: () => this.getChunkName()
14643 }), bundle);
14644 }
14645 generateIdPreserveModules(preserveModulesRelativeDir, options, bundle, unsetOptions) {
14646 const [{ id }] = this.orderedModules;
14647 const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14648 let path;
14649 const patternOpt = unsetOptions.has('entryFileNames')
14650 ? '[name][assetExtname].js'
14651 : options.entryFileNames;
14652 const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
14653 if (isAbsolute(sanitizedId)) {
14654 const currentDir = dirname(sanitizedId);
14655 const extension = extname(sanitizedId);
14656 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14657 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14658 ext: () => extension.substring(1),
14659 extname: () => extension,
14660 format: () => options.format,
14661 name: () => this.getChunkName()
14662 });
14663 const currentPath = `${currentDir}/${fileName}`;
14664 const { preserveModulesRoot } = options;
14665 if (preserveModulesRoot && resolve(currentPath).startsWith(preserveModulesRoot)) {
14666 path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14667 }
14668 else {
14669 path = relative(preserveModulesRelativeDir, currentPath);
14670 }
14671 }
14672 else {
14673 const extension = extname(sanitizedId);
14674 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14675 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14676 ext: () => extension.substring(1),
14677 extname: () => extension,
14678 format: () => options.format,
14679 name: () => getAliasName(sanitizedId)
14680 });
14681 path = `_virtual/${fileName}`;
14682 }
14683 return makeUnique(normalize(path), bundle);
14684 }
14685 getChunkInfo() {
14686 const facadeModule = this.facadeModule;
14687 const getChunkName = this.getChunkName.bind(this);
14688 return {
14689 exports: this.getExportNames(),
14690 facadeModuleId: facadeModule && facadeModule.id,
14691 isDynamicEntry: this.dynamicEntryModules.length > 0,
14692 isEntry: facadeModule !== null && facadeModule.info.isEntry,
14693 isImplicitEntry: this.implicitEntryModules.length > 0,
14694 modules: this.renderedModules,
14695 get name() {
14696 return getChunkName();
14697 },
14698 type: 'chunk'
14699 };
14700 }
14701 getChunkInfoWithFileNames() {
14702 return Object.assign(this.getChunkInfo(), {
14703 code: undefined,
14704 dynamicImports: Array.from(this.dynamicDependencies, getId),
14705 fileName: this.id,
14706 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
14707 importedBindings: this.getImportedBindingsPerDependency(),
14708 imports: Array.from(this.dependencies, getId),
14709 map: undefined,
14710 referencedFiles: this.getReferencedFiles()
14711 });
14712 }
14713 getChunkName() {
14714 var _a;
14715 return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
14716 }
14717 getExportNames() {
14718 var _a;
14719 return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14720 }
14721 getRenderedHash() {
14722 if (this.renderedHash)
14723 return this.renderedHash;
14724 const hash = createHash();
14725 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
14726 if (pluginHash) {
14727 augmentation += pluginHash;
14728 }
14729 return augmentation;
14730 });
14731 hash.update(hashAugmentation);
14732 hash.update(this.renderedSource.toString());
14733 hash.update(this.getExportNames()
14734 .map(exportName => {
14735 const variable = this.exportsByName.get(exportName);
14736 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14737 })
14738 .join(','));
14739 return (this.renderedHash = hash.digest('hex'));
14740 }
14741 getVariableExportName(variable) {
14742 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
14743 return '*';
14744 }
14745 return this.exportNamesByVariable.get(variable)[0];
14746 }
14747 link() {
14748 this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
14749 for (const module of this.orderedModules) {
14750 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
14751 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
14752 this.setUpChunkImportsAndExportsForModule(module);
14753 }
14754 }
14755 // prerender allows chunk hashes and names to be generated before finalizing
14756 preRender(options, inputBase, snippets) {
14757 const { _, getPropertyAccess, n } = snippets;
14758 const magicString = new Bundle$1({ separator: `${n}${n}` });
14759 this.usedModules = [];
14760 this.indentString = getIndentString(this.orderedModules, options);
14761 const renderOptions = {
14762 dynamicImportFunction: options.dynamicImportFunction,
14763 exportNamesByVariable: this.exportNamesByVariable,
14764 format: options.format,
14765 freeze: options.freeze,
14766 indent: this.indentString,
14767 namespaceToStringTag: options.namespaceToStringTag,
14768 outputPluginDriver: this.pluginDriver,
14769 snippets
14770 };
14771 // for static and dynamic entry points, inline the execution list to avoid loading latency
14772 if (options.hoistTransitiveImports &&
14773 !this.outputOptions.preserveModules &&
14774 this.facadeModule !== null) {
14775 for (const dep of this.dependencies) {
14776 if (dep instanceof Chunk)
14777 this.inlineChunkDependencies(dep);
14778 }
14779 }
14780 this.prepareModulesForRendering(snippets);
14781 this.setIdentifierRenderResolutions(options);
14782 let hoistedSource = '';
14783 const renderedModules = this.renderedModules;
14784 for (const module of this.orderedModules) {
14785 let renderedLength = 0;
14786 if (module.isIncluded() || this.includedNamespaces.has(module)) {
14787 const source = module.render(renderOptions).trim();
14788 renderedLength = source.length();
14789 if (renderedLength) {
14790 if (options.compact && source.lastLine().includes('//'))
14791 source.append('\n');
14792 this.renderedModuleSources.set(module, source);
14793 magicString.addSource(source);
14794 this.usedModules.push(module);
14795 }
14796 const namespace = module.namespace;
14797 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
14798 const rendered = namespace.renderBlock(renderOptions);
14799 if (namespace.renderFirst())
14800 hoistedSource += n + rendered;
14801 else
14802 magicString.addSource(new MagicString(rendered));
14803 }
14804 }
14805 const { renderedExports, removedExports } = module.getRenderedExports();
14806 const { renderedModuleSources } = this;
14807 renderedModules[module.id] = {
14808 get code() {
14809 var _a, _b;
14810 return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
14811 },
14812 originalLength: module.originalCode.length,
14813 removedExports,
14814 renderedExports,
14815 renderedLength
14816 };
14817 }
14818 if (hoistedSource)
14819 magicString.prepend(hoistedSource + n + n);
14820 if (this.needsExportsShim) {
14821 magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14822 }
14823 if (options.compact) {
14824 this.renderedSource = magicString;
14825 }
14826 else {
14827 this.renderedSource = magicString.trim();
14828 }
14829 this.renderedHash = undefined;
14830 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
14831 const chunkName = this.getChunkName();
14832 this.inputOptions.onwarn({
14833 chunkName,
14834 code: 'EMPTY_BUNDLE',
14835 message: `Generated an empty chunk: "${chunkName}"`
14836 });
14837 }
14838 this.setExternalRenderPaths(options, inputBase);
14839 this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
14840 this.renderedExports =
14841 this.exportMode === 'none'
14842 ? []
14843 : this.getChunkExportDeclarations(options.format, getPropertyAccess);
14844 }
14845 async render(options, addons, outputChunk, snippets) {
14846 timeStart('render format', 2);
14847 const format = options.format;
14848 const finalise = finalisers[format];
14849 if (options.dynamicImportFunction && format !== 'es') {
14850 this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
14851 }
14852 // populate ids in the rendered declarations only here
14853 // as chunk ids known only after prerender
14854 for (const dependency of this.dependencies) {
14855 const renderedDependency = this.renderedDependencies.get(dependency);
14856 if (dependency instanceof ExternalModule) {
14857 const originalId = dependency.renderPath;
14858 renderedDependency.id = escapeId(dependency.renormalizeRenderPath
14859 ? getImportPath(this.id, originalId, false, false)
14860 : originalId);
14861 }
14862 else {
14863 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
14864 renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
14865 }
14866 }
14867 this.finaliseDynamicImports(options, snippets);
14868 this.finaliseImportMetas(format, snippets);
14869 const hasExports = this.renderedExports.length !== 0 ||
14870 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
14871 let topLevelAwaitModule = null;
14872 const accessedGlobals = new Set();
14873 for (const module of this.orderedModules) {
14874 if (module.usesTopLevelAwait) {
14875 topLevelAwaitModule = module.id;
14876 }
14877 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
14878 if (accessedGlobalVariables) {
14879 for (const name of accessedGlobalVariables) {
14880 accessedGlobals.add(name);
14881 }
14882 }
14883 }
14884 if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
14885 return error({
14886 code: 'INVALID_TLA_FORMAT',
14887 id: topLevelAwaitModule,
14888 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
14889 });
14890 }
14891 /* istanbul ignore next */
14892 if (!this.id) {
14893 throw new Error('Internal Error: expecting chunk id');
14894 }
14895 const magicString = finalise(this.renderedSource, {
14896 accessedGlobals,
14897 dependencies: [...this.renderedDependencies.values()],
14898 exports: this.renderedExports,
14899 hasExports,
14900 id: this.id,
14901 indent: this.indentString,
14902 intro: addons.intro,
14903 isEntryFacade: this.outputOptions.preserveModules ||
14904 (this.facadeModule !== null && this.facadeModule.info.isEntry),
14905 isModuleFacade: this.facadeModule !== null,
14906 namedExportsMode: this.exportMode !== 'default',
14907 outro: addons.outro,
14908 snippets,
14909 usesTopLevelAwait: topLevelAwaitModule !== null,
14910 warn: this.inputOptions.onwarn
14911 }, options);
14912 if (addons.banner)
14913 magicString.prepend(addons.banner);
14914 if (addons.footer)
14915 magicString.append(addons.footer);
14916 const prevCode = magicString.toString();
14917 timeEnd('render format', 2);
14918 let map = null;
14919 const chunkSourcemapChain = [];
14920 let code = await renderChunk({
14921 code: prevCode,
14922 options,
14923 outputPluginDriver: this.pluginDriver,
14924 renderChunk: outputChunk,
14925 sourcemapChain: chunkSourcemapChain
14926 });
14927 if (options.sourcemap) {
14928 timeStart('sourcemap', 2);
14929 let file;
14930 if (options.file)
14931 file = resolve(options.sourcemapFile || options.file);
14932 else if (options.dir)
14933 file = resolve(options.dir, this.id);
14934 else
14935 file = resolve(this.id);
14936 const decodedMap = magicString.generateDecodedMap({});
14937 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
14938 map.sources = map.sources
14939 .map(sourcePath => {
14940 const { sourcemapPathTransform } = options;
14941 if (sourcemapPathTransform) {
14942 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
14943 if (typeof newSourcePath !== 'string') {
14944 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
14945 }
14946 return newSourcePath;
14947 }
14948 return sourcePath;
14949 })
14950 .map(normalize);
14951 timeEnd('sourcemap', 2);
14952 }
14953 if (!options.compact && code[code.length - 1] !== '\n')
14954 code += '\n';
14955 return { code, map };
14956 }
14957 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
14958 for (const module of moduleDependencies) {
14959 if (module instanceof Module) {
14960 const chunk = this.chunkByModule.get(module);
14961 if (chunk && chunk !== this) {
14962 chunkDependencies.add(chunk);
14963 }
14964 }
14965 else {
14966 chunkDependencies.add(module);
14967 }
14968 }
14969 }
14970 addNecessaryImportsForFacades() {
14971 for (const [module, variables] of this.includedReexportsByModule) {
14972 if (this.includedNamespaces.has(module)) {
14973 for (const variable of variables) {
14974 this.imports.add(variable);
14975 }
14976 }
14977 }
14978 }
14979 assignFacadeName({ fileName, name }, facadedModule) {
14980 if (fileName) {
14981 this.fileName = fileName;
14982 }
14983 else {
14984 this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
14985 }
14986 }
14987 checkCircularDependencyImport(variable, importingModule) {
14988 const variableModule = variable.module;
14989 if (variableModule instanceof Module) {
14990 const exportChunk = this.chunkByModule.get(variableModule);
14991 let alternativeReexportModule;
14992 do {
14993 alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
14994 if (alternativeReexportModule) {
14995 const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
14996 if (exportingChunk && exportingChunk !== exportChunk) {
14997 this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
14998 }
14999 importingModule = alternativeReexportModule;
15000 }
15001 } while (alternativeReexportModule);
15002 }
15003 }
15004 computeContentHashWithDependencies(addons, options, bundle) {
15005 const hash = createHash();
15006 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
15007 hash.update(options.format);
15008 const dependenciesForHashing = new Set([this]);
15009 for (const current of dependenciesForHashing) {
15010 if (current instanceof ExternalModule) {
15011 hash.update(`:${current.renderPath}`);
15012 }
15013 else {
15014 hash.update(current.getRenderedHash());
15015 hash.update(current.generateId(addons, options, bundle, false));
15016 }
15017 if (current instanceof ExternalModule)
15018 continue;
15019 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
15020 dependenciesForHashing.add(dependency);
15021 }
15022 }
15023 return hash.digest('hex').substr(0, 8);
15024 }
15025 ensureReexportsAreAvailableForModule(module) {
15026 const includedReexports = [];
15027 const map = module.getExportNamesByVariable();
15028 for (const exportedVariable of map.keys()) {
15029 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
15030 const importedVariable = isSynthetic
15031 ? exportedVariable.getBaseVariable()
15032 : exportedVariable;
15033 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
15034 this.checkCircularDependencyImport(importedVariable, module);
15035 const exportingModule = importedVariable.module;
15036 if (exportingModule instanceof Module) {
15037 const chunk = this.chunkByModule.get(exportingModule);
15038 if (chunk && chunk !== this) {
15039 chunk.exports.add(importedVariable);
15040 includedReexports.push(importedVariable);
15041 if (isSynthetic) {
15042 this.imports.add(importedVariable);
15043 }
15044 }
15045 }
15046 }
15047 }
15048 if (includedReexports.length) {
15049 this.includedReexportsByModule.set(module, includedReexports);
15050 }
15051 }
15052 finaliseDynamicImports(options, snippets) {
15053 const stripKnownJsExtensions = options.format === 'amd' && !options.amd.forceJsExtensionForImports;
15054 for (const [module, code] of this.renderedModuleSources) {
15055 for (const { node, resolution } of module.dynamicImports) {
15056 const chunk = this.chunkByModule.get(resolution);
15057 const facadeChunk = this.facadeChunkByModule.get(resolution);
15058 if (!resolution || !node.included || chunk === this) {
15059 continue;
15060 }
15061 const renderedResolution = resolution instanceof Module
15062 ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
15063 : resolution instanceof ExternalModule
15064 ? `'${escapeId(resolution.renormalizeRenderPath
15065 ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
15066 : resolution.renderPath)}'`
15067 : resolution;
15068 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
15069 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
15070 chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
15071 }
15072 }
15073 }
15074 finaliseImportMetas(format, snippets) {
15075 for (const [module, code] of this.renderedModuleSources) {
15076 for (const importMeta of module.importMetas) {
15077 importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
15078 }
15079 }
15080 }
15081 generateVariableName() {
15082 if (this.manualChunkAlias) {
15083 return this.manualChunkAlias;
15084 }
15085 const moduleForNaming = this.entryModules[0] ||
15086 this.implicitEntryModules[0] ||
15087 this.dynamicEntryModules[0] ||
15088 this.orderedModules[this.orderedModules.length - 1];
15089 if (moduleForNaming) {
15090 return getChunkNameFromModule(moduleForNaming);
15091 }
15092 return 'chunk';
15093 }
15094 getChunkDependencyDeclarations(options, getPropertyAccess) {
15095 const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
15096 const reexportSpecifiers = this.getReexportSpecifiers();
15097 const dependencyDeclaration = new Map();
15098 for (const dep of this.dependencies) {
15099 const imports = importSpecifiers.get(dep) || null;
15100 const reexports = reexportSpecifiers.get(dep) || null;
15101 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
15102 dependencyDeclaration.set(dep, {
15103 defaultVariableName: dep.defaultVariableName,
15104 globalName: (dep instanceof ExternalModule &&
15105 (options.format === 'umd' || options.format === 'iife') &&
15106 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
15107 id: undefined,
15108 imports,
15109 isChunk: dep instanceof Chunk,
15110 name: dep.variableName,
15111 namedExportsMode,
15112 namespaceVariableName: dep.namespaceVariableName,
15113 reexports
15114 });
15115 }
15116 return dependencyDeclaration;
15117 }
15118 getChunkExportDeclarations(format, getPropertyAccess) {
15119 const exports = [];
15120 for (const exportName of this.getExportNames()) {
15121 if (exportName[0] === '*')
15122 continue;
15123 const variable = this.exportsByName.get(exportName);
15124 if (!(variable instanceof SyntheticNamedExportVariable)) {
15125 const module = variable.module;
15126 if (module && this.chunkByModule.get(module) !== this)
15127 continue;
15128 }
15129 let expression = null;
15130 let hoisted = false;
15131 let local = variable.getName(getPropertyAccess);
15132 if (variable instanceof LocalVariable) {
15133 for (const declaration of variable.declarations) {
15134 if (declaration.parent instanceof FunctionDeclaration ||
15135 (declaration instanceof ExportDefaultDeclaration &&
15136 declaration.declaration instanceof FunctionDeclaration)) {
15137 hoisted = true;
15138 break;
15139 }
15140 }
15141 }
15142 else if (variable instanceof SyntheticNamedExportVariable) {
15143 expression = local;
15144 if (format === 'es') {
15145 local = variable.renderName;
15146 }
15147 }
15148 exports.push({
15149 exported: exportName,
15150 expression,
15151 hoisted,
15152 local
15153 });
15154 }
15155 return exports;
15156 }
15157 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
15158 const dependencies = new Set();
15159 const deconflictedDefault = new Set();
15160 const deconflictedNamespace = new Set();
15161 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
15162 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
15163 const module = variable.module;
15164 if (module instanceof ExternalModule) {
15165 dependencies.add(module);
15166 if (addNonNamespacesAndInteropHelpers) {
15167 if (variable.name === 'default') {
15168 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
15169 deconflictedDefault.add(module);
15170 }
15171 }
15172 else if (variable.name === '*') {
15173 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
15174 deconflictedNamespace.add(module);
15175 }
15176 }
15177 }
15178 }
15179 else {
15180 const chunk = this.chunkByModule.get(module);
15181 if (chunk !== this) {
15182 dependencies.add(chunk);
15183 if (addNonNamespacesAndInteropHelpers &&
15184 chunk.exportMode === 'default' &&
15185 variable.isNamespace) {
15186 deconflictedNamespace.add(chunk);
15187 }
15188 }
15189 }
15190 }
15191 }
15192 if (addDependenciesWithoutBindings) {
15193 for (const dependency of this.dependencies) {
15194 dependencies.add(dependency);
15195 }
15196 }
15197 return { deconflictedDefault, deconflictedNamespace, dependencies };
15198 }
15199 getFallbackChunkName() {
15200 if (this.manualChunkAlias) {
15201 return this.manualChunkAlias;
15202 }
15203 if (this.dynamicName) {
15204 return this.dynamicName;
15205 }
15206 if (this.fileName) {
15207 return getAliasName(this.fileName);
15208 }
15209 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15210 }
15211 getImportSpecifiers(getPropertyAccess) {
15212 const { interop } = this.outputOptions;
15213 const importsByDependency = new Map();
15214 for (const variable of this.imports) {
15215 const module = variable.module;
15216 let dependency;
15217 let imported;
15218 if (module instanceof ExternalModule) {
15219 dependency = module;
15220 imported = variable.name;
15221 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15222 return error(errUnexpectedNamedImport(module.id, imported, false));
15223 }
15224 }
15225 else {
15226 dependency = this.chunkByModule.get(module);
15227 imported = dependency.getVariableExportName(variable);
15228 }
15229 getOrCreate(importsByDependency, dependency, () => []).push({
15230 imported,
15231 local: variable.getName(getPropertyAccess)
15232 });
15233 }
15234 return importsByDependency;
15235 }
15236 getImportedBindingsPerDependency() {
15237 const importSpecifiers = {};
15238 for (const [dependency, declaration] of this.renderedDependencies) {
15239 const specifiers = new Set();
15240 if (declaration.imports) {
15241 for (const { imported } of declaration.imports) {
15242 specifiers.add(imported);
15243 }
15244 }
15245 if (declaration.reexports) {
15246 for (const { imported } of declaration.reexports) {
15247 specifiers.add(imported);
15248 }
15249 }
15250 importSpecifiers[dependency.id] = [...specifiers];
15251 }
15252 return importSpecifiers;
15253 }
15254 getReexportSpecifiers() {
15255 const { externalLiveBindings, interop } = this.outputOptions;
15256 const reexportSpecifiers = new Map();
15257 for (let exportName of this.getExportNames()) {
15258 let dependency;
15259 let imported;
15260 let needsLiveBinding = false;
15261 if (exportName[0] === '*') {
15262 const id = exportName.substring(1);
15263 if (interop(id) === 'defaultOnly') {
15264 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15265 }
15266 needsLiveBinding = externalLiveBindings;
15267 dependency = this.modulesById.get(id);
15268 imported = exportName = '*';
15269 }
15270 else {
15271 const variable = this.exportsByName.get(exportName);
15272 if (variable instanceof SyntheticNamedExportVariable)
15273 continue;
15274 const module = variable.module;
15275 if (module instanceof Module) {
15276 dependency = this.chunkByModule.get(module);
15277 if (dependency === this)
15278 continue;
15279 imported = dependency.getVariableExportName(variable);
15280 needsLiveBinding = variable.isReassigned;
15281 }
15282 else {
15283 dependency = module;
15284 imported = variable.name;
15285 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15286 return error(errUnexpectedNamedImport(module.id, imported, true));
15287 }
15288 needsLiveBinding =
15289 externalLiveBindings &&
15290 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
15291 }
15292 }
15293 getOrCreate(reexportSpecifiers, dependency, () => []).push({
15294 imported,
15295 needsLiveBinding,
15296 reexported: exportName
15297 });
15298 }
15299 return reexportSpecifiers;
15300 }
15301 getReferencedFiles() {
15302 const referencedFiles = [];
15303 for (const module of this.orderedModules) {
15304 for (const meta of module.importMetas) {
15305 const fileName = meta.getReferencedFileName(this.pluginDriver);
15306 if (fileName) {
15307 referencedFiles.push(fileName);
15308 }
15309 }
15310 }
15311 return referencedFiles;
15312 }
15313 inlineChunkDependencies(chunk) {
15314 for (const dep of chunk.dependencies) {
15315 if (this.dependencies.has(dep))
15316 continue;
15317 this.dependencies.add(dep);
15318 if (dep instanceof Chunk) {
15319 this.inlineChunkDependencies(dep);
15320 }
15321 }
15322 }
15323 prepareModulesForRendering(snippets) {
15324 var _a;
15325 const accessedGlobalsByScope = this.accessedGlobalsByScope;
15326 for (const module of this.orderedModules) {
15327 for (const { node, resolution } of module.dynamicImports) {
15328 if (node.included) {
15329 if (resolution instanceof Module) {
15330 const chunk = this.chunkByModule.get(resolution);
15331 if (chunk === this) {
15332 node.setInternalResolution(resolution.namespace);
15333 }
15334 else {
15335 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15336 }
15337 }
15338 else {
15339 node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15340 }
15341 }
15342 }
15343 for (const importMeta of module.importMetas) {
15344 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
15345 }
15346 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
15347 module.namespace.prepare(accessedGlobalsByScope);
15348 }
15349 }
15350 }
15351 setExternalRenderPaths(options, inputBase) {
15352 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
15353 if (dependency instanceof ExternalModule) {
15354 dependency.setRenderPath(options, inputBase);
15355 }
15356 }
15357 }
15358 setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
15359 const syntheticExports = new Set();
15360 for (const exportName of this.getExportNames()) {
15361 const exportVariable = this.exportsByName.get(exportName);
15362 if (format !== 'es' &&
15363 format !== 'system' &&
15364 exportVariable.isReassigned &&
15365 !exportVariable.isId) {
15366 exportVariable.setRenderNames('exports', exportName);
15367 }
15368 else if (exportVariable instanceof SyntheticNamedExportVariable) {
15369 syntheticExports.add(exportVariable);
15370 }
15371 else {
15372 exportVariable.setRenderNames(null, null);
15373 }
15374 }
15375 for (const module of this.orderedModules) {
15376 if (module.needsExportShim) {
15377 this.needsExportsShim = true;
15378 break;
15379 }
15380 }
15381 const usedNames = new Set(['Object', 'Promise']);
15382 if (this.needsExportsShim) {
15383 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
15384 }
15385 if (namespaceToStringTag) {
15386 usedNames.add('Symbol');
15387 }
15388 switch (format) {
15389 case 'system':
15390 usedNames.add('module').add('exports');
15391 break;
15392 case 'es':
15393 break;
15394 case 'cjs':
15395 usedNames.add('module').add('require').add('__filename').add('__dirname');
15396 // fallthrough
15397 default:
15398 usedNames.add('exports');
15399 for (const helper of HELPER_NAMES) {
15400 usedNames.add(helper);
15401 }
15402 }
15403 deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
15404 }
15405 setUpChunkImportsAndExportsForModule(module) {
15406 const moduleImports = new Set(module.includedImports);
15407 // when we are not preserving modules, we need to make all namespace variables available for
15408 // rendering the namespace object
15409 if (!this.outputOptions.preserveModules) {
15410 if (this.includedNamespaces.has(module)) {
15411 const memberVariables = module.namespace.getMemberVariables();
15412 for (const variable of Object.values(memberVariables)) {
15413 moduleImports.add(variable);
15414 }
15415 }
15416 }
15417 for (let variable of moduleImports) {
15418 if (variable instanceof ExportDefaultVariable) {
15419 variable = variable.getOriginalVariable();
15420 }
15421 if (variable instanceof SyntheticNamedExportVariable) {
15422 variable = variable.getBaseVariable();
15423 }
15424 const chunk = this.chunkByModule.get(variable.module);
15425 if (chunk !== this) {
15426 this.imports.add(variable);
15427 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
15428 variable.module instanceof Module) {
15429 chunk.exports.add(variable);
15430 this.checkCircularDependencyImport(variable, module);
15431 }
15432 }
15433 }
15434 if (this.includedNamespaces.has(module) ||
15435 (module.info.isEntry && module.preserveSignature !== false) ||
15436 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
15437 this.ensureReexportsAreAvailableForModule(module);
15438 }
15439 for (const { node, resolution } of module.dynamicImports) {
15440 if (node.included &&
15441 resolution instanceof Module &&
15442 this.chunkByModule.get(resolution) === this &&
15443 !this.includedNamespaces.has(resolution)) {
15444 this.includedNamespaces.add(resolution);
15445 this.ensureReexportsAreAvailableForModule(resolution);
15446 }
15447 }
15448 }
15449}
15450function getChunkNameFromModule(module) {
15451 var _a, _b, _c, _d;
15452 return ((_d = (_b = (_a = module.chunkNames.find(({ isUserDefined }) => isUserDefined)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (_c = module.chunkNames[0]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : getAliasName(module.id));
15453}
15454const QUERY_HASH_REGEX = /[?#]/;
15455
15456const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
15457const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
15458async function createAddons(options, outputPluginDriver) {
15459 try {
15460 let [banner, footer, intro, outro] = await Promise.all([
15461 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
15462 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
15463 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
15464 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
15465 ]);
15466 if (intro)
15467 intro += '\n\n';
15468 if (outro)
15469 outro = `\n\n${outro}`;
15470 if (banner.length)
15471 banner += '\n';
15472 if (footer.length)
15473 footer = '\n' + footer;
15474 return { banner, footer, intro, outro };
15475 }
15476 catch (err) {
15477 return error({
15478 code: 'ADDON_ERROR',
15479 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
15480\tError Message: ${err.message}`
15481 });
15482 }
15483}
15484
15485function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15486 const chunkDefinitions = [];
15487 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15488 const manualChunkModulesByAlias = Object.create(null);
15489 for (const [entry, alias] of manualChunkAliasByEntry) {
15490 const chunkModules = (manualChunkModulesByAlias[alias] =
15491 manualChunkModulesByAlias[alias] || []);
15492 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15493 }
15494 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15495 chunkDefinitions.push({ alias, modules });
15496 }
15497 const assignedEntryPointsByModule = new Map();
15498 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15499 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15500 const staticEntries = new Set(entryModules);
15501 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15502 const modulesToHandle = new Set([entry]);
15503 for (const module of modulesToHandle) {
15504 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15505 if (dynamicDependentEntryPoints &&
15506 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15507 continue;
15508 }
15509 else {
15510 assignedEntryPoints.add(entry);
15511 }
15512 for (const dependency of module.getDependenciesToBeIncluded()) {
15513 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15514 modulesToHandle.add(dependency);
15515 }
15516 }
15517 }
15518 }
15519 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15520 const entriesToCheck = new Set(entryPoints);
15521 for (const entry of entriesToCheck) {
15522 if (!containedIn.has(entry)) {
15523 if (staticEntries.has(entry))
15524 return false;
15525 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15526 for (const dependentEntry of dynamicallyDependentEntryPoints) {
15527 entriesToCheck.add(dependentEntry);
15528 }
15529 }
15530 }
15531 return true;
15532 }
15533 for (const entry of entryModules) {
15534 if (!modulesInManualChunks.has(entry)) {
15535 assignEntryToStaticDependencies(entry, null);
15536 }
15537 }
15538 for (const entry of dynamicEntryModules) {
15539 if (!modulesInManualChunks.has(entry)) {
15540 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
15541 }
15542 }
15543 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
15544 return chunkDefinitions;
15545}
15546function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
15547 const modulesToHandle = new Set([entry]);
15548 for (const module of modulesToHandle) {
15549 modulesInManualChunks.add(module);
15550 manualChunkModules.push(module);
15551 for (const dependency of module.dependencies) {
15552 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15553 modulesToHandle.add(dependency);
15554 }
15555 }
15556 }
15557}
15558function analyzeModuleGraph(entryModules) {
15559 const dynamicEntryModules = new Set();
15560 const dependentEntryPointsByModule = new Map();
15561 const entriesToHandle = new Set(entryModules);
15562 for (const currentEntry of entriesToHandle) {
15563 const modulesToHandle = new Set([currentEntry]);
15564 for (const module of modulesToHandle) {
15565 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
15566 for (const dependency of module.getDependenciesToBeIncluded()) {
15567 if (!(dependency instanceof ExternalModule)) {
15568 modulesToHandle.add(dependency);
15569 }
15570 }
15571 for (const { resolution } of module.dynamicImports) {
15572 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
15573 dynamicEntryModules.add(resolution);
15574 entriesToHandle.add(resolution);
15575 }
15576 }
15577 for (const dependency of module.implicitlyLoadedBefore) {
15578 dynamicEntryModules.add(dependency);
15579 entriesToHandle.add(dependency);
15580 }
15581 }
15582 }
15583 return { dependentEntryPointsByModule, dynamicEntryModules };
15584}
15585function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15586 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15587 for (const dynamicEntry of dynamicEntryModules) {
15588 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15589 for (const importer of [
15590 ...dynamicEntry.includedDynamicImporters,
15591 ...dynamicEntry.implicitlyLoadedAfter
15592 ]) {
15593 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15594 dynamicDependentEntryPoints.add(entryPoint);
15595 }
15596 }
15597 }
15598 return dynamicallyDependentEntryPointsByDynamicEntry;
15599}
15600function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15601 const chunkModules = Object.create(null);
15602 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15603 let chunkSignature = '';
15604 for (const entry of allEntryPoints) {
15605 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15606 }
15607 const chunk = chunkModules[chunkSignature];
15608 if (chunk) {
15609 chunk.push(module);
15610 }
15611 else {
15612 chunkModules[chunkSignature] = [module];
15613 }
15614 }
15615 return Object.values(chunkModules).map(modules => ({
15616 alias: null,
15617 modules
15618 }));
15619}
15620
15621// ported from https://github.com/substack/node-commondir
15622function commondir(files) {
15623 if (files.length === 0)
15624 return '/';
15625 if (files.length === 1)
15626 return dirname(files[0]);
15627 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15628 const pathSegements = file.split(/\/+|\\+/);
15629 let i;
15630 for (i = 0; commonSegments[i] === pathSegements[i] &&
15631 i < Math.min(commonSegments.length, pathSegements.length); i++)
15632 ;
15633 return commonSegments.slice(0, i);
15634 }, files[0].split(/\/+|\\+/));
15635 // Windows correctly handles paths with forward-slashes
15636 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15637}
15638
15639const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15640function sortByExecutionOrder(units) {
15641 units.sort(compareExecIndex);
15642}
15643function analyseModuleExecution(entryModules) {
15644 let nextExecIndex = 0;
15645 const cyclePaths = [];
15646 const analysedModules = new Set();
15647 const dynamicImports = new Set();
15648 const parents = new Map();
15649 const orderedModules = [];
15650 const analyseModule = (module) => {
15651 if (module instanceof Module) {
15652 for (const dependency of module.dependencies) {
15653 if (parents.has(dependency)) {
15654 if (!analysedModules.has(dependency)) {
15655 cyclePaths.push(getCyclePath(dependency, module, parents));
15656 }
15657 continue;
15658 }
15659 parents.set(dependency, module);
15660 analyseModule(dependency);
15661 }
15662 for (const dependency of module.implicitlyLoadedBefore) {
15663 dynamicImports.add(dependency);
15664 }
15665 for (const { resolution } of module.dynamicImports) {
15666 if (resolution instanceof Module) {
15667 dynamicImports.add(resolution);
15668 }
15669 }
15670 orderedModules.push(module);
15671 }
15672 module.execIndex = nextExecIndex++;
15673 analysedModules.add(module);
15674 };
15675 for (const curEntry of entryModules) {
15676 if (!parents.has(curEntry)) {
15677 parents.set(curEntry, null);
15678 analyseModule(curEntry);
15679 }
15680 }
15681 for (const curEntry of dynamicImports) {
15682 if (!parents.has(curEntry)) {
15683 parents.set(curEntry, null);
15684 analyseModule(curEntry);
15685 }
15686 }
15687 return { cyclePaths, orderedModules };
15688}
15689function getCyclePath(module, parent, parents) {
15690 const cycleSymbol = Symbol(module.id);
15691 const path = [relativeId(module.id)];
15692 let nextModule = parent;
15693 module.cycles.add(cycleSymbol);
15694 while (nextModule !== module) {
15695 nextModule.cycles.add(cycleSymbol);
15696 path.push(relativeId(nextModule.id));
15697 nextModule = parents.get(nextModule);
15698 }
15699 path.push(path[0]);
15700 path.reverse();
15701 return path;
15702}
15703
15704function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15705 const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15706 const cnst = constBindings ? 'const' : 'var';
15707 const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15708 const getFunctionIntro = arrowFunctions
15709 ? (params, { isAsync, name }) => {
15710 const singleParam = params.length === 1;
15711 const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15712 return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
15713 }
15714 : getNonArrowFunctionIntro;
15715 const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15716 `${getFunctionIntro(params, {
15717 isAsync: false,
15718 name
15719 })}${arrowFunctions
15720 ? lineBreakIndent
15721 ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
15722 : ''
15723 : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
15724 arrowFunctions
15725 ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15726 : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15727 ];
15728 const isValidPropName = reservedNamesAsProps
15729 ? (name) => validPropName.test(name)
15730 : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15731 return {
15732 _,
15733 cnst,
15734 getDirectReturnFunction,
15735 getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15736 const [left, right] = getDirectReturnFunction(params, {
15737 functionReturn: true,
15738 lineBreakIndent: null,
15739 name: null
15740 });
15741 return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
15742 },
15743 getFunctionIntro,
15744 getNonArrowFunctionIntro,
15745 getObject(fields, { lineBreakIndent }) {
15746 const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
15747 return `{${fields
15748 .map(([key, value]) => {
15749 if (key === null)
15750 return `${prefix}${value}`;
15751 const needsQuotes = !isValidPropName(key);
15752 return key === value && objectShorthand && !needsQuotes
15753 ? prefix + key
15754 : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15755 })
15756 .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15757 },
15758 getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15759 n,
15760 s
15761 };
15762}
15763const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15764const validPropName = /^(?!\d)[\w$]+$/;
15765
15766class Bundle {
15767 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
15768 this.outputOptions = outputOptions;
15769 this.unsetOptions = unsetOptions;
15770 this.inputOptions = inputOptions;
15771 this.pluginDriver = pluginDriver;
15772 this.graph = graph;
15773 this.facadeChunkByModule = new Map();
15774 this.includedNamespaces = new Set();
15775 }
15776 async generate(isWrite) {
15777 timeStart('GENERATE', 1);
15778 const outputBundleBase = Object.create(null);
15779 const outputBundle = getOutputBundle(outputBundleBase);
15780 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
15781 try {
15782 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
15783 timeStart('generate chunks', 2);
15784 const chunks = await this.generateChunks();
15785 if (chunks.length > 1) {
15786 validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
15787 }
15788 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
15789 timeEnd('generate chunks', 2);
15790 timeStart('render modules', 2);
15791 // We need to create addons before prerender because at the moment, there
15792 // can be no async code between prerender and render due to internal state
15793 const addons = await createAddons(this.outputOptions, this.pluginDriver);
15794 const snippets = getGenerateCodeSnippets(this.outputOptions);
15795 this.prerenderChunks(chunks, inputBase, snippets);
15796 timeEnd('render modules', 2);
15797 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
15798 }
15799 catch (err) {
15800 await this.pluginDriver.hookParallel('renderError', [err]);
15801 throw err;
15802 }
15803 await this.pluginDriver.hookSeq('generateBundle', [
15804 this.outputOptions,
15805 outputBundle,
15806 isWrite
15807 ]);
15808 this.finaliseAssets(outputBundle);
15809 validateOutputBundleFileNames(outputBundle);
15810 timeEnd('GENERATE', 1);
15811 return outputBundleBase;
15812 }
15813 async addFinalizedChunksToBundle(chunks, inputBase, addons, bundle, snippets) {
15814 this.assignChunkIds(chunks, inputBase, addons, bundle);
15815 for (const chunk of chunks) {
15816 bundle[chunk.id] = chunk.getChunkInfoWithFileNames();
15817 }
15818 await Promise.all(chunks.map(async (chunk) => {
15819 const outputChunk = bundle[chunk.id];
15820 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
15821 }));
15822 }
15823 async addManualChunks(manualChunks) {
15824 const manualChunkAliasByEntry = new Map();
15825 const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
15826 alias,
15827 entries: await this.graph.moduleLoader.addAdditionalModules(files)
15828 })));
15829 for (const { alias, entries } of chunkEntries) {
15830 for (const entry of entries) {
15831 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
15832 }
15833 }
15834 return manualChunkAliasByEntry;
15835 }
15836 assignChunkIds(chunks, inputBase, addons, bundle) {
15837 const entryChunks = [];
15838 const otherChunks = [];
15839 for (const chunk of chunks) {
15840 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
15841 ? entryChunks
15842 : otherChunks).push(chunk);
15843 }
15844 // make sure entry chunk names take precedence with regard to deconflicting
15845 const chunksForNaming = entryChunks.concat(otherChunks);
15846 for (const chunk of chunksForNaming) {
15847 if (this.outputOptions.file) {
15848 chunk.id = basename(this.outputOptions.file);
15849 }
15850 else if (this.outputOptions.preserveModules) {
15851 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
15852 }
15853 else {
15854 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
15855 }
15856 bundle[chunk.id] = FILE_PLACEHOLDER;
15857 }
15858 }
15859 assignManualChunks(getManualChunk) {
15860 const manualChunkAliasesWithEntry = [];
15861 const manualChunksApi = {
15862 getModuleIds: () => this.graph.modulesById.keys(),
15863 getModuleInfo: this.graph.getModuleInfo
15864 };
15865 for (const module of this.graph.modulesById.values()) {
15866 if (module instanceof Module) {
15867 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
15868 if (typeof manualChunkAlias === 'string') {
15869 manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
15870 }
15871 }
15872 }
15873 manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
15874 const manualChunkAliasByEntry = new Map();
15875 for (const [alias, module] of manualChunkAliasesWithEntry) {
15876 addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
15877 }
15878 return manualChunkAliasByEntry;
15879 }
15880 finaliseAssets(outputBundle) {
15881 for (const file of Object.values(outputBundle)) {
15882 if (!file.type) {
15883 warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
15884 file.type = 'asset';
15885 }
15886 if (this.outputOptions.validate && 'code' in file) {
15887 try {
15888 this.graph.contextParse(file.code, {
15889 allowHashBang: true,
15890 ecmaVersion: 'latest'
15891 });
15892 }
15893 catch (err) {
15894 this.inputOptions.onwarn(errChunkInvalid(file, err));
15895 }
15896 }
15897 }
15898 this.pluginDriver.finaliseAssets();
15899 }
15900 async generateChunks() {
15901 const { manualChunks } = this.outputOptions;
15902 const manualChunkAliasByEntry = typeof manualChunks === 'object'
15903 ? await this.addManualChunks(manualChunks)
15904 : this.assignManualChunks(manualChunks);
15905 const chunks = [];
15906 const chunkByModule = new Map();
15907 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
15908 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
15909 : this.outputOptions.preserveModules
15910 ? getIncludedModules(this.graph.modulesById).map(module => ({
15911 alias: null,
15912 modules: [module]
15913 }))
15914 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
15915 sortByExecutionOrder(modules);
15916 const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
15917 chunks.push(chunk);
15918 for (const module of modules) {
15919 chunkByModule.set(module, chunk);
15920 }
15921 }
15922 for (const chunk of chunks) {
15923 chunk.link();
15924 }
15925 const facades = [];
15926 for (const chunk of chunks) {
15927 facades.push(...chunk.generateFacades());
15928 }
15929 return [...chunks, ...facades];
15930 }
15931 prerenderChunks(chunks, inputBase, snippets) {
15932 for (const chunk of chunks) {
15933 chunk.generateExports();
15934 }
15935 for (const chunk of chunks) {
15936 chunk.preRender(this.outputOptions, inputBase, snippets);
15937 }
15938 }
15939}
15940function getAbsoluteEntryModulePaths(chunks) {
15941 const absoluteEntryModulePaths = [];
15942 for (const chunk of chunks) {
15943 for (const entryModule of chunk.entryModules) {
15944 if (isAbsolute(entryModule.id)) {
15945 absoluteEntryModulePaths.push(entryModule.id);
15946 }
15947 }
15948 }
15949 return absoluteEntryModulePaths;
15950}
15951function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
15952 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
15953 return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
15954 if (typeof outputOptions.file === 'string')
15955 return error(errInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
15956 if (outputOptions.sourcemapFile)
15957 return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
15958 if (!outputOptions.amd.autoId && outputOptions.amd.id)
15959 onWarn(errInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
15960}
15961function getIncludedModules(modulesById) {
15962 return [...modulesById.values()].filter((module) => module instanceof Module &&
15963 (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
15964}
15965function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
15966 const existingAlias = manualChunkAliasByEntry.get(module);
15967 if (typeof existingAlias === 'string' && existingAlias !== alias) {
15968 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
15969 }
15970 manualChunkAliasByEntry.set(module, alias);
15971}
15972function isFileNameOutsideOutputDirectory(fileName) {
15973 // Use join() to normalize ".." segments, then replace backslashes so the
15974 // string checks below work identically on Windows and POSIX.
15975 const normalized = join(fileName).replace(/\\/g, '/');
15976 return (normalized === '..' ||
15977 normalized.startsWith('../') ||
15978 normalized === '.' ||
15979 isAbsolute(normalized));
15980}
15981function validateOutputBundleFileNames(bundle) {
15982 for (const [bundleKey, entry] of Object.entries(bundle)) {
15983 if (isFileNameOutsideOutputDirectory(bundleKey)) {
15984 return error(errFileNameOutsideOutputDirectory(bundleKey));
15985 }
15986 if (entry.type !== 'placeholder') {
15987 const { fileName } = entry;
15988 if (fileName !== bundleKey && isFileNameOutsideOutputDirectory(fileName)) {
15989 return error(errFileNameOutsideOutputDirectory(fileName));
15990 }
15991 }
15992 }
15993}
15994
15995// This file was generated. Do not modify manually!
15996var 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, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 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, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
15997
15998// This file was generated. Do not modify manually!
15999var 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 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, 38, 6, 186, 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, 19, 72, 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, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 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, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 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, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
16000
16001// This file was generated. Do not modify manually!
16002var 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\u0898-\u089f\u08ca-\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\u0c3c\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\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";
16003
16004// This file was generated. Do not modify manually!
16005var 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\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-\u1711\u171f-\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-\u1b4c\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-\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-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\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";
16006
16007// These are a run-length and offset encoded representation of the
16008
16009// Reserved word lists for various dialects of the language
16010
16011var reservedWords = {
16012 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",
16013 5: "class enum extends super const export import",
16014 6: "enum",
16015 strict: "implements interface let package private protected public static yield",
16016 strictBind: "eval arguments"
16017};
16018
16019// And the keywords
16020
16021var 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";
16022
16023var keywords$1 = {
16024 5: ecma5AndLessKeywords,
16025 "5module": ecma5AndLessKeywords + " export import",
16026 6: ecma5AndLessKeywords + " const class extends export import super"
16027};
16028
16029var keywordRelationalOperator = /^in(stanceof)?$/;
16030
16031// ## Character categories
16032
16033var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
16034var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
16035
16036// This has a complexity linear to the value of the code. The
16037// assumption is that looking up astral identifier characters is
16038// rare.
16039function isInAstralSet(code, set) {
16040 var pos = 0x10000;
16041 for (var i = 0; i < set.length; i += 2) {
16042 pos += set[i];
16043 if (pos > code) { return false }
16044 pos += set[i + 1];
16045 if (pos >= code) { return true }
16046 }
16047}
16048
16049// Test whether a given character code starts an identifier.
16050
16051function isIdentifierStart(code, astral) {
16052 if (code < 65) { return code === 36 }
16053 if (code < 91) { return true }
16054 if (code < 97) { return code === 95 }
16055 if (code < 123) { return true }
16056 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
16057 if (astral === false) { return false }
16058 return isInAstralSet(code, astralIdentifierStartCodes)
16059}
16060
16061// Test whether a given character is part of an identifier.
16062
16063function isIdentifierChar(code, astral) {
16064 if (code < 48) { return code === 36 }
16065 if (code < 58) { return true }
16066 if (code < 65) { return false }
16067 if (code < 91) { return true }
16068 if (code < 97) { return code === 95 }
16069 if (code < 123) { return true }
16070 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
16071 if (astral === false) { return false }
16072 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
16073}
16074
16075// ## Token types
16076
16077// The assignment of fine-grained, information-carrying type objects
16078// allows the tokenizer to store the information it has about a
16079// token in a way that is very cheap for the parser to look up.
16080
16081// All token type variables start with an underscore, to make them
16082// easy to recognize.
16083
16084// The `beforeExpr` property is used to disambiguate between regular
16085// expressions and divisions. It is set on all token types that can
16086// be followed by an expression (thus, a slash after them would be a
16087// regular expression).
16088//
16089// The `startsExpr` property is used to check if the token ends a
16090// `yield` expression. It is set on all token types that either can
16091// directly start an expression (like a quotation mark) or can
16092// continue an expression (like the body of a string).
16093//
16094// `isLoop` marks a keyword as starting a loop, which is important
16095// to know when parsing a label, in order to allow or disallow
16096// continue jumps to that label.
16097
16098var TokenType = function TokenType(label, conf) {
16099 if ( conf === void 0 ) conf = {};
16100
16101 this.label = label;
16102 this.keyword = conf.keyword;
16103 this.beforeExpr = !!conf.beforeExpr;
16104 this.startsExpr = !!conf.startsExpr;
16105 this.isLoop = !!conf.isLoop;
16106 this.isAssign = !!conf.isAssign;
16107 this.prefix = !!conf.prefix;
16108 this.postfix = !!conf.postfix;
16109 this.binop = conf.binop || null;
16110 this.updateContext = null;
16111};
16112
16113function binop(name, prec) {
16114 return new TokenType(name, {beforeExpr: true, binop: prec})
16115}
16116var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
16117
16118// Map keyword names to token types.
16119
16120var keywords = {};
16121
16122// Succinct definitions of keyword token types
16123function kw(name, options) {
16124 if ( options === void 0 ) options = {};
16125
16126 options.keyword = name;
16127 return keywords[name] = new TokenType(name, options)
16128}
16129
16130var types$1 = {
16131 num: new TokenType("num", startsExpr),
16132 regexp: new TokenType("regexp", startsExpr),
16133 string: new TokenType("string", startsExpr),
16134 name: new TokenType("name", startsExpr),
16135 privateId: new TokenType("privateId", startsExpr),
16136 eof: new TokenType("eof"),
16137
16138 // Punctuation token types.
16139 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
16140 bracketR: new TokenType("]"),
16141 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
16142 braceR: new TokenType("}"),
16143 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
16144 parenR: new TokenType(")"),
16145 comma: new TokenType(",", beforeExpr),
16146 semi: new TokenType(";", beforeExpr),
16147 colon: new TokenType(":", beforeExpr),
16148 dot: new TokenType("."),
16149 question: new TokenType("?", beforeExpr),
16150 questionDot: new TokenType("?."),
16151 arrow: new TokenType("=>", beforeExpr),
16152 template: new TokenType("template"),
16153 invalidTemplate: new TokenType("invalidTemplate"),
16154 ellipsis: new TokenType("...", beforeExpr),
16155 backQuote: new TokenType("`", startsExpr),
16156 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
16157
16158 // Operators. These carry several kinds of properties to help the
16159 // parser use them properly (the presence of these properties is
16160 // what categorizes them as operators).
16161 //
16162 // `binop`, when present, specifies that this operator is a binary
16163 // operator, and will refer to its precedence.
16164 //
16165 // `prefix` and `postfix` mark the operator as a prefix or postfix
16166 // unary operator.
16167 //
16168 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
16169 // binary operators with a very low precedence, that should result
16170 // in AssignmentExpression nodes.
16171
16172 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
16173 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
16174 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
16175 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
16176 logicalOR: binop("||", 1),
16177 logicalAND: binop("&&", 2),
16178 bitwiseOR: binop("|", 3),
16179 bitwiseXOR: binop("^", 4),
16180 bitwiseAND: binop("&", 5),
16181 equality: binop("==/!=/===/!==", 6),
16182 relational: binop("</>/<=/>=", 7),
16183 bitShift: binop("<</>>/>>>", 8),
16184 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
16185 modulo: binop("%", 10),
16186 star: binop("*", 10),
16187 slash: binop("/", 10),
16188 starstar: new TokenType("**", {beforeExpr: true}),
16189 coalesce: binop("??", 1),
16190
16191 // Keyword token types.
16192 _break: kw("break"),
16193 _case: kw("case", beforeExpr),
16194 _catch: kw("catch"),
16195 _continue: kw("continue"),
16196 _debugger: kw("debugger"),
16197 _default: kw("default", beforeExpr),
16198 _do: kw("do", {isLoop: true, beforeExpr: true}),
16199 _else: kw("else", beforeExpr),
16200 _finally: kw("finally"),
16201 _for: kw("for", {isLoop: true}),
16202 _function: kw("function", startsExpr),
16203 _if: kw("if"),
16204 _return: kw("return", beforeExpr),
16205 _switch: kw("switch"),
16206 _throw: kw("throw", beforeExpr),
16207 _try: kw("try"),
16208 _var: kw("var"),
16209 _const: kw("const"),
16210 _while: kw("while", {isLoop: true}),
16211 _with: kw("with"),
16212 _new: kw("new", {beforeExpr: true, startsExpr: true}),
16213 _this: kw("this", startsExpr),
16214 _super: kw("super", startsExpr),
16215 _class: kw("class", startsExpr),
16216 _extends: kw("extends", beforeExpr),
16217 _export: kw("export"),
16218 _import: kw("import", startsExpr),
16219 _null: kw("null", startsExpr),
16220 _true: kw("true", startsExpr),
16221 _false: kw("false", startsExpr),
16222 _in: kw("in", {beforeExpr: true, binop: 7}),
16223 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
16224 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
16225 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
16226 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
16227};
16228
16229// Matches a whole line break (where CRLF is considered a single
16230// line break). Used to count lines.
16231
16232var lineBreak = /\r\n?|\n|\u2028|\u2029/;
16233var lineBreakG = new RegExp(lineBreak.source, "g");
16234
16235function isNewLine(code) {
16236 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
16237}
16238
16239function nextLineBreak(code, from, end) {
16240 if ( end === void 0 ) end = code.length;
16241
16242 for (var i = from; i < end; i++) {
16243 var next = code.charCodeAt(i);
16244 if (isNewLine(next))
16245 { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
16246 }
16247 return -1
16248}
16249
16250var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
16251
16252var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
16253
16254var ref = Object.prototype;
16255var hasOwnProperty = ref.hasOwnProperty;
16256var toString = ref.toString;
16257
16258var hasOwn = Object.hasOwn || (function (obj, propName) { return (
16259 hasOwnProperty.call(obj, propName)
16260); });
16261
16262var isArray = Array.isArray || (function (obj) { return (
16263 toString.call(obj) === "[object Array]"
16264); });
16265
16266function wordsRegexp(words) {
16267 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
16268}
16269
16270function codePointToString(code) {
16271 // UTF-16 Decoding
16272 if (code <= 0xFFFF) { return String.fromCharCode(code) }
16273 code -= 0x10000;
16274 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
16275}
16276
16277var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
16278
16279// These are used when `options.locations` is on, for the
16280// `startLoc` and `endLoc` properties.
16281
16282var Position = function Position(line, col) {
16283 this.line = line;
16284 this.column = col;
16285};
16286
16287Position.prototype.offset = function offset (n) {
16288 return new Position(this.line, this.column + n)
16289};
16290
16291var SourceLocation = function SourceLocation(p, start, end) {
16292 this.start = start;
16293 this.end = end;
16294 if (p.sourceFile !== null) { this.source = p.sourceFile; }
16295};
16296
16297// The `getLineInfo` function is mostly useful when the
16298// `locations` option is off (for performance reasons) and you
16299// want to find the line/column position for a given character
16300// offset. `input` should be the code string that the offset refers
16301// into.
16302
16303function getLineInfo(input, offset) {
16304 for (var line = 1, cur = 0;;) {
16305 var nextBreak = nextLineBreak(input, cur, offset);
16306 if (nextBreak < 0) { return new Position(line, offset - cur) }
16307 ++line;
16308 cur = nextBreak;
16309 }
16310}
16311
16312// A second argument must be given to configure the parser process.
16313// These options are recognized (only `ecmaVersion` is required):
16314
16315var defaultOptions = {
16316 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
16317 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
16318 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
16319 // latest version the library supports). This influences support
16320 // for strict mode, the set of reserved words, and support for
16321 // new syntax features.
16322 ecmaVersion: null,
16323 // `sourceType` indicates the mode the code should be parsed in.
16324 // Can be either `"script"` or `"module"`. This influences global
16325 // strict mode and parsing of `import` and `export` declarations.
16326 sourceType: "script",
16327 // `onInsertedSemicolon` can be a callback that will be called
16328 // when a semicolon is automatically inserted. It will be passed
16329 // the position of the comma as an offset, and if `locations` is
16330 // enabled, it is given the location as a `{line, column}` object
16331 // as second argument.
16332 onInsertedSemicolon: null,
16333 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
16334 // trailing commas.
16335 onTrailingComma: null,
16336 // By default, reserved words are only enforced if ecmaVersion >= 5.
16337 // Set `allowReserved` to a boolean value to explicitly turn this on
16338 // an off. When this option has the value "never", reserved words
16339 // and keywords can also not be used as property names.
16340 allowReserved: null,
16341 // When enabled, a return at the top level is not considered an
16342 // error.
16343 allowReturnOutsideFunction: false,
16344 // When enabled, import/export statements are not constrained to
16345 // appearing at the top of the program, and an import.meta expression
16346 // in a script isn't considered an error.
16347 allowImportExportEverywhere: false,
16348 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
16349 // When enabled, await identifiers are allowed to appear at the top-level scope,
16350 // but they are still not allowed in non-async functions.
16351 allowAwaitOutsideFunction: null,
16352 // When enabled, super identifiers are not constrained to
16353 // appearing in methods and do not raise an error when they appear elsewhere.
16354 allowSuperOutsideMethod: null,
16355 // When enabled, hashbang directive in the beginning of file
16356 // is allowed and treated as a line comment.
16357 allowHashBang: false,
16358 // When `locations` is on, `loc` properties holding objects with
16359 // `start` and `end` properties in `{line, column}` form (with
16360 // line being 1-based and column 0-based) will be attached to the
16361 // nodes.
16362 locations: false,
16363 // A function can be passed as `onToken` option, which will
16364 // cause Acorn to call that function with object in the same
16365 // format as tokens returned from `tokenizer().getToken()`. Note
16366 // that you are not allowed to call the parser from the
16367 // callback—that will corrupt its internal state.
16368 onToken: null,
16369 // A function can be passed as `onComment` option, which will
16370 // cause Acorn to call that function with `(block, text, start,
16371 // end)` parameters whenever a comment is skipped. `block` is a
16372 // boolean indicating whether this is a block (`/* */`) comment,
16373 // `text` is the content of the comment, and `start` and `end` are
16374 // character offsets that denote the start and end of the comment.
16375 // When the `locations` option is on, two more parameters are
16376 // passed, the full `{line, column}` locations of the start and
16377 // end of the comments. Note that you are not allowed to call the
16378 // parser from the callback—that will corrupt its internal state.
16379 onComment: null,
16380 // Nodes have their start and end characters offsets recorded in
16381 // `start` and `end` properties (directly on the node, rather than
16382 // the `loc` object, which holds line/column data. To also add a
16383 // [semi-standardized][range] `range` property holding a `[start,
16384 // end]` array with the same numbers, set the `ranges` option to
16385 // `true`.
16386 //
16387 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
16388 ranges: false,
16389 // It is possible to parse multiple files into a single AST by
16390 // passing the tree produced by parsing the first file as
16391 // `program` option in subsequent parses. This will add the
16392 // toplevel forms of the parsed file to the `Program` (top) node
16393 // of an existing parse tree.
16394 program: null,
16395 // When `locations` is on, you can pass this to record the source
16396 // file in every node's `loc` object.
16397 sourceFile: null,
16398 // This value, if given, is stored in every node, whether
16399 // `locations` is on or off.
16400 directSourceFile: null,
16401 // When enabled, parenthesized expressions are represented by
16402 // (non-standard) ParenthesizedExpression nodes
16403 preserveParens: false
16404};
16405
16406// Interpret and default an options object
16407
16408var warnedAboutEcmaVersion = false;
16409
16410function getOptions(opts) {
16411 var options = {};
16412
16413 for (var opt in defaultOptions)
16414 { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
16415
16416 if (options.ecmaVersion === "latest") {
16417 options.ecmaVersion = 1e8;
16418 } else if (options.ecmaVersion == null) {
16419 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
16420 warnedAboutEcmaVersion = true;
16421 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
16422 }
16423 options.ecmaVersion = 11;
16424 } else if (options.ecmaVersion >= 2015) {
16425 options.ecmaVersion -= 2009;
16426 }
16427
16428 if (options.allowReserved == null)
16429 { options.allowReserved = options.ecmaVersion < 5; }
16430
16431 if (isArray(options.onToken)) {
16432 var tokens = options.onToken;
16433 options.onToken = function (token) { return tokens.push(token); };
16434 }
16435 if (isArray(options.onComment))
16436 { options.onComment = pushComment(options, options.onComment); }
16437
16438 return options
16439}
16440
16441function pushComment(options, array) {
16442 return function(block, text, start, end, startLoc, endLoc) {
16443 var comment = {
16444 type: block ? "Block" : "Line",
16445 value: text,
16446 start: start,
16447 end: end
16448 };
16449 if (options.locations)
16450 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
16451 if (options.ranges)
16452 { comment.range = [start, end]; }
16453 array.push(comment);
16454 }
16455}
16456
16457// Each scope gets a bitset that may contain these flags
16458var
16459 SCOPE_TOP = 1,
16460 SCOPE_FUNCTION = 2,
16461 SCOPE_ASYNC = 4,
16462 SCOPE_GENERATOR = 8,
16463 SCOPE_ARROW = 16,
16464 SCOPE_SIMPLE_CATCH = 32,
16465 SCOPE_SUPER = 64,
16466 SCOPE_DIRECT_SUPER = 128,
16467 SCOPE_CLASS_STATIC_BLOCK = 256,
16468 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
16469
16470function functionFlags(async, generator) {
16471 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
16472}
16473
16474// Used in checkLVal* and declareName to determine the type of a binding
16475var
16476 BIND_NONE = 0, // Not a binding
16477 BIND_VAR = 1, // Var-style binding
16478 BIND_LEXICAL = 2, // Let- or const-style binding
16479 BIND_FUNCTION = 3, // Function declaration
16480 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
16481 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
16482
16483var Parser = function Parser(options, input, startPos) {
16484 this.options = options = getOptions(options);
16485 this.sourceFile = options.sourceFile;
16486 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
16487 var reserved = "";
16488 if (options.allowReserved !== true) {
16489 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
16490 if (options.sourceType === "module") { reserved += " await"; }
16491 }
16492 this.reservedWords = wordsRegexp(reserved);
16493 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
16494 this.reservedWordsStrict = wordsRegexp(reservedStrict);
16495 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
16496 this.input = String(input);
16497
16498 // Used to signal to callers of `readWord1` whether the word
16499 // contained any escape sequences. This is needed because words with
16500 // escape sequences must not be interpreted as keywords.
16501 this.containsEsc = false;
16502
16503 // Set up token state
16504
16505 // The current position of the tokenizer in the input.
16506 if (startPos) {
16507 this.pos = startPos;
16508 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
16509 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
16510 } else {
16511 this.pos = this.lineStart = 0;
16512 this.curLine = 1;
16513 }
16514
16515 // Properties of the current token:
16516 // Its type
16517 this.type = types$1.eof;
16518 // For tokens that include more information than their type, the value
16519 this.value = null;
16520 // Its start and end offset
16521 this.start = this.end = this.pos;
16522 // And, if locations are used, the {line, column} object
16523 // corresponding to those offsets
16524 this.startLoc = this.endLoc = this.curPosition();
16525
16526 // Position information for the previous token
16527 this.lastTokEndLoc = this.lastTokStartLoc = null;
16528 this.lastTokStart = this.lastTokEnd = this.pos;
16529
16530 // The context stack is used to superficially track syntactic
16531 // context to predict whether a regular expression is allowed in a
16532 // given position.
16533 this.context = this.initialContext();
16534 this.exprAllowed = true;
16535
16536 // Figure out if it's a module code.
16537 this.inModule = options.sourceType === "module";
16538 this.strict = this.inModule || this.strictDirective(this.pos);
16539
16540 // Used to signify the start of a potential arrow function
16541 this.potentialArrowAt = -1;
16542 this.potentialArrowInForAwait = false;
16543
16544 // Positions to delayed-check that yield/await does not exist in default parameters.
16545 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
16546 // Labels in scope.
16547 this.labels = [];
16548 // Thus-far undefined exports.
16549 this.undefinedExports = Object.create(null);
16550
16551 // If enabled, skip leading hashbang line.
16552 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
16553 { this.skipLineComment(2); }
16554
16555 // Scope tracking for duplicate variable names (see scope.js)
16556 this.scopeStack = [];
16557 this.enterScope(SCOPE_TOP);
16558
16559 // For RegExp validation
16560 this.regexpState = null;
16561
16562 // The stack of private names.
16563 // Each element has two properties: 'declared' and 'used'.
16564 // When it exited from the outermost class definition, all used private names must be declared.
16565 this.privateNameStack = [];
16566};
16567
16568var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
16569
16570Parser.prototype.parse = function parse () {
16571 var node = this.options.program || this.startNode();
16572 this.nextToken();
16573 return this.parseTopLevel(node)
16574};
16575
16576prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
16577
16578prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
16579
16580prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
16581
16582prototypeAccessors.canAwait.get = function () {
16583 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
16584 var scope = this.scopeStack[i];
16585 if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
16586 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
16587 }
16588 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
16589};
16590
16591prototypeAccessors.allowSuper.get = function () {
16592 var ref = this.currentThisScope();
16593 var flags = ref.flags;
16594 var inClassFieldInit = ref.inClassFieldInit;
16595 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
16596};
16597
16598prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
16599
16600prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
16601
16602prototypeAccessors.allowNewDotTarget.get = function () {
16603 var ref = this.currentThisScope();
16604 var flags = ref.flags;
16605 var inClassFieldInit = ref.inClassFieldInit;
16606 return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
16607};
16608
16609prototypeAccessors.inClassStaticBlock.get = function () {
16610 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
16611};
16612
16613Parser.extend = function extend () {
16614 var plugins = [], len = arguments.length;
16615 while ( len-- ) plugins[ len ] = arguments[ len ];
16616
16617 var cls = this;
16618 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
16619 return cls
16620};
16621
16622Parser.parse = function parse (input, options) {
16623 return new this(options, input).parse()
16624};
16625
16626Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
16627 var parser = new this(options, input, pos);
16628 parser.nextToken();
16629 return parser.parseExpression()
16630};
16631
16632Parser.tokenizer = function tokenizer (input, options) {
16633 return new this(options, input)
16634};
16635
16636Object.defineProperties( Parser.prototype, prototypeAccessors );
16637
16638var pp$9 = Parser.prototype;
16639
16640// ## Parser utilities
16641
16642var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
16643pp$9.strictDirective = function(start) {
16644 if (this.options.ecmaVersion < 5) { return false }
16645 for (;;) {
16646 // Try to find string literal.
16647 skipWhiteSpace.lastIndex = start;
16648 start += skipWhiteSpace.exec(this.input)[0].length;
16649 var match = literal.exec(this.input.slice(start));
16650 if (!match) { return false }
16651 if ((match[1] || match[2]) === "use strict") {
16652 skipWhiteSpace.lastIndex = start + match[0].length;
16653 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
16654 var next = this.input.charAt(end);
16655 return next === ";" || next === "}" ||
16656 (lineBreak.test(spaceAfter[0]) &&
16657 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
16658 }
16659 start += match[0].length;
16660
16661 // Skip semicolon, if any.
16662 skipWhiteSpace.lastIndex = start;
16663 start += skipWhiteSpace.exec(this.input)[0].length;
16664 if (this.input[start] === ";")
16665 { start++; }
16666 }
16667};
16668
16669// Predicate that tests whether the next token is of the given
16670// type, and if yes, consumes it as a side effect.
16671
16672pp$9.eat = function(type) {
16673 if (this.type === type) {
16674 this.next();
16675 return true
16676 } else {
16677 return false
16678 }
16679};
16680
16681// Tests whether parsed token is a contextual keyword.
16682
16683pp$9.isContextual = function(name) {
16684 return this.type === types$1.name && this.value === name && !this.containsEsc
16685};
16686
16687// Consumes contextual keyword if possible.
16688
16689pp$9.eatContextual = function(name) {
16690 if (!this.isContextual(name)) { return false }
16691 this.next();
16692 return true
16693};
16694
16695// Asserts that following token is given contextual keyword.
16696
16697pp$9.expectContextual = function(name) {
16698 if (!this.eatContextual(name)) { this.unexpected(); }
16699};
16700
16701// Test whether a semicolon can be inserted at the current position.
16702
16703pp$9.canInsertSemicolon = function() {
16704 return this.type === types$1.eof ||
16705 this.type === types$1.braceR ||
16706 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
16707};
16708
16709pp$9.insertSemicolon = function() {
16710 if (this.canInsertSemicolon()) {
16711 if (this.options.onInsertedSemicolon)
16712 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
16713 return true
16714 }
16715};
16716
16717// Consume a semicolon, or, failing that, see if we are allowed to
16718// pretend that there is a semicolon at this position.
16719
16720pp$9.semicolon = function() {
16721 if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
16722};
16723
16724pp$9.afterTrailingComma = function(tokType, notNext) {
16725 if (this.type === tokType) {
16726 if (this.options.onTrailingComma)
16727 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
16728 if (!notNext)
16729 { this.next(); }
16730 return true
16731 }
16732};
16733
16734// Expect a token of a given type. If found, consume it, otherwise,
16735// raise an unexpected token error.
16736
16737pp$9.expect = function(type) {
16738 this.eat(type) || this.unexpected();
16739};
16740
16741// Raise an unexpected token error.
16742
16743pp$9.unexpected = function(pos) {
16744 this.raise(pos != null ? pos : this.start, "Unexpected token");
16745};
16746
16747var DestructuringErrors = function DestructuringErrors() {
16748 this.shorthandAssign =
16749 this.trailingComma =
16750 this.parenthesizedAssign =
16751 this.parenthesizedBind =
16752 this.doubleProto =
16753 -1;
16754};
16755
16756pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
16757 if (!refDestructuringErrors) { return }
16758 if (refDestructuringErrors.trailingComma > -1)
16759 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
16760 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
16761 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
16762};
16763
16764pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
16765 if (!refDestructuringErrors) { return false }
16766 var shorthandAssign = refDestructuringErrors.shorthandAssign;
16767 var doubleProto = refDestructuringErrors.doubleProto;
16768 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
16769 if (shorthandAssign >= 0)
16770 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
16771 if (doubleProto >= 0)
16772 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
16773};
16774
16775pp$9.checkYieldAwaitInDefaultParams = function() {
16776 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
16777 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
16778 if (this.awaitPos)
16779 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
16780};
16781
16782pp$9.isSimpleAssignTarget = function(expr) {
16783 if (expr.type === "ParenthesizedExpression")
16784 { return this.isSimpleAssignTarget(expr.expression) }
16785 return expr.type === "Identifier" || expr.type === "MemberExpression"
16786};
16787
16788var pp$8 = Parser.prototype;
16789
16790// ### Statement parsing
16791
16792// Parse a program. Initializes the parser, reads any number of
16793// statements, and wraps them in a Program node. Optionally takes a
16794// `program` argument. If present, the statements will be appended
16795// to its body instead of creating a new node.
16796
16797pp$8.parseTopLevel = function(node) {
16798 var exports = Object.create(null);
16799 if (!node.body) { node.body = []; }
16800 while (this.type !== types$1.eof) {
16801 var stmt = this.parseStatement(null, true, exports);
16802 node.body.push(stmt);
16803 }
16804 if (this.inModule)
16805 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
16806 {
16807 var name = list[i];
16808
16809 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
16810 } }
16811 this.adaptDirectivePrologue(node.body);
16812 this.next();
16813 node.sourceType = this.options.sourceType;
16814 return this.finishNode(node, "Program")
16815};
16816
16817var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
16818
16819pp$8.isLet = function(context) {
16820 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
16821 skipWhiteSpace.lastIndex = this.pos;
16822 var skip = skipWhiteSpace.exec(this.input);
16823 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
16824 // For ambiguous cases, determine if a LexicalDeclaration (or only a
16825 // Statement) is allowed here. If context is not empty then only a Statement
16826 // is allowed. However, `let [` is an explicit negative lookahead for
16827 // ExpressionStatement, so special-case it first.
16828 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
16829 if (context) { return false }
16830
16831 if (nextCh === 123) { return true } // '{'
16832 if (isIdentifierStart(nextCh, true)) {
16833 var pos = next + 1;
16834 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
16835 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
16836 var ident = this.input.slice(next, pos);
16837 if (!keywordRelationalOperator.test(ident)) { return true }
16838 }
16839 return false
16840};
16841
16842// check 'async [no LineTerminator here] function'
16843// - 'async /*foo*/ function' is OK.
16844// - 'async /*\n*/ function' is invalid.
16845pp$8.isAsyncFunction = function() {
16846 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
16847 { return false }
16848
16849 skipWhiteSpace.lastIndex = this.pos;
16850 var skip = skipWhiteSpace.exec(this.input);
16851 var next = this.pos + skip[0].length, after;
16852 return !lineBreak.test(this.input.slice(this.pos, next)) &&
16853 this.input.slice(next, next + 8) === "function" &&
16854 (next + 8 === this.input.length ||
16855 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
16856};
16857
16858// Parse a single statement.
16859//
16860// If expecting a statement and finding a slash operator, parse a
16861// regular expression literal. This is to handle cases like
16862// `if (foo) /blah/.exec(foo)`, where looking at the previous token
16863// does not help.
16864
16865pp$8.parseStatement = function(context, topLevel, exports) {
16866 var starttype = this.type, node = this.startNode(), kind;
16867
16868 if (this.isLet(context)) {
16869 starttype = types$1._var;
16870 kind = "let";
16871 }
16872
16873 // Most types of statements are recognized by the keyword they
16874 // start with. Many are trivial to parse, some require a bit of
16875 // complexity.
16876
16877 switch (starttype) {
16878 case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
16879 case types$1._debugger: return this.parseDebuggerStatement(node)
16880 case types$1._do: return this.parseDoStatement(node)
16881 case types$1._for: return this.parseForStatement(node)
16882 case types$1._function:
16883 // Function as sole body of either an if statement or a labeled statement
16884 // works, but not when it is part of a labeled statement that is the sole
16885 // body of an if statement.
16886 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
16887 return this.parseFunctionStatement(node, false, !context)
16888 case types$1._class:
16889 if (context) { this.unexpected(); }
16890 return this.parseClass(node, true)
16891 case types$1._if: return this.parseIfStatement(node)
16892 case types$1._return: return this.parseReturnStatement(node)
16893 case types$1._switch: return this.parseSwitchStatement(node)
16894 case types$1._throw: return this.parseThrowStatement(node)
16895 case types$1._try: return this.parseTryStatement(node)
16896 case types$1._const: case types$1._var:
16897 kind = kind || this.value;
16898 if (context && kind !== "var") { this.unexpected(); }
16899 return this.parseVarStatement(node, kind)
16900 case types$1._while: return this.parseWhileStatement(node)
16901 case types$1._with: return this.parseWithStatement(node)
16902 case types$1.braceL: return this.parseBlock(true, node)
16903 case types$1.semi: return this.parseEmptyStatement(node)
16904 case types$1._export:
16905 case types$1._import:
16906 if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
16907 skipWhiteSpace.lastIndex = this.pos;
16908 var skip = skipWhiteSpace.exec(this.input);
16909 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
16910 if (nextCh === 40 || nextCh === 46) // '(' or '.'
16911 { return this.parseExpressionStatement(node, this.parseExpression()) }
16912 }
16913
16914 if (!this.options.allowImportExportEverywhere) {
16915 if (!topLevel)
16916 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
16917 if (!this.inModule)
16918 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
16919 }
16920 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
16921
16922 // If the statement does not start with a statement keyword or a
16923 // brace, it's an ExpressionStatement or LabeledStatement. We
16924 // simply start parsing an expression, and afterwards, if the
16925 // next token is a colon and the expression was a simple
16926 // Identifier node, we switch to interpreting it as a label.
16927 default:
16928 if (this.isAsyncFunction()) {
16929 if (context) { this.unexpected(); }
16930 this.next();
16931 return this.parseFunctionStatement(node, true, !context)
16932 }
16933
16934 var maybeName = this.value, expr = this.parseExpression();
16935 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
16936 { return this.parseLabeledStatement(node, maybeName, expr, context) }
16937 else { return this.parseExpressionStatement(node, expr) }
16938 }
16939};
16940
16941pp$8.parseBreakContinueStatement = function(node, keyword) {
16942 var isBreak = keyword === "break";
16943 this.next();
16944 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
16945 else if (this.type !== types$1.name) { this.unexpected(); }
16946 else {
16947 node.label = this.parseIdent();
16948 this.semicolon();
16949 }
16950
16951 // Verify that there is an actual destination to break or
16952 // continue to.
16953 var i = 0;
16954 for (; i < this.labels.length; ++i) {
16955 var lab = this.labels[i];
16956 if (node.label == null || lab.name === node.label.name) {
16957 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
16958 if (node.label && isBreak) { break }
16959 }
16960 }
16961 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
16962 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
16963};
16964
16965pp$8.parseDebuggerStatement = function(node) {
16966 this.next();
16967 this.semicolon();
16968 return this.finishNode(node, "DebuggerStatement")
16969};
16970
16971pp$8.parseDoStatement = function(node) {
16972 this.next();
16973 this.labels.push(loopLabel);
16974 node.body = this.parseStatement("do");
16975 this.labels.pop();
16976 this.expect(types$1._while);
16977 node.test = this.parseParenExpression();
16978 if (this.options.ecmaVersion >= 6)
16979 { this.eat(types$1.semi); }
16980 else
16981 { this.semicolon(); }
16982 return this.finishNode(node, "DoWhileStatement")
16983};
16984
16985// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
16986// loop is non-trivial. Basically, we have to parse the init `var`
16987// statement or expression, disallowing the `in` operator (see
16988// the second parameter to `parseExpression`), and then check
16989// whether the next token is `in` or `of`. When there is no init
16990// part (semicolon immediately after the opening parenthesis), it
16991// is a regular `for` loop.
16992
16993pp$8.parseForStatement = function(node) {
16994 this.next();
16995 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
16996 this.labels.push(loopLabel);
16997 this.enterScope(0);
16998 this.expect(types$1.parenL);
16999 if (this.type === types$1.semi) {
17000 if (awaitAt > -1) { this.unexpected(awaitAt); }
17001 return this.parseFor(node, null)
17002 }
17003 var isLet = this.isLet();
17004 if (this.type === types$1._var || this.type === types$1._const || isLet) {
17005 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
17006 this.next();
17007 this.parseVar(init$1, true, kind);
17008 this.finishNode(init$1, "VariableDeclaration");
17009 if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
17010 if (this.options.ecmaVersion >= 9) {
17011 if (this.type === types$1._in) {
17012 if (awaitAt > -1) { this.unexpected(awaitAt); }
17013 } else { node.await = awaitAt > -1; }
17014 }
17015 return this.parseForIn(node, init$1)
17016 }
17017 if (awaitAt > -1) { this.unexpected(awaitAt); }
17018 return this.parseFor(node, init$1)
17019 }
17020 var startsWithLet = this.isContextual("let"), isForOf = false;
17021 var refDestructuringErrors = new DestructuringErrors;
17022 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
17023 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
17024 if (this.options.ecmaVersion >= 9) {
17025 if (this.type === types$1._in) {
17026 if (awaitAt > -1) { this.unexpected(awaitAt); }
17027 } else { node.await = awaitAt > -1; }
17028 }
17029 if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
17030 this.toAssignable(init, false, refDestructuringErrors);
17031 this.checkLValPattern(init);
17032 return this.parseForIn(node, init)
17033 } else {
17034 this.checkExpressionErrors(refDestructuringErrors, true);
17035 }
17036 if (awaitAt > -1) { this.unexpected(awaitAt); }
17037 return this.parseFor(node, init)
17038};
17039
17040pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
17041 this.next();
17042 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
17043};
17044
17045pp$8.parseIfStatement = function(node) {
17046 this.next();
17047 node.test = this.parseParenExpression();
17048 // allow function declarations in branches, but only in non-strict mode
17049 node.consequent = this.parseStatement("if");
17050 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
17051 return this.finishNode(node, "IfStatement")
17052};
17053
17054pp$8.parseReturnStatement = function(node) {
17055 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
17056 { this.raise(this.start, "'return' outside of function"); }
17057 this.next();
17058
17059 // In `return` (and `break`/`continue`), the keywords with
17060 // optional arguments, we eagerly look for a semicolon or the
17061 // possibility to insert one.
17062
17063 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
17064 else { node.argument = this.parseExpression(); this.semicolon(); }
17065 return this.finishNode(node, "ReturnStatement")
17066};
17067
17068pp$8.parseSwitchStatement = function(node) {
17069 this.next();
17070 node.discriminant = this.parseParenExpression();
17071 node.cases = [];
17072 this.expect(types$1.braceL);
17073 this.labels.push(switchLabel);
17074 this.enterScope(0);
17075
17076 // Statements under must be grouped (by label) in SwitchCase
17077 // nodes. `cur` is used to keep the node that we are currently
17078 // adding statements to.
17079
17080 var cur;
17081 for (var sawDefault = false; this.type !== types$1.braceR;) {
17082 if (this.type === types$1._case || this.type === types$1._default) {
17083 var isCase = this.type === types$1._case;
17084 if (cur) { this.finishNode(cur, "SwitchCase"); }
17085 node.cases.push(cur = this.startNode());
17086 cur.consequent = [];
17087 this.next();
17088 if (isCase) {
17089 cur.test = this.parseExpression();
17090 } else {
17091 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
17092 sawDefault = true;
17093 cur.test = null;
17094 }
17095 this.expect(types$1.colon);
17096 } else {
17097 if (!cur) { this.unexpected(); }
17098 cur.consequent.push(this.parseStatement(null));
17099 }
17100 }
17101 this.exitScope();
17102 if (cur) { this.finishNode(cur, "SwitchCase"); }
17103 this.next(); // Closing brace
17104 this.labels.pop();
17105 return this.finishNode(node, "SwitchStatement")
17106};
17107
17108pp$8.parseThrowStatement = function(node) {
17109 this.next();
17110 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
17111 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
17112 node.argument = this.parseExpression();
17113 this.semicolon();
17114 return this.finishNode(node, "ThrowStatement")
17115};
17116
17117// Reused empty array added for node fields that are always empty.
17118
17119var empty$1 = [];
17120
17121pp$8.parseTryStatement = function(node) {
17122 this.next();
17123 node.block = this.parseBlock();
17124 node.handler = null;
17125 if (this.type === types$1._catch) {
17126 var clause = this.startNode();
17127 this.next();
17128 if (this.eat(types$1.parenL)) {
17129 clause.param = this.parseBindingAtom();
17130 var simple = clause.param.type === "Identifier";
17131 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
17132 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
17133 this.expect(types$1.parenR);
17134 } else {
17135 if (this.options.ecmaVersion < 10) { this.unexpected(); }
17136 clause.param = null;
17137 this.enterScope(0);
17138 }
17139 clause.body = this.parseBlock(false);
17140 this.exitScope();
17141 node.handler = this.finishNode(clause, "CatchClause");
17142 }
17143 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
17144 if (!node.handler && !node.finalizer)
17145 { this.raise(node.start, "Missing catch or finally clause"); }
17146 return this.finishNode(node, "TryStatement")
17147};
17148
17149pp$8.parseVarStatement = function(node, kind) {
17150 this.next();
17151 this.parseVar(node, false, kind);
17152 this.semicolon();
17153 return this.finishNode(node, "VariableDeclaration")
17154};
17155
17156pp$8.parseWhileStatement = function(node) {
17157 this.next();
17158 node.test = this.parseParenExpression();
17159 this.labels.push(loopLabel);
17160 node.body = this.parseStatement("while");
17161 this.labels.pop();
17162 return this.finishNode(node, "WhileStatement")
17163};
17164
17165pp$8.parseWithStatement = function(node) {
17166 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
17167 this.next();
17168 node.object = this.parseParenExpression();
17169 node.body = this.parseStatement("with");
17170 return this.finishNode(node, "WithStatement")
17171};
17172
17173pp$8.parseEmptyStatement = function(node) {
17174 this.next();
17175 return this.finishNode(node, "EmptyStatement")
17176};
17177
17178pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
17179 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
17180 {
17181 var label = list[i$1];
17182
17183 if (label.name === maybeName)
17184 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
17185 } }
17186 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
17187 for (var i = this.labels.length - 1; i >= 0; i--) {
17188 var label$1 = this.labels[i];
17189 if (label$1.statementStart === node.start) {
17190 // Update information about previous labels on this node
17191 label$1.statementStart = this.start;
17192 label$1.kind = kind;
17193 } else { break }
17194 }
17195 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
17196 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
17197 this.labels.pop();
17198 node.label = expr;
17199 return this.finishNode(node, "LabeledStatement")
17200};
17201
17202pp$8.parseExpressionStatement = function(node, expr) {
17203 node.expression = expr;
17204 this.semicolon();
17205 return this.finishNode(node, "ExpressionStatement")
17206};
17207
17208// Parse a semicolon-enclosed block of statements, handling `"use
17209// strict"` declarations when `allowStrict` is true (used for
17210// function bodies).
17211
17212pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
17213 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
17214 if ( node === void 0 ) node = this.startNode();
17215
17216 node.body = [];
17217 this.expect(types$1.braceL);
17218 if (createNewLexicalScope) { this.enterScope(0); }
17219 while (this.type !== types$1.braceR) {
17220 var stmt = this.parseStatement(null);
17221 node.body.push(stmt);
17222 }
17223 if (exitStrict) { this.strict = false; }
17224 this.next();
17225 if (createNewLexicalScope) { this.exitScope(); }
17226 return this.finishNode(node, "BlockStatement")
17227};
17228
17229// Parse a regular `for` loop. The disambiguation code in
17230// `parseStatement` will already have parsed the init statement or
17231// expression.
17232
17233pp$8.parseFor = function(node, init) {
17234 node.init = init;
17235 this.expect(types$1.semi);
17236 node.test = this.type === types$1.semi ? null : this.parseExpression();
17237 this.expect(types$1.semi);
17238 node.update = this.type === types$1.parenR ? null : this.parseExpression();
17239 this.expect(types$1.parenR);
17240 node.body = this.parseStatement("for");
17241 this.exitScope();
17242 this.labels.pop();
17243 return this.finishNode(node, "ForStatement")
17244};
17245
17246// Parse a `for`/`in` and `for`/`of` loop, which are almost
17247// same from parser's perspective.
17248
17249pp$8.parseForIn = function(node, init) {
17250 var isForIn = this.type === types$1._in;
17251 this.next();
17252
17253 if (
17254 init.type === "VariableDeclaration" &&
17255 init.declarations[0].init != null &&
17256 (
17257 !isForIn ||
17258 this.options.ecmaVersion < 8 ||
17259 this.strict ||
17260 init.kind !== "var" ||
17261 init.declarations[0].id.type !== "Identifier"
17262 )
17263 ) {
17264 this.raise(
17265 init.start,
17266 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
17267 );
17268 }
17269 node.left = init;
17270 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
17271 this.expect(types$1.parenR);
17272 node.body = this.parseStatement("for");
17273 this.exitScope();
17274 this.labels.pop();
17275 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
17276};
17277
17278// Parse a list of variable declarations.
17279
17280pp$8.parseVar = function(node, isFor, kind) {
17281 node.declarations = [];
17282 node.kind = kind;
17283 for (;;) {
17284 var decl = this.startNode();
17285 this.parseVarId(decl, kind);
17286 if (this.eat(types$1.eq)) {
17287 decl.init = this.parseMaybeAssign(isFor);
17288 } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
17289 this.unexpected();
17290 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
17291 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
17292 } else {
17293 decl.init = null;
17294 }
17295 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
17296 if (!this.eat(types$1.comma)) { break }
17297 }
17298 return node
17299};
17300
17301pp$8.parseVarId = function(decl, kind) {
17302 decl.id = this.parseBindingAtom();
17303 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
17304};
17305
17306var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
17307
17308// Parse a function declaration or literal (depending on the
17309// `statement & FUNC_STATEMENT`).
17310
17311// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
17312pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
17313 this.initFunction(node);
17314 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
17315 if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
17316 { this.unexpected(); }
17317 node.generator = this.eat(types$1.star);
17318 }
17319 if (this.options.ecmaVersion >= 8)
17320 { node.async = !!isAsync; }
17321
17322 if (statement & FUNC_STATEMENT) {
17323 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
17324 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
17325 // If it is a regular function declaration in sloppy mode, then it is
17326 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
17327 // mode depends on properties of the current scope (see
17328 // treatFunctionsAsVar).
17329 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
17330 }
17331
17332 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
17333 this.yieldPos = 0;
17334 this.awaitPos = 0;
17335 this.awaitIdentPos = 0;
17336 this.enterScope(functionFlags(node.async, node.generator));
17337
17338 if (!(statement & FUNC_STATEMENT))
17339 { node.id = this.type === types$1.name ? this.parseIdent() : null; }
17340
17341 this.parseFunctionParams(node);
17342 this.parseFunctionBody(node, allowExpressionBody, false, forInit);
17343
17344 this.yieldPos = oldYieldPos;
17345 this.awaitPos = oldAwaitPos;
17346 this.awaitIdentPos = oldAwaitIdentPos;
17347 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
17348};
17349
17350pp$8.parseFunctionParams = function(node) {
17351 this.expect(types$1.parenL);
17352 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
17353 this.checkYieldAwaitInDefaultParams();
17354};
17355
17356// Parse a class declaration or literal (depending on the
17357// `isStatement` parameter).
17358
17359pp$8.parseClass = function(node, isStatement) {
17360 this.next();
17361
17362 // ecma-262 14.6 Class Definitions
17363 // A class definition is always strict mode code.
17364 var oldStrict = this.strict;
17365 this.strict = true;
17366
17367 this.parseClassId(node, isStatement);
17368 this.parseClassSuper(node);
17369 var privateNameMap = this.enterClassBody();
17370 var classBody = this.startNode();
17371 var hadConstructor = false;
17372 classBody.body = [];
17373 this.expect(types$1.braceL);
17374 while (this.type !== types$1.braceR) {
17375 var element = this.parseClassElement(node.superClass !== null);
17376 if (element) {
17377 classBody.body.push(element);
17378 if (element.type === "MethodDefinition" && element.kind === "constructor") {
17379 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
17380 hadConstructor = true;
17381 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
17382 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
17383 }
17384 }
17385 }
17386 this.strict = oldStrict;
17387 this.next();
17388 node.body = this.finishNode(classBody, "ClassBody");
17389 this.exitClassBody();
17390 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
17391};
17392
17393pp$8.parseClassElement = function(constructorAllowsSuper) {
17394 if (this.eat(types$1.semi)) { return null }
17395
17396 var ecmaVersion = this.options.ecmaVersion;
17397 var node = this.startNode();
17398 var keyName = "";
17399 var isGenerator = false;
17400 var isAsync = false;
17401 var kind = "method";
17402 var isStatic = false;
17403
17404 if (this.eatContextual("static")) {
17405 // Parse static init block
17406 if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
17407 this.parseClassStaticBlock(node);
17408 return node
17409 }
17410 if (this.isClassElementNameStart() || this.type === types$1.star) {
17411 isStatic = true;
17412 } else {
17413 keyName = "static";
17414 }
17415 }
17416 node.static = isStatic;
17417 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
17418 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
17419 isAsync = true;
17420 } else {
17421 keyName = "async";
17422 }
17423 }
17424 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
17425 isGenerator = true;
17426 }
17427 if (!keyName && !isAsync && !isGenerator) {
17428 var lastValue = this.value;
17429 if (this.eatContextual("get") || this.eatContextual("set")) {
17430 if (this.isClassElementNameStart()) {
17431 kind = lastValue;
17432 } else {
17433 keyName = lastValue;
17434 }
17435 }
17436 }
17437
17438 // Parse element name
17439 if (keyName) {
17440 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
17441 // The last token is any of those. Make it the element name.
17442 node.computed = false;
17443 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
17444 node.key.name = keyName;
17445 this.finishNode(node.key, "Identifier");
17446 } else {
17447 this.parseClassElementName(node);
17448 }
17449
17450 // Parse element value
17451 if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
17452 var isConstructor = !node.static && checkKeyName(node, "constructor");
17453 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
17454 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
17455 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
17456 node.kind = isConstructor ? "constructor" : kind;
17457 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
17458 } else {
17459 this.parseClassField(node);
17460 }
17461
17462 return node
17463};
17464
17465pp$8.isClassElementNameStart = function() {
17466 return (
17467 this.type === types$1.name ||
17468 this.type === types$1.privateId ||
17469 this.type === types$1.num ||
17470 this.type === types$1.string ||
17471 this.type === types$1.bracketL ||
17472 this.type.keyword
17473 )
17474};
17475
17476pp$8.parseClassElementName = function(element) {
17477 if (this.type === types$1.privateId) {
17478 if (this.value === "constructor") {
17479 this.raise(this.start, "Classes can't have an element named '#constructor'");
17480 }
17481 element.computed = false;
17482 element.key = this.parsePrivateIdent();
17483 } else {
17484 this.parsePropertyName(element);
17485 }
17486};
17487
17488pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
17489 // Check key and flags
17490 var key = method.key;
17491 if (method.kind === "constructor") {
17492 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
17493 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
17494 } else if (method.static && checkKeyName(method, "prototype")) {
17495 this.raise(key.start, "Classes may not have a static property named prototype");
17496 }
17497
17498 // Parse value
17499 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
17500
17501 // Check value
17502 if (method.kind === "get" && value.params.length !== 0)
17503 { this.raiseRecoverable(value.start, "getter should have no params"); }
17504 if (method.kind === "set" && value.params.length !== 1)
17505 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
17506 if (method.kind === "set" && value.params[0].type === "RestElement")
17507 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
17508
17509 return this.finishNode(method, "MethodDefinition")
17510};
17511
17512pp$8.parseClassField = function(field) {
17513 if (checkKeyName(field, "constructor")) {
17514 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
17515 } else if (field.static && checkKeyName(field, "prototype")) {
17516 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
17517 }
17518
17519 if (this.eat(types$1.eq)) {
17520 // To raise SyntaxError if 'arguments' exists in the initializer.
17521 var scope = this.currentThisScope();
17522 var inClassFieldInit = scope.inClassFieldInit;
17523 scope.inClassFieldInit = true;
17524 field.value = this.parseMaybeAssign();
17525 scope.inClassFieldInit = inClassFieldInit;
17526 } else {
17527 field.value = null;
17528 }
17529 this.semicolon();
17530
17531 return this.finishNode(field, "PropertyDefinition")
17532};
17533
17534pp$8.parseClassStaticBlock = function(node) {
17535 node.body = [];
17536
17537 var oldLabels = this.labels;
17538 this.labels = [];
17539 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
17540 while (this.type !== types$1.braceR) {
17541 var stmt = this.parseStatement(null);
17542 node.body.push(stmt);
17543 }
17544 this.next();
17545 this.exitScope();
17546 this.labels = oldLabels;
17547
17548 return this.finishNode(node, "StaticBlock")
17549};
17550
17551pp$8.parseClassId = function(node, isStatement) {
17552 if (this.type === types$1.name) {
17553 node.id = this.parseIdent();
17554 if (isStatement)
17555 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
17556 } else {
17557 if (isStatement === true)
17558 { this.unexpected(); }
17559 node.id = null;
17560 }
17561};
17562
17563pp$8.parseClassSuper = function(node) {
17564 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
17565};
17566
17567pp$8.enterClassBody = function() {
17568 var element = {declared: Object.create(null), used: []};
17569 this.privateNameStack.push(element);
17570 return element.declared
17571};
17572
17573pp$8.exitClassBody = function() {
17574 var ref = this.privateNameStack.pop();
17575 var declared = ref.declared;
17576 var used = ref.used;
17577 var len = this.privateNameStack.length;
17578 var parent = len === 0 ? null : this.privateNameStack[len - 1];
17579 for (var i = 0; i < used.length; ++i) {
17580 var id = used[i];
17581 if (!hasOwn(declared, id.name)) {
17582 if (parent) {
17583 parent.used.push(id);
17584 } else {
17585 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
17586 }
17587 }
17588 }
17589};
17590
17591function isPrivateNameConflicted(privateNameMap, element) {
17592 var name = element.key.name;
17593 var curr = privateNameMap[name];
17594
17595 var next = "true";
17596 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
17597 next = (element.static ? "s" : "i") + element.kind;
17598 }
17599
17600 // `class { get #a(){}; static set #a(_){} }` is also conflict.
17601 if (
17602 curr === "iget" && next === "iset" ||
17603 curr === "iset" && next === "iget" ||
17604 curr === "sget" && next === "sset" ||
17605 curr === "sset" && next === "sget"
17606 ) {
17607 privateNameMap[name] = "true";
17608 return false
17609 } else if (!curr) {
17610 privateNameMap[name] = next;
17611 return false
17612 } else {
17613 return true
17614 }
17615}
17616
17617function checkKeyName(node, name) {
17618 var computed = node.computed;
17619 var key = node.key;
17620 return !computed && (
17621 key.type === "Identifier" && key.name === name ||
17622 key.type === "Literal" && key.value === name
17623 )
17624}
17625
17626// Parses module export declaration.
17627
17628pp$8.parseExport = function(node, exports) {
17629 this.next();
17630 // export * from '...'
17631 if (this.eat(types$1.star)) {
17632 if (this.options.ecmaVersion >= 11) {
17633 if (this.eatContextual("as")) {
17634 node.exported = this.parseModuleExportName();
17635 this.checkExport(exports, node.exported, this.lastTokStart);
17636 } else {
17637 node.exported = null;
17638 }
17639 }
17640 this.expectContextual("from");
17641 if (this.type !== types$1.string) { this.unexpected(); }
17642 node.source = this.parseExprAtom();
17643 this.semicolon();
17644 return this.finishNode(node, "ExportAllDeclaration")
17645 }
17646 if (this.eat(types$1._default)) { // export default ...
17647 this.checkExport(exports, "default", this.lastTokStart);
17648 var isAsync;
17649 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
17650 var fNode = this.startNode();
17651 this.next();
17652 if (isAsync) { this.next(); }
17653 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
17654 } else if (this.type === types$1._class) {
17655 var cNode = this.startNode();
17656 node.declaration = this.parseClass(cNode, "nullableID");
17657 } else {
17658 node.declaration = this.parseMaybeAssign();
17659 this.semicolon();
17660 }
17661 return this.finishNode(node, "ExportDefaultDeclaration")
17662 }
17663 // export var|const|let|function|class ...
17664 if (this.shouldParseExportStatement()) {
17665 node.declaration = this.parseStatement(null);
17666 if (node.declaration.type === "VariableDeclaration")
17667 { this.checkVariableExport(exports, node.declaration.declarations); }
17668 else
17669 { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
17670 node.specifiers = [];
17671 node.source = null;
17672 } else { // export { x, y as z } [from '...']
17673 node.declaration = null;
17674 node.specifiers = this.parseExportSpecifiers(exports);
17675 if (this.eatContextual("from")) {
17676 if (this.type !== types$1.string) { this.unexpected(); }
17677 node.source = this.parseExprAtom();
17678 } else {
17679 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
17680 // check for keywords used as local names
17681 var spec = list[i];
17682
17683 this.checkUnreserved(spec.local);
17684 // check if export is defined
17685 this.checkLocalExport(spec.local);
17686
17687 if (spec.local.type === "Literal") {
17688 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
17689 }
17690 }
17691
17692 node.source = null;
17693 }
17694 this.semicolon();
17695 }
17696 return this.finishNode(node, "ExportNamedDeclaration")
17697};
17698
17699pp$8.checkExport = function(exports, name, pos) {
17700 if (!exports) { return }
17701 if (typeof name !== "string")
17702 { name = name.type === "Identifier" ? name.name : name.value; }
17703 if (hasOwn(exports, name))
17704 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
17705 exports[name] = true;
17706};
17707
17708pp$8.checkPatternExport = function(exports, pat) {
17709 var type = pat.type;
17710 if (type === "Identifier")
17711 { this.checkExport(exports, pat, pat.start); }
17712 else if (type === "ObjectPattern")
17713 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
17714 {
17715 var prop = list[i];
17716
17717 this.checkPatternExport(exports, prop);
17718 } }
17719 else if (type === "ArrayPattern")
17720 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
17721 var elt = list$1[i$1];
17722
17723 if (elt) { this.checkPatternExport(exports, elt); }
17724 } }
17725 else if (type === "Property")
17726 { this.checkPatternExport(exports, pat.value); }
17727 else if (type === "AssignmentPattern")
17728 { this.checkPatternExport(exports, pat.left); }
17729 else if (type === "RestElement")
17730 { this.checkPatternExport(exports, pat.argument); }
17731 else if (type === "ParenthesizedExpression")
17732 { this.checkPatternExport(exports, pat.expression); }
17733};
17734
17735pp$8.checkVariableExport = function(exports, decls) {
17736 if (!exports) { return }
17737 for (var i = 0, list = decls; i < list.length; i += 1)
17738 {
17739 var decl = list[i];
17740
17741 this.checkPatternExport(exports, decl.id);
17742 }
17743};
17744
17745pp$8.shouldParseExportStatement = function() {
17746 return this.type.keyword === "var" ||
17747 this.type.keyword === "const" ||
17748 this.type.keyword === "class" ||
17749 this.type.keyword === "function" ||
17750 this.isLet() ||
17751 this.isAsyncFunction()
17752};
17753
17754// Parses a comma-separated list of module exports.
17755
17756pp$8.parseExportSpecifiers = function(exports) {
17757 var nodes = [], first = true;
17758 // export { x, y as z } [from '...']
17759 this.expect(types$1.braceL);
17760 while (!this.eat(types$1.braceR)) {
17761 if (!first) {
17762 this.expect(types$1.comma);
17763 if (this.afterTrailingComma(types$1.braceR)) { break }
17764 } else { first = false; }
17765
17766 var node = this.startNode();
17767 node.local = this.parseModuleExportName();
17768 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
17769 this.checkExport(
17770 exports,
17771 node.exported,
17772 node.exported.start
17773 );
17774 nodes.push(this.finishNode(node, "ExportSpecifier"));
17775 }
17776 return nodes
17777};
17778
17779// Parses import declaration.
17780
17781pp$8.parseImport = function(node) {
17782 this.next();
17783 // import '...'
17784 if (this.type === types$1.string) {
17785 node.specifiers = empty$1;
17786 node.source = this.parseExprAtom();
17787 } else {
17788 node.specifiers = this.parseImportSpecifiers();
17789 this.expectContextual("from");
17790 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
17791 }
17792 this.semicolon();
17793 return this.finishNode(node, "ImportDeclaration")
17794};
17795
17796// Parses a comma-separated list of module imports.
17797
17798pp$8.parseImportSpecifiers = function() {
17799 var nodes = [], first = true;
17800 if (this.type === types$1.name) {
17801 // import defaultObj, { x, y as z } from '...'
17802 var node = this.startNode();
17803 node.local = this.parseIdent();
17804 this.checkLValSimple(node.local, BIND_LEXICAL);
17805 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
17806 if (!this.eat(types$1.comma)) { return nodes }
17807 }
17808 if (this.type === types$1.star) {
17809 var node$1 = this.startNode();
17810 this.next();
17811 this.expectContextual("as");
17812 node$1.local = this.parseIdent();
17813 this.checkLValSimple(node$1.local, BIND_LEXICAL);
17814 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
17815 return nodes
17816 }
17817 this.expect(types$1.braceL);
17818 while (!this.eat(types$1.braceR)) {
17819 if (!first) {
17820 this.expect(types$1.comma);
17821 if (this.afterTrailingComma(types$1.braceR)) { break }
17822 } else { first = false; }
17823
17824 var node$2 = this.startNode();
17825 node$2.imported = this.parseModuleExportName();
17826 if (this.eatContextual("as")) {
17827 node$2.local = this.parseIdent();
17828 } else {
17829 this.checkUnreserved(node$2.imported);
17830 node$2.local = node$2.imported;
17831 }
17832 this.checkLValSimple(node$2.local, BIND_LEXICAL);
17833 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
17834 }
17835 return nodes
17836};
17837
17838pp$8.parseModuleExportName = function() {
17839 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
17840 var stringLiteral = this.parseLiteral(this.value);
17841 if (loneSurrogate.test(stringLiteral.value)) {
17842 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
17843 }
17844 return stringLiteral
17845 }
17846 return this.parseIdent(true)
17847};
17848
17849// Set `ExpressionStatement#directive` property for directive prologues.
17850pp$8.adaptDirectivePrologue = function(statements) {
17851 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
17852 statements[i].directive = statements[i].expression.raw.slice(1, -1);
17853 }
17854};
17855pp$8.isDirectiveCandidate = function(statement) {
17856 return (
17857 statement.type === "ExpressionStatement" &&
17858 statement.expression.type === "Literal" &&
17859 typeof statement.expression.value === "string" &&
17860 // Reject parenthesized strings.
17861 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
17862 )
17863};
17864
17865var pp$7 = Parser.prototype;
17866
17867// Convert existing expression atom to assignable pattern
17868// if possible.
17869
17870pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
17871 if (this.options.ecmaVersion >= 6 && node) {
17872 switch (node.type) {
17873 case "Identifier":
17874 if (this.inAsync && node.name === "await")
17875 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
17876 break
17877
17878 case "ObjectPattern":
17879 case "ArrayPattern":
17880 case "AssignmentPattern":
17881 case "RestElement":
17882 break
17883
17884 case "ObjectExpression":
17885 node.type = "ObjectPattern";
17886 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
17887 for (var i = 0, list = node.properties; i < list.length; i += 1) {
17888 var prop = list[i];
17889
17890 this.toAssignable(prop, isBinding);
17891 // Early error:
17892 // AssignmentRestProperty[Yield, Await] :
17893 // `...` DestructuringAssignmentTarget[Yield, Await]
17894 //
17895 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
17896 if (
17897 prop.type === "RestElement" &&
17898 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
17899 ) {
17900 this.raise(prop.argument.start, "Unexpected token");
17901 }
17902 }
17903 break
17904
17905 case "Property":
17906 // AssignmentProperty has type === "Property"
17907 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
17908 this.toAssignable(node.value, isBinding);
17909 break
17910
17911 case "ArrayExpression":
17912 node.type = "ArrayPattern";
17913 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
17914 this.toAssignableList(node.elements, isBinding);
17915 break
17916
17917 case "SpreadElement":
17918 node.type = "RestElement";
17919 this.toAssignable(node.argument, isBinding);
17920 if (node.argument.type === "AssignmentPattern")
17921 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
17922 break
17923
17924 case "AssignmentExpression":
17925 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
17926 node.type = "AssignmentPattern";
17927 delete node.operator;
17928 this.toAssignable(node.left, isBinding);
17929 break
17930
17931 case "ParenthesizedExpression":
17932 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
17933 break
17934
17935 case "ChainExpression":
17936 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
17937 break
17938
17939 case "MemberExpression":
17940 if (!isBinding) { break }
17941
17942 default:
17943 this.raise(node.start, "Assigning to rvalue");
17944 }
17945 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
17946 return node
17947};
17948
17949// Convert list of expression atoms to binding list.
17950
17951pp$7.toAssignableList = function(exprList, isBinding) {
17952 var end = exprList.length;
17953 for (var i = 0; i < end; i++) {
17954 var elt = exprList[i];
17955 if (elt) { this.toAssignable(elt, isBinding); }
17956 }
17957 if (end) {
17958 var last = exprList[end - 1];
17959 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
17960 { this.unexpected(last.argument.start); }
17961 }
17962 return exprList
17963};
17964
17965// Parses spread element.
17966
17967pp$7.parseSpread = function(refDestructuringErrors) {
17968 var node = this.startNode();
17969 this.next();
17970 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
17971 return this.finishNode(node, "SpreadElement")
17972};
17973
17974pp$7.parseRestBinding = function() {
17975 var node = this.startNode();
17976 this.next();
17977
17978 // RestElement inside of a function parameter must be an identifier
17979 if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
17980 { this.unexpected(); }
17981
17982 node.argument = this.parseBindingAtom();
17983
17984 return this.finishNode(node, "RestElement")
17985};
17986
17987// Parses lvalue (assignable) atom.
17988
17989pp$7.parseBindingAtom = function() {
17990 if (this.options.ecmaVersion >= 6) {
17991 switch (this.type) {
17992 case types$1.bracketL:
17993 var node = this.startNode();
17994 this.next();
17995 node.elements = this.parseBindingList(types$1.bracketR, true, true);
17996 return this.finishNode(node, "ArrayPattern")
17997
17998 case types$1.braceL:
17999 return this.parseObj(true)
18000 }
18001 }
18002 return this.parseIdent()
18003};
18004
18005pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
18006 var elts = [], first = true;
18007 while (!this.eat(close)) {
18008 if (first) { first = false; }
18009 else { this.expect(types$1.comma); }
18010 if (allowEmpty && this.type === types$1.comma) {
18011 elts.push(null);
18012 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
18013 break
18014 } else if (this.type === types$1.ellipsis) {
18015 var rest = this.parseRestBinding();
18016 this.parseBindingListItem(rest);
18017 elts.push(rest);
18018 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
18019 this.expect(close);
18020 break
18021 } else {
18022 var elem = this.parseMaybeDefault(this.start, this.startLoc);
18023 this.parseBindingListItem(elem);
18024 elts.push(elem);
18025 }
18026 }
18027 return elts
18028};
18029
18030pp$7.parseBindingListItem = function(param) {
18031 return param
18032};
18033
18034// Parses assignment pattern around given atom if possible.
18035
18036pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
18037 left = left || this.parseBindingAtom();
18038 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
18039 var node = this.startNodeAt(startPos, startLoc);
18040 node.left = left;
18041 node.right = this.parseMaybeAssign();
18042 return this.finishNode(node, "AssignmentPattern")
18043};
18044
18045// The following three functions all verify that a node is an lvalue —
18046// something that can be bound, or assigned to. In order to do so, they perform
18047// a variety of checks:
18048//
18049// - Check that none of the bound/assigned-to identifiers are reserved words.
18050// - Record name declarations for bindings in the appropriate scope.
18051// - Check duplicate argument names, if checkClashes is set.
18052//
18053// If a complex binding pattern is encountered (e.g., object and array
18054// destructuring), the entire pattern is recursively checked.
18055//
18056// There are three versions of checkLVal*() appropriate for different
18057// circumstances:
18058//
18059// - checkLValSimple() shall be used if the syntactic construct supports
18060// nothing other than identifiers and member expressions. Parenthesized
18061// expressions are also correctly handled. This is generally appropriate for
18062// constructs for which the spec says
18063//
18064// > It is a Syntax Error if AssignmentTargetType of [the production] is not
18065// > simple.
18066//
18067// It is also appropriate for checking if an identifier is valid and not
18068// defined elsewhere, like import declarations or function/class identifiers.
18069//
18070// Examples where this is used include:
18071// a += …;
18072// import a from '…';
18073// where a is the node to be checked.
18074//
18075// - checkLValPattern() shall be used if the syntactic construct supports
18076// anything checkLValSimple() supports, as well as object and array
18077// destructuring patterns. This is generally appropriate for constructs for
18078// which the spec says
18079//
18080// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
18081// > an ArrayLiteral and AssignmentTargetType of [the production] is not
18082// > simple.
18083//
18084// Examples where this is used include:
18085// (a = …);
18086// const a = …;
18087// try { … } catch (a) { … }
18088// where a is the node to be checked.
18089//
18090// - checkLValInnerPattern() shall be used if the syntactic construct supports
18091// anything checkLValPattern() supports, as well as default assignment
18092// patterns, rest elements, and other constructs that may appear within an
18093// object or array destructuring pattern.
18094//
18095// As a special case, function parameters also use checkLValInnerPattern(),
18096// as they also support defaults and rest constructs.
18097//
18098// These functions deliberately support both assignment and binding constructs,
18099// as the logic for both is exceedingly similar. If the node is the target of
18100// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
18101// should be set to the appropriate BIND_* constant, like BIND_VAR or
18102// BIND_LEXICAL.
18103//
18104// If the function is called with a non-BIND_NONE bindingType, then
18105// additionally a checkClashes object may be specified to allow checking for
18106// duplicate argument names. checkClashes is ignored if the provided construct
18107// is an assignment (i.e., bindingType is BIND_NONE).
18108
18109pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
18110 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18111
18112 var isBind = bindingType !== BIND_NONE;
18113
18114 switch (expr.type) {
18115 case "Identifier":
18116 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
18117 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
18118 if (isBind) {
18119 if (bindingType === BIND_LEXICAL && expr.name === "let")
18120 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
18121 if (checkClashes) {
18122 if (hasOwn(checkClashes, expr.name))
18123 { this.raiseRecoverable(expr.start, "Argument name clash"); }
18124 checkClashes[expr.name] = true;
18125 }
18126 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
18127 }
18128 break
18129
18130 case "ChainExpression":
18131 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
18132 break
18133
18134 case "MemberExpression":
18135 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
18136 break
18137
18138 case "ParenthesizedExpression":
18139 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
18140 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
18141
18142 default:
18143 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
18144 }
18145};
18146
18147pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
18148 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18149
18150 switch (expr.type) {
18151 case "ObjectPattern":
18152 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
18153 var prop = list[i];
18154
18155 this.checkLValInnerPattern(prop, bindingType, checkClashes);
18156 }
18157 break
18158
18159 case "ArrayPattern":
18160 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
18161 var elem = list$1[i$1];
18162
18163 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
18164 }
18165 break
18166
18167 default:
18168 this.checkLValSimple(expr, bindingType, checkClashes);
18169 }
18170};
18171
18172pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
18173 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18174
18175 switch (expr.type) {
18176 case "Property":
18177 // AssignmentProperty has type === "Property"
18178 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
18179 break
18180
18181 case "AssignmentPattern":
18182 this.checkLValPattern(expr.left, bindingType, checkClashes);
18183 break
18184
18185 case "RestElement":
18186 this.checkLValPattern(expr.argument, bindingType, checkClashes);
18187 break
18188
18189 default:
18190 this.checkLValPattern(expr, bindingType, checkClashes);
18191 }
18192};
18193
18194// The algorithm used to determine whether a regexp can appear at a
18195
18196var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
18197 this.token = token;
18198 this.isExpr = !!isExpr;
18199 this.preserveSpace = !!preserveSpace;
18200 this.override = override;
18201 this.generator = !!generator;
18202};
18203
18204var types = {
18205 b_stat: new TokContext("{", false),
18206 b_expr: new TokContext("{", true),
18207 b_tmpl: new TokContext("${", false),
18208 p_stat: new TokContext("(", false),
18209 p_expr: new TokContext("(", true),
18210 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
18211 f_stat: new TokContext("function", false),
18212 f_expr: new TokContext("function", true),
18213 f_expr_gen: new TokContext("function", true, false, null, true),
18214 f_gen: new TokContext("function", false, false, null, true)
18215};
18216
18217var pp$6 = Parser.prototype;
18218
18219pp$6.initialContext = function() {
18220 return [types.b_stat]
18221};
18222
18223pp$6.curContext = function() {
18224 return this.context[this.context.length - 1]
18225};
18226
18227pp$6.braceIsBlock = function(prevType) {
18228 var parent = this.curContext();
18229 if (parent === types.f_expr || parent === types.f_stat)
18230 { return true }
18231 if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
18232 { return !parent.isExpr }
18233
18234 // The check for `tt.name && exprAllowed` detects whether we are
18235 // after a `yield` or `of` construct. See the `updateContext` for
18236 // `tt.name`.
18237 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
18238 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
18239 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
18240 { return true }
18241 if (prevType === types$1.braceL)
18242 { return parent === types.b_stat }
18243 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
18244 { return false }
18245 return !this.exprAllowed
18246};
18247
18248pp$6.inGeneratorContext = function() {
18249 for (var i = this.context.length - 1; i >= 1; i--) {
18250 var context = this.context[i];
18251 if (context.token === "function")
18252 { return context.generator }
18253 }
18254 return false
18255};
18256
18257pp$6.updateContext = function(prevType) {
18258 var update, type = this.type;
18259 if (type.keyword && prevType === types$1.dot)
18260 { this.exprAllowed = false; }
18261 else if (update = type.updateContext)
18262 { update.call(this, prevType); }
18263 else
18264 { this.exprAllowed = type.beforeExpr; }
18265};
18266
18267// Used to handle egde case when token context could not be inferred correctly in tokenize phase
18268pp$6.overrideContext = function(tokenCtx) {
18269 if (this.curContext() !== tokenCtx) {
18270 this.context[this.context.length - 1] = tokenCtx;
18271 }
18272};
18273
18274// Token-specific context update code
18275
18276types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
18277 if (this.context.length === 1) {
18278 this.exprAllowed = true;
18279 return
18280 }
18281 var out = this.context.pop();
18282 if (out === types.b_stat && this.curContext().token === "function") {
18283 out = this.context.pop();
18284 }
18285 this.exprAllowed = !out.isExpr;
18286};
18287
18288types$1.braceL.updateContext = function(prevType) {
18289 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
18290 this.exprAllowed = true;
18291};
18292
18293types$1.dollarBraceL.updateContext = function() {
18294 this.context.push(types.b_tmpl);
18295 this.exprAllowed = true;
18296};
18297
18298types$1.parenL.updateContext = function(prevType) {
18299 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
18300 this.context.push(statementParens ? types.p_stat : types.p_expr);
18301 this.exprAllowed = true;
18302};
18303
18304types$1.incDec.updateContext = function() {
18305 // tokExprAllowed stays unchanged
18306};
18307
18308types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
18309 if (prevType.beforeExpr && prevType !== types$1._else &&
18310 !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
18311 !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
18312 !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
18313 { this.context.push(types.f_expr); }
18314 else
18315 { this.context.push(types.f_stat); }
18316 this.exprAllowed = false;
18317};
18318
18319types$1.backQuote.updateContext = function() {
18320 if (this.curContext() === types.q_tmpl)
18321 { this.context.pop(); }
18322 else
18323 { this.context.push(types.q_tmpl); }
18324 this.exprAllowed = false;
18325};
18326
18327types$1.star.updateContext = function(prevType) {
18328 if (prevType === types$1._function) {
18329 var index = this.context.length - 1;
18330 if (this.context[index] === types.f_expr)
18331 { this.context[index] = types.f_expr_gen; }
18332 else
18333 { this.context[index] = types.f_gen; }
18334 }
18335 this.exprAllowed = true;
18336};
18337
18338types$1.name.updateContext = function(prevType) {
18339 var allowed = false;
18340 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
18341 if (this.value === "of" && !this.exprAllowed ||
18342 this.value === "yield" && this.inGeneratorContext())
18343 { allowed = true; }
18344 }
18345 this.exprAllowed = allowed;
18346};
18347
18348// A recursive descent parser operates by defining functions for all
18349
18350var pp$5 = Parser.prototype;
18351
18352// Check if property name clashes with already added.
18353// Object/class getters and setters are not allowed to clash —
18354// either with each other or with an init property — and in
18355// strict mode, init properties are also not allowed to be repeated.
18356
18357pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
18358 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
18359 { return }
18360 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
18361 { return }
18362 var key = prop.key;
18363 var name;
18364 switch (key.type) {
18365 case "Identifier": name = key.name; break
18366 case "Literal": name = String(key.value); break
18367 default: return
18368 }
18369 var kind = prop.kind;
18370 if (this.options.ecmaVersion >= 6) {
18371 if (name === "__proto__" && kind === "init") {
18372 if (propHash.proto) {
18373 if (refDestructuringErrors) {
18374 if (refDestructuringErrors.doubleProto < 0) {
18375 refDestructuringErrors.doubleProto = key.start;
18376 }
18377 } else {
18378 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
18379 }
18380 }
18381 propHash.proto = true;
18382 }
18383 return
18384 }
18385 name = "$" + name;
18386 var other = propHash[name];
18387 if (other) {
18388 var redefinition;
18389 if (kind === "init") {
18390 redefinition = this.strict && other.init || other.get || other.set;
18391 } else {
18392 redefinition = other.init || other[kind];
18393 }
18394 if (redefinition)
18395 { this.raiseRecoverable(key.start, "Redefinition of property"); }
18396 } else {
18397 other = propHash[name] = {
18398 init: false,
18399 get: false,
18400 set: false
18401 };
18402 }
18403 other[kind] = true;
18404};
18405
18406// ### Expression parsing
18407
18408// These nest, from the most general expression type at the top to
18409// 'atomic', nondivisible expression types at the bottom. Most of
18410// the functions will simply let the function(s) below them parse,
18411// and, *if* the syntactic construct they handle is present, wrap
18412// the AST node that the inner parser gave them in another node.
18413
18414// Parse a full expression. The optional arguments are used to
18415// forbid the `in` operator (in for loops initalization expressions)
18416// and provide reference for storing '=' operator inside shorthand
18417// property assignment in contexts where both object expression
18418// and object pattern might appear (so it's possible to raise
18419// delayed syntax error at correct position).
18420
18421pp$5.parseExpression = function(forInit, refDestructuringErrors) {
18422 var startPos = this.start, startLoc = this.startLoc;
18423 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
18424 if (this.type === types$1.comma) {
18425 var node = this.startNodeAt(startPos, startLoc);
18426 node.expressions = [expr];
18427 while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
18428 return this.finishNode(node, "SequenceExpression")
18429 }
18430 return expr
18431};
18432
18433// Parse an assignment expression. This includes applications of
18434// operators like `+=`.
18435
18436pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
18437 if (this.isContextual("yield")) {
18438 if (this.inGenerator) { return this.parseYield(forInit) }
18439 // The tokenizer will assume an expression is allowed after
18440 // `yield`, but this isn't that kind of yield
18441 else { this.exprAllowed = false; }
18442 }
18443
18444 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
18445 if (refDestructuringErrors) {
18446 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
18447 oldTrailingComma = refDestructuringErrors.trailingComma;
18448 oldDoubleProto = refDestructuringErrors.doubleProto;
18449 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
18450 } else {
18451 refDestructuringErrors = new DestructuringErrors;
18452 ownDestructuringErrors = true;
18453 }
18454
18455 var startPos = this.start, startLoc = this.startLoc;
18456 if (this.type === types$1.parenL || this.type === types$1.name) {
18457 this.potentialArrowAt = this.start;
18458 this.potentialArrowInForAwait = forInit === "await";
18459 }
18460 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
18461 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
18462 if (this.type.isAssign) {
18463 var node = this.startNodeAt(startPos, startLoc);
18464 node.operator = this.value;
18465 if (this.type === types$1.eq)
18466 { left = this.toAssignable(left, false, refDestructuringErrors); }
18467 if (!ownDestructuringErrors) {
18468 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
18469 }
18470 if (refDestructuringErrors.shorthandAssign >= left.start)
18471 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
18472 if (this.type === types$1.eq)
18473 { this.checkLValPattern(left); }
18474 else
18475 { this.checkLValSimple(left); }
18476 node.left = left;
18477 this.next();
18478 node.right = this.parseMaybeAssign(forInit);
18479 if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
18480 return this.finishNode(node, "AssignmentExpression")
18481 } else {
18482 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
18483 }
18484 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
18485 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
18486 return left
18487};
18488
18489// Parse a ternary conditional (`?:`) operator.
18490
18491pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
18492 var startPos = this.start, startLoc = this.startLoc;
18493 var expr = this.parseExprOps(forInit, refDestructuringErrors);
18494 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18495 if (this.eat(types$1.question)) {
18496 var node = this.startNodeAt(startPos, startLoc);
18497 node.test = expr;
18498 node.consequent = this.parseMaybeAssign();
18499 this.expect(types$1.colon);
18500 node.alternate = this.parseMaybeAssign(forInit);
18501 return this.finishNode(node, "ConditionalExpression")
18502 }
18503 return expr
18504};
18505
18506// Start the precedence parser.
18507
18508pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
18509 var startPos = this.start, startLoc = this.startLoc;
18510 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
18511 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18512 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
18513};
18514
18515// Parse binary operators with the operator precedence parsing
18516// algorithm. `left` is the left-hand side of the operator.
18517// `minPrec` provides context that allows the function to stop and
18518// defer further parser to one of its callers when it encounters an
18519// operator that has a lower precedence than the set it is parsing.
18520
18521pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
18522 var prec = this.type.binop;
18523 if (prec != null && (!forInit || this.type !== types$1._in)) {
18524 if (prec > minPrec) {
18525 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
18526 var coalesce = this.type === types$1.coalesce;
18527 if (coalesce) {
18528 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
18529 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
18530 prec = types$1.logicalAND.binop;
18531 }
18532 var op = this.value;
18533 this.next();
18534 var startPos = this.start, startLoc = this.startLoc;
18535 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
18536 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
18537 if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
18538 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
18539 }
18540 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
18541 }
18542 }
18543 return left
18544};
18545
18546pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
18547 if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
18548 var node = this.startNodeAt(startPos, startLoc);
18549 node.left = left;
18550 node.operator = op;
18551 node.right = right;
18552 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
18553};
18554
18555// Parse unary operators, both prefix and postfix.
18556
18557pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
18558 var startPos = this.start, startLoc = this.startLoc, expr;
18559 if (this.isContextual("await") && this.canAwait) {
18560 expr = this.parseAwait(forInit);
18561 sawUnary = true;
18562 } else if (this.type.prefix) {
18563 var node = this.startNode(), update = this.type === types$1.incDec;
18564 node.operator = this.value;
18565 node.prefix = true;
18566 this.next();
18567 node.argument = this.parseMaybeUnary(null, true, update, forInit);
18568 this.checkExpressionErrors(refDestructuringErrors, true);
18569 if (update) { this.checkLValSimple(node.argument); }
18570 else if (this.strict && node.operator === "delete" &&
18571 node.argument.type === "Identifier")
18572 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
18573 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
18574 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
18575 else { sawUnary = true; }
18576 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
18577 } else if (!sawUnary && this.type === types$1.privateId) {
18578 if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
18579 expr = this.parsePrivateIdent();
18580 // only could be private fields in 'in', such as #x in obj
18581 if (this.type !== types$1._in) { this.unexpected(); }
18582 } else {
18583 expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
18584 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18585 while (this.type.postfix && !this.canInsertSemicolon()) {
18586 var node$1 = this.startNodeAt(startPos, startLoc);
18587 node$1.operator = this.value;
18588 node$1.prefix = false;
18589 node$1.argument = expr;
18590 this.checkLValSimple(expr);
18591 this.next();
18592 expr = this.finishNode(node$1, "UpdateExpression");
18593 }
18594 }
18595
18596 if (!incDec && this.eat(types$1.starstar)) {
18597 if (sawUnary)
18598 { this.unexpected(this.lastTokStart); }
18599 else
18600 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
18601 } else {
18602 return expr
18603 }
18604};
18605
18606function isPrivateFieldAccess(node) {
18607 return (
18608 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
18609 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
18610 )
18611}
18612
18613// Parse call, dot, and `[]`-subscript expressions.
18614
18615pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
18616 var startPos = this.start, startLoc = this.startLoc;
18617 var expr = this.parseExprAtom(refDestructuringErrors, forInit);
18618 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
18619 { return expr }
18620 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
18621 if (refDestructuringErrors && result.type === "MemberExpression") {
18622 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
18623 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
18624 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
18625 }
18626 return result
18627};
18628
18629pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
18630 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
18631 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
18632 this.potentialArrowAt === base.start;
18633 var optionalChained = false;
18634
18635 while (true) {
18636 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
18637
18638 if (element.optional) { optionalChained = true; }
18639 if (element === base || element.type === "ArrowFunctionExpression") {
18640 if (optionalChained) {
18641 var chainNode = this.startNodeAt(startPos, startLoc);
18642 chainNode.expression = element;
18643 element = this.finishNode(chainNode, "ChainExpression");
18644 }
18645 return element
18646 }
18647
18648 base = element;
18649 }
18650};
18651
18652pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
18653 var optionalSupported = this.options.ecmaVersion >= 11;
18654 var optional = optionalSupported && this.eat(types$1.questionDot);
18655 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
18656
18657 var computed = this.eat(types$1.bracketL);
18658 if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
18659 var node = this.startNodeAt(startPos, startLoc);
18660 node.object = base;
18661 if (computed) {
18662 node.property = this.parseExpression();
18663 this.expect(types$1.bracketR);
18664 } else if (this.type === types$1.privateId && base.type !== "Super") {
18665 node.property = this.parsePrivateIdent();
18666 } else {
18667 node.property = this.parseIdent(this.options.allowReserved !== "never");
18668 }
18669 node.computed = !!computed;
18670 if (optionalSupported) {
18671 node.optional = optional;
18672 }
18673 base = this.finishNode(node, "MemberExpression");
18674 } else if (!noCalls && this.eat(types$1.parenL)) {
18675 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
18676 this.yieldPos = 0;
18677 this.awaitPos = 0;
18678 this.awaitIdentPos = 0;
18679 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
18680 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
18681 this.checkPatternErrors(refDestructuringErrors, false);
18682 this.checkYieldAwaitInDefaultParams();
18683 if (this.awaitIdentPos > 0)
18684 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
18685 this.yieldPos = oldYieldPos;
18686 this.awaitPos = oldAwaitPos;
18687 this.awaitIdentPos = oldAwaitIdentPos;
18688 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
18689 }
18690 this.checkExpressionErrors(refDestructuringErrors, true);
18691 this.yieldPos = oldYieldPos || this.yieldPos;
18692 this.awaitPos = oldAwaitPos || this.awaitPos;
18693 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
18694 var node$1 = this.startNodeAt(startPos, startLoc);
18695 node$1.callee = base;
18696 node$1.arguments = exprList;
18697 if (optionalSupported) {
18698 node$1.optional = optional;
18699 }
18700 base = this.finishNode(node$1, "CallExpression");
18701 } else if (this.type === types$1.backQuote) {
18702 if (optional || optionalChained) {
18703 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
18704 }
18705 var node$2 = this.startNodeAt(startPos, startLoc);
18706 node$2.tag = base;
18707 node$2.quasi = this.parseTemplate({isTagged: true});
18708 base = this.finishNode(node$2, "TaggedTemplateExpression");
18709 }
18710 return base
18711};
18712
18713// Parse an atomic expression — either a single token that is an
18714// expression, an expression started by a keyword like `function` or
18715// `new`, or an expression wrapped in punctuation like `()`, `[]`,
18716// or `{}`.
18717
18718pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
18719 // If a division operator appears in an expression position, the
18720 // tokenizer got confused, and we force it to read a regexp instead.
18721 if (this.type === types$1.slash) { this.readRegexp(); }
18722
18723 var node, canBeArrow = this.potentialArrowAt === this.start;
18724 switch (this.type) {
18725 case types$1._super:
18726 if (!this.allowSuper)
18727 { this.raise(this.start, "'super' keyword outside a method"); }
18728 node = this.startNode();
18729 this.next();
18730 if (this.type === types$1.parenL && !this.allowDirectSuper)
18731 { this.raise(node.start, "super() call outside constructor of a subclass"); }
18732 // The `super` keyword can appear at below:
18733 // SuperProperty:
18734 // super [ Expression ]
18735 // super . IdentifierName
18736 // SuperCall:
18737 // super ( Arguments )
18738 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
18739 { this.unexpected(); }
18740 return this.finishNode(node, "Super")
18741
18742 case types$1._this:
18743 node = this.startNode();
18744 this.next();
18745 return this.finishNode(node, "ThisExpression")
18746
18747 case types$1.name:
18748 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
18749 var id = this.parseIdent(false);
18750 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
18751 this.overrideContext(types.f_expr);
18752 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
18753 }
18754 if (canBeArrow && !this.canInsertSemicolon()) {
18755 if (this.eat(types$1.arrow))
18756 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
18757 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
18758 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
18759 id = this.parseIdent(false);
18760 if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
18761 { this.unexpected(); }
18762 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
18763 }
18764 }
18765 return id
18766
18767 case types$1.regexp:
18768 var value = this.value;
18769 node = this.parseLiteral(value.value);
18770 node.regex = {pattern: value.pattern, flags: value.flags};
18771 return node
18772
18773 case types$1.num: case types$1.string:
18774 return this.parseLiteral(this.value)
18775
18776 case types$1._null: case types$1._true: case types$1._false:
18777 node = this.startNode();
18778 node.value = this.type === types$1._null ? null : this.type === types$1._true;
18779 node.raw = this.type.keyword;
18780 this.next();
18781 return this.finishNode(node, "Literal")
18782
18783 case types$1.parenL:
18784 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
18785 if (refDestructuringErrors) {
18786 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
18787 { refDestructuringErrors.parenthesizedAssign = start; }
18788 if (refDestructuringErrors.parenthesizedBind < 0)
18789 { refDestructuringErrors.parenthesizedBind = start; }
18790 }
18791 return expr
18792
18793 case types$1.bracketL:
18794 node = this.startNode();
18795 this.next();
18796 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
18797 return this.finishNode(node, "ArrayExpression")
18798
18799 case types$1.braceL:
18800 this.overrideContext(types.b_expr);
18801 return this.parseObj(false, refDestructuringErrors)
18802
18803 case types$1._function:
18804 node = this.startNode();
18805 this.next();
18806 return this.parseFunction(node, 0)
18807
18808 case types$1._class:
18809 return this.parseClass(this.startNode(), false)
18810
18811 case types$1._new:
18812 return this.parseNew()
18813
18814 case types$1.backQuote:
18815 return this.parseTemplate()
18816
18817 case types$1._import:
18818 if (this.options.ecmaVersion >= 11) {
18819 return this.parseExprImport()
18820 } else {
18821 return this.unexpected()
18822 }
18823
18824 default:
18825 this.unexpected();
18826 }
18827};
18828
18829pp$5.parseExprImport = function() {
18830 var node = this.startNode();
18831
18832 // Consume `import` as an identifier for `import.meta`.
18833 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
18834 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
18835 var meta = this.parseIdent(true);
18836
18837 switch (this.type) {
18838 case types$1.parenL:
18839 return this.parseDynamicImport(node)
18840 case types$1.dot:
18841 node.meta = meta;
18842 return this.parseImportMeta(node)
18843 default:
18844 this.unexpected();
18845 }
18846};
18847
18848pp$5.parseDynamicImport = function(node) {
18849 this.next(); // skip `(`
18850
18851 // Parse node.source.
18852 node.source = this.parseMaybeAssign();
18853
18854 // Verify ending.
18855 if (!this.eat(types$1.parenR)) {
18856 var errorPos = this.start;
18857 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
18858 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
18859 } else {
18860 this.unexpected(errorPos);
18861 }
18862 }
18863
18864 return this.finishNode(node, "ImportExpression")
18865};
18866
18867pp$5.parseImportMeta = function(node) {
18868 this.next(); // skip `.`
18869
18870 var containsEsc = this.containsEsc;
18871 node.property = this.parseIdent(true);
18872
18873 if (node.property.name !== "meta")
18874 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
18875 if (containsEsc)
18876 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
18877 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
18878 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
18879
18880 return this.finishNode(node, "MetaProperty")
18881};
18882
18883pp$5.parseLiteral = function(value) {
18884 var node = this.startNode();
18885 node.value = value;
18886 node.raw = this.input.slice(this.start, this.end);
18887 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
18888 this.next();
18889 return this.finishNode(node, "Literal")
18890};
18891
18892pp$5.parseParenExpression = function() {
18893 this.expect(types$1.parenL);
18894 var val = this.parseExpression();
18895 this.expect(types$1.parenR);
18896 return val
18897};
18898
18899pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
18900 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
18901 if (this.options.ecmaVersion >= 6) {
18902 this.next();
18903
18904 var innerStartPos = this.start, innerStartLoc = this.startLoc;
18905 var exprList = [], first = true, lastIsComma = false;
18906 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
18907 this.yieldPos = 0;
18908 this.awaitPos = 0;
18909 // Do not save awaitIdentPos to allow checking awaits nested in parameters
18910 while (this.type !== types$1.parenR) {
18911 first ? first = false : this.expect(types$1.comma);
18912 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
18913 lastIsComma = true;
18914 break
18915 } else if (this.type === types$1.ellipsis) {
18916 spreadStart = this.start;
18917 exprList.push(this.parseParenItem(this.parseRestBinding()));
18918 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
18919 break
18920 } else {
18921 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
18922 }
18923 }
18924 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
18925 this.expect(types$1.parenR);
18926
18927 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
18928 this.checkPatternErrors(refDestructuringErrors, false);
18929 this.checkYieldAwaitInDefaultParams();
18930 this.yieldPos = oldYieldPos;
18931 this.awaitPos = oldAwaitPos;
18932 return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
18933 }
18934
18935 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
18936 if (spreadStart) { this.unexpected(spreadStart); }
18937 this.checkExpressionErrors(refDestructuringErrors, true);
18938 this.yieldPos = oldYieldPos || this.yieldPos;
18939 this.awaitPos = oldAwaitPos || this.awaitPos;
18940
18941 if (exprList.length > 1) {
18942 val = this.startNodeAt(innerStartPos, innerStartLoc);
18943 val.expressions = exprList;
18944 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
18945 } else {
18946 val = exprList[0];
18947 }
18948 } else {
18949 val = this.parseParenExpression();
18950 }
18951
18952 if (this.options.preserveParens) {
18953 var par = this.startNodeAt(startPos, startLoc);
18954 par.expression = val;
18955 return this.finishNode(par, "ParenthesizedExpression")
18956 } else {
18957 return val
18958 }
18959};
18960
18961pp$5.parseParenItem = function(item) {
18962 return item
18963};
18964
18965pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
18966 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
18967};
18968
18969// New's precedence is slightly tricky. It must allow its argument to
18970// be a `[]` or dot subscript expression, but not a call — at least,
18971// not without wrapping it in parentheses. Thus, it uses the noCalls
18972// argument to parseSubscripts to prevent it from consuming the
18973// argument list.
18974
18975var empty = [];
18976
18977pp$5.parseNew = function() {
18978 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
18979 var node = this.startNode();
18980 var meta = this.parseIdent(true);
18981 if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
18982 node.meta = meta;
18983 var containsEsc = this.containsEsc;
18984 node.property = this.parseIdent(true);
18985 if (node.property.name !== "target")
18986 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
18987 if (containsEsc)
18988 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
18989 if (!this.allowNewDotTarget)
18990 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
18991 return this.finishNode(node, "MetaProperty")
18992 }
18993 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
18994 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
18995 if (isImport && node.callee.type === "ImportExpression") {
18996 this.raise(startPos, "Cannot use new with import()");
18997 }
18998 if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
18999 else { node.arguments = empty; }
19000 return this.finishNode(node, "NewExpression")
19001};
19002
19003// Parse template expression.
19004
19005pp$5.parseTemplateElement = function(ref) {
19006 var isTagged = ref.isTagged;
19007
19008 var elem = this.startNode();
19009 if (this.type === types$1.invalidTemplate) {
19010 if (!isTagged) {
19011 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
19012 }
19013 elem.value = {
19014 raw: this.value,
19015 cooked: null
19016 };
19017 } else {
19018 elem.value = {
19019 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
19020 cooked: this.value
19021 };
19022 }
19023 this.next();
19024 elem.tail = this.type === types$1.backQuote;
19025 return this.finishNode(elem, "TemplateElement")
19026};
19027
19028pp$5.parseTemplate = function(ref) {
19029 if ( ref === void 0 ) ref = {};
19030 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
19031
19032 var node = this.startNode();
19033 this.next();
19034 node.expressions = [];
19035 var curElt = this.parseTemplateElement({isTagged: isTagged});
19036 node.quasis = [curElt];
19037 while (!curElt.tail) {
19038 if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
19039 this.expect(types$1.dollarBraceL);
19040 node.expressions.push(this.parseExpression());
19041 this.expect(types$1.braceR);
19042 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
19043 }
19044 this.next();
19045 return this.finishNode(node, "TemplateLiteral")
19046};
19047
19048pp$5.isAsyncProp = function(prop) {
19049 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
19050 (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
19051 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
19052};
19053
19054// Parse an object literal or binding pattern.
19055
19056pp$5.parseObj = function(isPattern, refDestructuringErrors) {
19057 var node = this.startNode(), first = true, propHash = {};
19058 node.properties = [];
19059 this.next();
19060 while (!this.eat(types$1.braceR)) {
19061 if (!first) {
19062 this.expect(types$1.comma);
19063 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
19064 } else { first = false; }
19065
19066 var prop = this.parseProperty(isPattern, refDestructuringErrors);
19067 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
19068 node.properties.push(prop);
19069 }
19070 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
19071};
19072
19073pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
19074 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
19075 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
19076 if (isPattern) {
19077 prop.argument = this.parseIdent(false);
19078 if (this.type === types$1.comma) {
19079 this.raise(this.start, "Comma is not permitted after the rest element");
19080 }
19081 return this.finishNode(prop, "RestElement")
19082 }
19083 // To disallow parenthesized identifier via `this.toAssignable()`.
19084 if (this.type === types$1.parenL && refDestructuringErrors) {
19085 if (refDestructuringErrors.parenthesizedAssign < 0) {
19086 refDestructuringErrors.parenthesizedAssign = this.start;
19087 }
19088 if (refDestructuringErrors.parenthesizedBind < 0) {
19089 refDestructuringErrors.parenthesizedBind = this.start;
19090 }
19091 }
19092 // Parse argument.
19093 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
19094 // To disallow trailing comma via `this.toAssignable()`.
19095 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
19096 refDestructuringErrors.trailingComma = this.start;
19097 }
19098 // Finish
19099 return this.finishNode(prop, "SpreadElement")
19100 }
19101 if (this.options.ecmaVersion >= 6) {
19102 prop.method = false;
19103 prop.shorthand = false;
19104 if (isPattern || refDestructuringErrors) {
19105 startPos = this.start;
19106 startLoc = this.startLoc;
19107 }
19108 if (!isPattern)
19109 { isGenerator = this.eat(types$1.star); }
19110 }
19111 var containsEsc = this.containsEsc;
19112 this.parsePropertyName(prop);
19113 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
19114 isAsync = true;
19115 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
19116 this.parsePropertyName(prop, refDestructuringErrors);
19117 } else {
19118 isAsync = false;
19119 }
19120 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
19121 return this.finishNode(prop, "Property")
19122};
19123
19124pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
19125 if ((isGenerator || isAsync) && this.type === types$1.colon)
19126 { this.unexpected(); }
19127
19128 if (this.eat(types$1.colon)) {
19129 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
19130 prop.kind = "init";
19131 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
19132 if (isPattern) { this.unexpected(); }
19133 prop.kind = "init";
19134 prop.method = true;
19135 prop.value = this.parseMethod(isGenerator, isAsync);
19136 } else if (!isPattern && !containsEsc &&
19137 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
19138 (prop.key.name === "get" || prop.key.name === "set") &&
19139 (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
19140 if (isGenerator || isAsync) { this.unexpected(); }
19141 prop.kind = prop.key.name;
19142 this.parsePropertyName(prop);
19143 prop.value = this.parseMethod(false);
19144 var paramCount = prop.kind === "get" ? 0 : 1;
19145 if (prop.value.params.length !== paramCount) {
19146 var start = prop.value.start;
19147 if (prop.kind === "get")
19148 { this.raiseRecoverable(start, "getter should have no params"); }
19149 else
19150 { this.raiseRecoverable(start, "setter should have exactly one param"); }
19151 } else {
19152 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
19153 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
19154 }
19155 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
19156 if (isGenerator || isAsync) { this.unexpected(); }
19157 this.checkUnreserved(prop.key);
19158 if (prop.key.name === "await" && !this.awaitIdentPos)
19159 { this.awaitIdentPos = startPos; }
19160 prop.kind = "init";
19161 if (isPattern) {
19162 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19163 } else if (this.type === types$1.eq && refDestructuringErrors) {
19164 if (refDestructuringErrors.shorthandAssign < 0)
19165 { refDestructuringErrors.shorthandAssign = this.start; }
19166 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19167 } else {
19168 prop.value = this.copyNode(prop.key);
19169 }
19170 prop.shorthand = true;
19171 } else { this.unexpected(); }
19172};
19173
19174pp$5.parsePropertyName = function(prop) {
19175 if (this.options.ecmaVersion >= 6) {
19176 if (this.eat(types$1.bracketL)) {
19177 prop.computed = true;
19178 prop.key = this.parseMaybeAssign();
19179 this.expect(types$1.bracketR);
19180 return prop.key
19181 } else {
19182 prop.computed = false;
19183 }
19184 }
19185 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
19186};
19187
19188// Initialize empty function node.
19189
19190pp$5.initFunction = function(node) {
19191 node.id = null;
19192 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
19193 if (this.options.ecmaVersion >= 8) { node.async = false; }
19194};
19195
19196// Parse object or class method.
19197
19198pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
19199 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19200
19201 this.initFunction(node);
19202 if (this.options.ecmaVersion >= 6)
19203 { node.generator = isGenerator; }
19204 if (this.options.ecmaVersion >= 8)
19205 { node.async = !!isAsync; }
19206
19207 this.yieldPos = 0;
19208 this.awaitPos = 0;
19209 this.awaitIdentPos = 0;
19210 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
19211
19212 this.expect(types$1.parenL);
19213 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
19214 this.checkYieldAwaitInDefaultParams();
19215 this.parseFunctionBody(node, false, true, false);
19216
19217 this.yieldPos = oldYieldPos;
19218 this.awaitPos = oldAwaitPos;
19219 this.awaitIdentPos = oldAwaitIdentPos;
19220 return this.finishNode(node, "FunctionExpression")
19221};
19222
19223// Parse arrow function expression with given parameters.
19224
19225pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
19226 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19227
19228 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
19229 this.initFunction(node);
19230 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
19231
19232 this.yieldPos = 0;
19233 this.awaitPos = 0;
19234 this.awaitIdentPos = 0;
19235
19236 node.params = this.toAssignableList(params, true);
19237 this.parseFunctionBody(node, true, false, forInit);
19238
19239 this.yieldPos = oldYieldPos;
19240 this.awaitPos = oldAwaitPos;
19241 this.awaitIdentPos = oldAwaitIdentPos;
19242 return this.finishNode(node, "ArrowFunctionExpression")
19243};
19244
19245// Parse function body and check parameters.
19246
19247pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
19248 var isExpression = isArrowFunction && this.type !== types$1.braceL;
19249 var oldStrict = this.strict, useStrict = false;
19250
19251 if (isExpression) {
19252 node.body = this.parseMaybeAssign(forInit);
19253 node.expression = true;
19254 this.checkParams(node, false);
19255 } else {
19256 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
19257 if (!oldStrict || nonSimple) {
19258 useStrict = this.strictDirective(this.end);
19259 // If this is a strict mode function, verify that argument names
19260 // are not repeated, and it does not try to bind the words `eval`
19261 // or `arguments`.
19262 if (useStrict && nonSimple)
19263 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
19264 }
19265 // Start a new scope with regard to labels and the `inFunction`
19266 // flag (restore them to their old value afterwards).
19267 var oldLabels = this.labels;
19268 this.labels = [];
19269 if (useStrict) { this.strict = true; }
19270
19271 // Add the params to varDeclaredNames to ensure that an error is thrown
19272 // if a let/const declaration in the function clashes with one of the params.
19273 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
19274 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
19275 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
19276 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
19277 node.expression = false;
19278 this.adaptDirectivePrologue(node.body.body);
19279 this.labels = oldLabels;
19280 }
19281 this.exitScope();
19282};
19283
19284pp$5.isSimpleParamList = function(params) {
19285 for (var i = 0, list = params; i < list.length; i += 1)
19286 {
19287 var param = list[i];
19288
19289 if (param.type !== "Identifier") { return false
19290 } }
19291 return true
19292};
19293
19294// Checks function params for various disallowed patterns such as using "eval"
19295// or "arguments" and duplicate parameters.
19296
19297pp$5.checkParams = function(node, allowDuplicates) {
19298 var nameHash = Object.create(null);
19299 for (var i = 0, list = node.params; i < list.length; i += 1)
19300 {
19301 var param = list[i];
19302
19303 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
19304 }
19305};
19306
19307// Parses a comma-separated list of expressions, and returns them as
19308// an array. `close` is the token type that ends the list, and
19309// `allowEmpty` can be turned on to allow subsequent commas with
19310// nothing in between them to be parsed as `null` (which is needed
19311// for array literals).
19312
19313pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
19314 var elts = [], first = true;
19315 while (!this.eat(close)) {
19316 if (!first) {
19317 this.expect(types$1.comma);
19318 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
19319 } else { first = false; }
19320
19321 var elt = (void 0);
19322 if (allowEmpty && this.type === types$1.comma)
19323 { elt = null; }
19324 else if (this.type === types$1.ellipsis) {
19325 elt = this.parseSpread(refDestructuringErrors);
19326 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
19327 { refDestructuringErrors.trailingComma = this.start; }
19328 } else {
19329 elt = this.parseMaybeAssign(false, refDestructuringErrors);
19330 }
19331 elts.push(elt);
19332 }
19333 return elts
19334};
19335
19336pp$5.checkUnreserved = function(ref) {
19337 var start = ref.start;
19338 var end = ref.end;
19339 var name = ref.name;
19340
19341 if (this.inGenerator && name === "yield")
19342 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
19343 if (this.inAsync && name === "await")
19344 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
19345 if (this.currentThisScope().inClassFieldInit && name === "arguments")
19346 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
19347 if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
19348 { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
19349 if (this.keywords.test(name))
19350 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
19351 if (this.options.ecmaVersion < 6 &&
19352 this.input.slice(start, end).indexOf("\\") !== -1) { return }
19353 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
19354 if (re.test(name)) {
19355 if (!this.inAsync && name === "await")
19356 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
19357 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
19358 }
19359};
19360
19361// Parse the next token as an identifier. If `liberal` is true (used
19362// when parsing properties), it will also convert keywords into
19363// identifiers.
19364
19365pp$5.parseIdent = function(liberal, isBinding) {
19366 var node = this.startNode();
19367 if (this.type === types$1.name) {
19368 node.name = this.value;
19369 } else if (this.type.keyword) {
19370 node.name = this.type.keyword;
19371
19372 // To fix https://github.com/acornjs/acorn/issues/575
19373 // `class` and `function` keywords push new context into this.context.
19374 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
19375 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
19376 if ((node.name === "class" || node.name === "function") &&
19377 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
19378 this.context.pop();
19379 }
19380 } else {
19381 this.unexpected();
19382 }
19383 this.next(!!liberal);
19384 this.finishNode(node, "Identifier");
19385 if (!liberal) {
19386 this.checkUnreserved(node);
19387 if (node.name === "await" && !this.awaitIdentPos)
19388 { this.awaitIdentPos = node.start; }
19389 }
19390 return node
19391};
19392
19393pp$5.parsePrivateIdent = function() {
19394 var node = this.startNode();
19395 if (this.type === types$1.privateId) {
19396 node.name = this.value;
19397 } else {
19398 this.unexpected();
19399 }
19400 this.next();
19401 this.finishNode(node, "PrivateIdentifier");
19402
19403 // For validating existence
19404 if (this.privateNameStack.length === 0) {
19405 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
19406 } else {
19407 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
19408 }
19409
19410 return node
19411};
19412
19413// Parses yield expression inside generator.
19414
19415pp$5.parseYield = function(forInit) {
19416 if (!this.yieldPos) { this.yieldPos = this.start; }
19417
19418 var node = this.startNode();
19419 this.next();
19420 if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
19421 node.delegate = false;
19422 node.argument = null;
19423 } else {
19424 node.delegate = this.eat(types$1.star);
19425 node.argument = this.parseMaybeAssign(forInit);
19426 }
19427 return this.finishNode(node, "YieldExpression")
19428};
19429
19430pp$5.parseAwait = function(forInit) {
19431 if (!this.awaitPos) { this.awaitPos = this.start; }
19432
19433 var node = this.startNode();
19434 this.next();
19435 node.argument = this.parseMaybeUnary(null, true, false, forInit);
19436 return this.finishNode(node, "AwaitExpression")
19437};
19438
19439var pp$4 = Parser.prototype;
19440
19441// This function is used to raise exceptions on parse errors. It
19442// takes an offset integer (into the current `input`) to indicate
19443// the location of the error, attaches the position to the end
19444// of the error message, and then raises a `SyntaxError` with that
19445// message.
19446
19447pp$4.raise = function(pos, message) {
19448 var loc = getLineInfo(this.input, pos);
19449 message += " (" + loc.line + ":" + loc.column + ")";
19450 var err = new SyntaxError(message);
19451 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
19452 throw err
19453};
19454
19455pp$4.raiseRecoverable = pp$4.raise;
19456
19457pp$4.curPosition = function() {
19458 if (this.options.locations) {
19459 return new Position(this.curLine, this.pos - this.lineStart)
19460 }
19461};
19462
19463var pp$3 = Parser.prototype;
19464
19465var Scope = function Scope(flags) {
19466 this.flags = flags;
19467 // A list of var-declared names in the current lexical scope
19468 this.var = [];
19469 // A list of lexically-declared names in the current lexical scope
19470 this.lexical = [];
19471 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
19472 this.functions = [];
19473 // A switch to disallow the identifier reference 'arguments'
19474 this.inClassFieldInit = false;
19475};
19476
19477// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
19478
19479pp$3.enterScope = function(flags) {
19480 this.scopeStack.push(new Scope(flags));
19481};
19482
19483pp$3.exitScope = function() {
19484 this.scopeStack.pop();
19485};
19486
19487// The spec says:
19488// > At the top level of a function, or script, function declarations are
19489// > treated like var declarations rather than like lexical declarations.
19490pp$3.treatFunctionsAsVarInScope = function(scope) {
19491 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
19492};
19493
19494pp$3.declareName = function(name, bindingType, pos) {
19495 var redeclared = false;
19496 if (bindingType === BIND_LEXICAL) {
19497 var scope = this.currentScope();
19498 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
19499 scope.lexical.push(name);
19500 if (this.inModule && (scope.flags & SCOPE_TOP))
19501 { delete this.undefinedExports[name]; }
19502 } else if (bindingType === BIND_SIMPLE_CATCH) {
19503 var scope$1 = this.currentScope();
19504 scope$1.lexical.push(name);
19505 } else if (bindingType === BIND_FUNCTION) {
19506 var scope$2 = this.currentScope();
19507 if (this.treatFunctionsAsVar)
19508 { redeclared = scope$2.lexical.indexOf(name) > -1; }
19509 else
19510 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
19511 scope$2.functions.push(name);
19512 } else {
19513 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
19514 var scope$3 = this.scopeStack[i];
19515 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
19516 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
19517 redeclared = true;
19518 break
19519 }
19520 scope$3.var.push(name);
19521 if (this.inModule && (scope$3.flags & SCOPE_TOP))
19522 { delete this.undefinedExports[name]; }
19523 if (scope$3.flags & SCOPE_VAR) { break }
19524 }
19525 }
19526 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
19527};
19528
19529pp$3.checkLocalExport = function(id) {
19530 // scope.functions must be empty as Module code is always strict.
19531 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
19532 this.scopeStack[0].var.indexOf(id.name) === -1) {
19533 this.undefinedExports[id.name] = id;
19534 }
19535};
19536
19537pp$3.currentScope = function() {
19538 return this.scopeStack[this.scopeStack.length - 1]
19539};
19540
19541pp$3.currentVarScope = function() {
19542 for (var i = this.scopeStack.length - 1;; i--) {
19543 var scope = this.scopeStack[i];
19544 if (scope.flags & SCOPE_VAR) { return scope }
19545 }
19546};
19547
19548// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
19549pp$3.currentThisScope = function() {
19550 for (var i = this.scopeStack.length - 1;; i--) {
19551 var scope = this.scopeStack[i];
19552 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
19553 }
19554};
19555
19556var Node = function Node(parser, pos, loc) {
19557 this.type = "";
19558 this.start = pos;
19559 this.end = 0;
19560 if (parser.options.locations)
19561 { this.loc = new SourceLocation(parser, loc); }
19562 if (parser.options.directSourceFile)
19563 { this.sourceFile = parser.options.directSourceFile; }
19564 if (parser.options.ranges)
19565 { this.range = [pos, 0]; }
19566};
19567
19568// Start an AST node, attaching a start offset.
19569
19570var pp$2 = Parser.prototype;
19571
19572pp$2.startNode = function() {
19573 return new Node(this, this.start, this.startLoc)
19574};
19575
19576pp$2.startNodeAt = function(pos, loc) {
19577 return new Node(this, pos, loc)
19578};
19579
19580// Finish an AST node, adding `type` and `end` properties.
19581
19582function finishNodeAt(node, type, pos, loc) {
19583 node.type = type;
19584 node.end = pos;
19585 if (this.options.locations)
19586 { node.loc.end = loc; }
19587 if (this.options.ranges)
19588 { node.range[1] = pos; }
19589 return node
19590}
19591
19592pp$2.finishNode = function(node, type) {
19593 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
19594};
19595
19596// Finish node at given position
19597
19598pp$2.finishNodeAt = function(node, type, pos, loc) {
19599 return finishNodeAt.call(this, node, type, pos, loc)
19600};
19601
19602pp$2.copyNode = function(node) {
19603 var newNode = new Node(this, node.start, this.startLoc);
19604 for (var prop in node) { newNode[prop] = node[prop]; }
19605 return newNode
19606};
19607
19608// This file contains Unicode properties extracted from the ECMAScript
19609// specification. The lists are extracted like so:
19610// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
19611
19612// #table-binary-unicode-properties
19613var 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";
19614var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
19615var ecma11BinaryProperties = ecma10BinaryProperties;
19616var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
19617var ecma13BinaryProperties = ecma12BinaryProperties;
19618var unicodeBinaryProperties = {
19619 9: ecma9BinaryProperties,
19620 10: ecma10BinaryProperties,
19621 11: ecma11BinaryProperties,
19622 12: ecma12BinaryProperties,
19623 13: ecma13BinaryProperties
19624};
19625
19626// #table-unicode-general-category-values
19627var 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";
19628
19629// #table-unicode-script-values
19630var ecma9ScriptValues = "Adlam Adlm 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 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";
19631var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
19632var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
19633var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
19634var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
19635var unicodeScriptValues = {
19636 9: ecma9ScriptValues,
19637 10: ecma10ScriptValues,
19638 11: ecma11ScriptValues,
19639 12: ecma12ScriptValues,
19640 13: ecma13ScriptValues
19641};
19642
19643var data = {};
19644function buildUnicodeData(ecmaVersion) {
19645 var d = data[ecmaVersion] = {
19646 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
19647 nonBinary: {
19648 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
19649 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
19650 }
19651 };
19652 d.nonBinary.Script_Extensions = d.nonBinary.Script;
19653
19654 d.nonBinary.gc = d.nonBinary.General_Category;
19655 d.nonBinary.sc = d.nonBinary.Script;
19656 d.nonBinary.scx = d.nonBinary.Script_Extensions;
19657}
19658
19659for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
19660 var ecmaVersion = list[i];
19661
19662 buildUnicodeData(ecmaVersion);
19663}
19664
19665var pp$1 = Parser.prototype;
19666
19667var RegExpValidationState = function RegExpValidationState(parser) {
19668 this.parser = parser;
19669 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
19670 this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
19671 this.source = "";
19672 this.flags = "";
19673 this.start = 0;
19674 this.switchU = false;
19675 this.switchN = false;
19676 this.pos = 0;
19677 this.lastIntValue = 0;
19678 this.lastStringValue = "";
19679 this.lastAssertionIsQuantifiable = false;
19680 this.numCapturingParens = 0;
19681 this.maxBackReference = 0;
19682 this.groupNames = [];
19683 this.backReferenceNames = [];
19684};
19685
19686RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
19687 var unicode = flags.indexOf("u") !== -1;
19688 this.start = start | 0;
19689 this.source = pattern + "";
19690 this.flags = flags;
19691 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
19692 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
19693};
19694
19695RegExpValidationState.prototype.raise = function raise (message) {
19696 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
19697};
19698
19699// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
19700// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
19701RegExpValidationState.prototype.at = function at (i, forceU) {
19702 if ( forceU === void 0 ) forceU = false;
19703
19704 var s = this.source;
19705 var l = s.length;
19706 if (i >= l) {
19707 return -1
19708 }
19709 var c = s.charCodeAt(i);
19710 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
19711 return c
19712 }
19713 var next = s.charCodeAt(i + 1);
19714 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
19715};
19716
19717RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
19718 if ( forceU === void 0 ) forceU = false;
19719
19720 var s = this.source;
19721 var l = s.length;
19722 if (i >= l) {
19723 return l
19724 }
19725 var c = s.charCodeAt(i), next;
19726 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
19727 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
19728 return i + 1
19729 }
19730 return i + 2
19731};
19732
19733RegExpValidationState.prototype.current = function current (forceU) {
19734 if ( forceU === void 0 ) forceU = false;
19735
19736 return this.at(this.pos, forceU)
19737};
19738
19739RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
19740 if ( forceU === void 0 ) forceU = false;
19741
19742 return this.at(this.nextIndex(this.pos, forceU), forceU)
19743};
19744
19745RegExpValidationState.prototype.advance = function advance (forceU) {
19746 if ( forceU === void 0 ) forceU = false;
19747
19748 this.pos = this.nextIndex(this.pos, forceU);
19749};
19750
19751RegExpValidationState.prototype.eat = function eat (ch, forceU) {
19752 if ( forceU === void 0 ) forceU = false;
19753
19754 if (this.current(forceU) === ch) {
19755 this.advance(forceU);
19756 return true
19757 }
19758 return false
19759};
19760
19761/**
19762 * Validate the flags part of a given RegExpLiteral.
19763 *
19764 * @param {RegExpValidationState} state The state to validate RegExp.
19765 * @returns {void}
19766 */
19767pp$1.validateRegExpFlags = function(state) {
19768 var validFlags = state.validFlags;
19769 var flags = state.flags;
19770
19771 for (var i = 0; i < flags.length; i++) {
19772 var flag = flags.charAt(i);
19773 if (validFlags.indexOf(flag) === -1) {
19774 this.raise(state.start, "Invalid regular expression flag");
19775 }
19776 if (flags.indexOf(flag, i + 1) > -1) {
19777 this.raise(state.start, "Duplicate regular expression flag");
19778 }
19779 }
19780};
19781
19782/**
19783 * Validate the pattern part of a given RegExpLiteral.
19784 *
19785 * @param {RegExpValidationState} state The state to validate RegExp.
19786 * @returns {void}
19787 */
19788pp$1.validateRegExpPattern = function(state) {
19789 this.regexp_pattern(state);
19790
19791 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
19792 // parsing contains a |GroupName|, reparse with the goal symbol
19793 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
19794 // exception if _P_ did not conform to the grammar, if any elements of _P_
19795 // were not matched by the parse, or if any Early Error conditions exist.
19796 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
19797 state.switchN = true;
19798 this.regexp_pattern(state);
19799 }
19800};
19801
19802// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
19803pp$1.regexp_pattern = function(state) {
19804 state.pos = 0;
19805 state.lastIntValue = 0;
19806 state.lastStringValue = "";
19807 state.lastAssertionIsQuantifiable = false;
19808 state.numCapturingParens = 0;
19809 state.maxBackReference = 0;
19810 state.groupNames.length = 0;
19811 state.backReferenceNames.length = 0;
19812
19813 this.regexp_disjunction(state);
19814
19815 if (state.pos !== state.source.length) {
19816 // Make the same messages as V8.
19817 if (state.eat(0x29 /* ) */)) {
19818 state.raise("Unmatched ')'");
19819 }
19820 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
19821 state.raise("Lone quantifier brackets");
19822 }
19823 }
19824 if (state.maxBackReference > state.numCapturingParens) {
19825 state.raise("Invalid escape");
19826 }
19827 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
19828 var name = list[i];
19829
19830 if (state.groupNames.indexOf(name) === -1) {
19831 state.raise("Invalid named capture referenced");
19832 }
19833 }
19834};
19835
19836// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
19837pp$1.regexp_disjunction = function(state) {
19838 this.regexp_alternative(state);
19839 while (state.eat(0x7C /* | */)) {
19840 this.regexp_alternative(state);
19841 }
19842
19843 // Make the same message as V8.
19844 if (this.regexp_eatQuantifier(state, true)) {
19845 state.raise("Nothing to repeat");
19846 }
19847 if (state.eat(0x7B /* { */)) {
19848 state.raise("Lone quantifier brackets");
19849 }
19850};
19851
19852// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
19853pp$1.regexp_alternative = function(state) {
19854 while (state.pos < state.source.length && this.regexp_eatTerm(state))
19855 { }
19856};
19857
19858// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
19859pp$1.regexp_eatTerm = function(state) {
19860 if (this.regexp_eatAssertion(state)) {
19861 // Handle `QuantifiableAssertion Quantifier` alternative.
19862 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
19863 // is a QuantifiableAssertion.
19864 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
19865 // Make the same message as V8.
19866 if (state.switchU) {
19867 state.raise("Invalid quantifier");
19868 }
19869 }
19870 return true
19871 }
19872
19873 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
19874 this.regexp_eatQuantifier(state);
19875 return true
19876 }
19877
19878 return false
19879};
19880
19881// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
19882pp$1.regexp_eatAssertion = function(state) {
19883 var start = state.pos;
19884 state.lastAssertionIsQuantifiable = false;
19885
19886 // ^, $
19887 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
19888 return true
19889 }
19890
19891 // \b \B
19892 if (state.eat(0x5C /* \ */)) {
19893 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
19894 return true
19895 }
19896 state.pos = start;
19897 }
19898
19899 // Lookahead / Lookbehind
19900 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
19901 var lookbehind = false;
19902 if (this.options.ecmaVersion >= 9) {
19903 lookbehind = state.eat(0x3C /* < */);
19904 }
19905 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
19906 this.regexp_disjunction(state);
19907 if (!state.eat(0x29 /* ) */)) {
19908 state.raise("Unterminated group");
19909 }
19910 state.lastAssertionIsQuantifiable = !lookbehind;
19911 return true
19912 }
19913 }
19914
19915 state.pos = start;
19916 return false
19917};
19918
19919// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
19920pp$1.regexp_eatQuantifier = function(state, noError) {
19921 if ( noError === void 0 ) noError = false;
19922
19923 if (this.regexp_eatQuantifierPrefix(state, noError)) {
19924 state.eat(0x3F /* ? */);
19925 return true
19926 }
19927 return false
19928};
19929
19930// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
19931pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
19932 return (
19933 state.eat(0x2A /* * */) ||
19934 state.eat(0x2B /* + */) ||
19935 state.eat(0x3F /* ? */) ||
19936 this.regexp_eatBracedQuantifier(state, noError)
19937 )
19938};
19939pp$1.regexp_eatBracedQuantifier = function(state, noError) {
19940 var start = state.pos;
19941 if (state.eat(0x7B /* { */)) {
19942 var min = 0, max = -1;
19943 if (this.regexp_eatDecimalDigits(state)) {
19944 min = state.lastIntValue;
19945 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
19946 max = state.lastIntValue;
19947 }
19948 if (state.eat(0x7D /* } */)) {
19949 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
19950 if (max !== -1 && max < min && !noError) {
19951 state.raise("numbers out of order in {} quantifier");
19952 }
19953 return true
19954 }
19955 }
19956 if (state.switchU && !noError) {
19957 state.raise("Incomplete quantifier");
19958 }
19959 state.pos = start;
19960 }
19961 return false
19962};
19963
19964// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
19965pp$1.regexp_eatAtom = function(state) {
19966 return (
19967 this.regexp_eatPatternCharacters(state) ||
19968 state.eat(0x2E /* . */) ||
19969 this.regexp_eatReverseSolidusAtomEscape(state) ||
19970 this.regexp_eatCharacterClass(state) ||
19971 this.regexp_eatUncapturingGroup(state) ||
19972 this.regexp_eatCapturingGroup(state)
19973 )
19974};
19975pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
19976 var start = state.pos;
19977 if (state.eat(0x5C /* \ */)) {
19978 if (this.regexp_eatAtomEscape(state)) {
19979 return true
19980 }
19981 state.pos = start;
19982 }
19983 return false
19984};
19985pp$1.regexp_eatUncapturingGroup = function(state) {
19986 var start = state.pos;
19987 if (state.eat(0x28 /* ( */)) {
19988 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
19989 this.regexp_disjunction(state);
19990 if (state.eat(0x29 /* ) */)) {
19991 return true
19992 }
19993 state.raise("Unterminated group");
19994 }
19995 state.pos = start;
19996 }
19997 return false
19998};
19999pp$1.regexp_eatCapturingGroup = function(state) {
20000 if (state.eat(0x28 /* ( */)) {
20001 if (this.options.ecmaVersion >= 9) {
20002 this.regexp_groupSpecifier(state);
20003 } else if (state.current() === 0x3F /* ? */) {
20004 state.raise("Invalid group");
20005 }
20006 this.regexp_disjunction(state);
20007 if (state.eat(0x29 /* ) */)) {
20008 state.numCapturingParens += 1;
20009 return true
20010 }
20011 state.raise("Unterminated group");
20012 }
20013 return false
20014};
20015
20016// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
20017pp$1.regexp_eatExtendedAtom = function(state) {
20018 return (
20019 state.eat(0x2E /* . */) ||
20020 this.regexp_eatReverseSolidusAtomEscape(state) ||
20021 this.regexp_eatCharacterClass(state) ||
20022 this.regexp_eatUncapturingGroup(state) ||
20023 this.regexp_eatCapturingGroup(state) ||
20024 this.regexp_eatInvalidBracedQuantifier(state) ||
20025 this.regexp_eatExtendedPatternCharacter(state)
20026 )
20027};
20028
20029// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
20030pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
20031 if (this.regexp_eatBracedQuantifier(state, true)) {
20032 state.raise("Nothing to repeat");
20033 }
20034 return false
20035};
20036
20037// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
20038pp$1.regexp_eatSyntaxCharacter = function(state) {
20039 var ch = state.current();
20040 if (isSyntaxCharacter(ch)) {
20041 state.lastIntValue = ch;
20042 state.advance();
20043 return true
20044 }
20045 return false
20046};
20047function isSyntaxCharacter(ch) {
20048 return (
20049 ch === 0x24 /* $ */ ||
20050 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
20051 ch === 0x2E /* . */ ||
20052 ch === 0x3F /* ? */ ||
20053 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
20054 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
20055 )
20056}
20057
20058// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
20059// But eat eager.
20060pp$1.regexp_eatPatternCharacters = function(state) {
20061 var start = state.pos;
20062 var ch = 0;
20063 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
20064 state.advance();
20065 }
20066 return state.pos !== start
20067};
20068
20069// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
20070pp$1.regexp_eatExtendedPatternCharacter = function(state) {
20071 var ch = state.current();
20072 if (
20073 ch !== -1 &&
20074 ch !== 0x24 /* $ */ &&
20075 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
20076 ch !== 0x2E /* . */ &&
20077 ch !== 0x3F /* ? */ &&
20078 ch !== 0x5B /* [ */ &&
20079 ch !== 0x5E /* ^ */ &&
20080 ch !== 0x7C /* | */
20081 ) {
20082 state.advance();
20083 return true
20084 }
20085 return false
20086};
20087
20088// GroupSpecifier ::
20089// [empty]
20090// `?` GroupName
20091pp$1.regexp_groupSpecifier = function(state) {
20092 if (state.eat(0x3F /* ? */)) {
20093 if (this.regexp_eatGroupName(state)) {
20094 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
20095 state.raise("Duplicate capture group name");
20096 }
20097 state.groupNames.push(state.lastStringValue);
20098 return
20099 }
20100 state.raise("Invalid group");
20101 }
20102};
20103
20104// GroupName ::
20105// `<` RegExpIdentifierName `>`
20106// Note: this updates `state.lastStringValue` property with the eaten name.
20107pp$1.regexp_eatGroupName = function(state) {
20108 state.lastStringValue = "";
20109 if (state.eat(0x3C /* < */)) {
20110 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
20111 return true
20112 }
20113 state.raise("Invalid capture group name");
20114 }
20115 return false
20116};
20117
20118// RegExpIdentifierName ::
20119// RegExpIdentifierStart
20120// RegExpIdentifierName RegExpIdentifierPart
20121// Note: this updates `state.lastStringValue` property with the eaten name.
20122pp$1.regexp_eatRegExpIdentifierName = function(state) {
20123 state.lastStringValue = "";
20124 if (this.regexp_eatRegExpIdentifierStart(state)) {
20125 state.lastStringValue += codePointToString(state.lastIntValue);
20126 while (this.regexp_eatRegExpIdentifierPart(state)) {
20127 state.lastStringValue += codePointToString(state.lastIntValue);
20128 }
20129 return true
20130 }
20131 return false
20132};
20133
20134// RegExpIdentifierStart ::
20135// UnicodeIDStart
20136// `$`
20137// `_`
20138// `\` RegExpUnicodeEscapeSequence[+U]
20139pp$1.regexp_eatRegExpIdentifierStart = function(state) {
20140 var start = state.pos;
20141 var forceU = this.options.ecmaVersion >= 11;
20142 var ch = state.current(forceU);
20143 state.advance(forceU);
20144
20145 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20146 ch = state.lastIntValue;
20147 }
20148 if (isRegExpIdentifierStart(ch)) {
20149 state.lastIntValue = ch;
20150 return true
20151 }
20152
20153 state.pos = start;
20154 return false
20155};
20156function isRegExpIdentifierStart(ch) {
20157 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
20158}
20159
20160// RegExpIdentifierPart ::
20161// UnicodeIDContinue
20162// `$`
20163// `_`
20164// `\` RegExpUnicodeEscapeSequence[+U]
20165// <ZWNJ>
20166// <ZWJ>
20167pp$1.regexp_eatRegExpIdentifierPart = function(state) {
20168 var start = state.pos;
20169 var forceU = this.options.ecmaVersion >= 11;
20170 var ch = state.current(forceU);
20171 state.advance(forceU);
20172
20173 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20174 ch = state.lastIntValue;
20175 }
20176 if (isRegExpIdentifierPart(ch)) {
20177 state.lastIntValue = ch;
20178 return true
20179 }
20180
20181 state.pos = start;
20182 return false
20183};
20184function isRegExpIdentifierPart(ch) {
20185 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
20186}
20187
20188// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
20189pp$1.regexp_eatAtomEscape = function(state) {
20190 if (
20191 this.regexp_eatBackReference(state) ||
20192 this.regexp_eatCharacterClassEscape(state) ||
20193 this.regexp_eatCharacterEscape(state) ||
20194 (state.switchN && this.regexp_eatKGroupName(state))
20195 ) {
20196 return true
20197 }
20198 if (state.switchU) {
20199 // Make the same message as V8.
20200 if (state.current() === 0x63 /* c */) {
20201 state.raise("Invalid unicode escape");
20202 }
20203 state.raise("Invalid escape");
20204 }
20205 return false
20206};
20207pp$1.regexp_eatBackReference = function(state) {
20208 var start = state.pos;
20209 if (this.regexp_eatDecimalEscape(state)) {
20210 var n = state.lastIntValue;
20211 if (state.switchU) {
20212 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
20213 if (n > state.maxBackReference) {
20214 state.maxBackReference = n;
20215 }
20216 return true
20217 }
20218 if (n <= state.numCapturingParens) {
20219 return true
20220 }
20221 state.pos = start;
20222 }
20223 return false
20224};
20225pp$1.regexp_eatKGroupName = function(state) {
20226 if (state.eat(0x6B /* k */)) {
20227 if (this.regexp_eatGroupName(state)) {
20228 state.backReferenceNames.push(state.lastStringValue);
20229 return true
20230 }
20231 state.raise("Invalid named reference");
20232 }
20233 return false
20234};
20235
20236// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
20237pp$1.regexp_eatCharacterEscape = function(state) {
20238 return (
20239 this.regexp_eatControlEscape(state) ||
20240 this.regexp_eatCControlLetter(state) ||
20241 this.regexp_eatZero(state) ||
20242 this.regexp_eatHexEscapeSequence(state) ||
20243 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
20244 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
20245 this.regexp_eatIdentityEscape(state)
20246 )
20247};
20248pp$1.regexp_eatCControlLetter = function(state) {
20249 var start = state.pos;
20250 if (state.eat(0x63 /* c */)) {
20251 if (this.regexp_eatControlLetter(state)) {
20252 return true
20253 }
20254 state.pos = start;
20255 }
20256 return false
20257};
20258pp$1.regexp_eatZero = function(state) {
20259 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
20260 state.lastIntValue = 0;
20261 state.advance();
20262 return true
20263 }
20264 return false
20265};
20266
20267// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
20268pp$1.regexp_eatControlEscape = function(state) {
20269 var ch = state.current();
20270 if (ch === 0x74 /* t */) {
20271 state.lastIntValue = 0x09; /* \t */
20272 state.advance();
20273 return true
20274 }
20275 if (ch === 0x6E /* n */) {
20276 state.lastIntValue = 0x0A; /* \n */
20277 state.advance();
20278 return true
20279 }
20280 if (ch === 0x76 /* v */) {
20281 state.lastIntValue = 0x0B; /* \v */
20282 state.advance();
20283 return true
20284 }
20285 if (ch === 0x66 /* f */) {
20286 state.lastIntValue = 0x0C; /* \f */
20287 state.advance();
20288 return true
20289 }
20290 if (ch === 0x72 /* r */) {
20291 state.lastIntValue = 0x0D; /* \r */
20292 state.advance();
20293 return true
20294 }
20295 return false
20296};
20297
20298// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
20299pp$1.regexp_eatControlLetter = function(state) {
20300 var ch = state.current();
20301 if (isControlLetter(ch)) {
20302 state.lastIntValue = ch % 0x20;
20303 state.advance();
20304 return true
20305 }
20306 return false
20307};
20308function isControlLetter(ch) {
20309 return (
20310 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
20311 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
20312 )
20313}
20314
20315// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
20316pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
20317 if ( forceU === void 0 ) forceU = false;
20318
20319 var start = state.pos;
20320 var switchU = forceU || state.switchU;
20321
20322 if (state.eat(0x75 /* u */)) {
20323 if (this.regexp_eatFixedHexDigits(state, 4)) {
20324 var lead = state.lastIntValue;
20325 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
20326 var leadSurrogateEnd = state.pos;
20327 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
20328 var trail = state.lastIntValue;
20329 if (trail >= 0xDC00 && trail <= 0xDFFF) {
20330 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
20331 return true
20332 }
20333 }
20334 state.pos = leadSurrogateEnd;
20335 state.lastIntValue = lead;
20336 }
20337 return true
20338 }
20339 if (
20340 switchU &&
20341 state.eat(0x7B /* { */) &&
20342 this.regexp_eatHexDigits(state) &&
20343 state.eat(0x7D /* } */) &&
20344 isValidUnicode(state.lastIntValue)
20345 ) {
20346 return true
20347 }
20348 if (switchU) {
20349 state.raise("Invalid unicode escape");
20350 }
20351 state.pos = start;
20352 }
20353
20354 return false
20355};
20356function isValidUnicode(ch) {
20357 return ch >= 0 && ch <= 0x10FFFF
20358}
20359
20360// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
20361pp$1.regexp_eatIdentityEscape = function(state) {
20362 if (state.switchU) {
20363 if (this.regexp_eatSyntaxCharacter(state)) {
20364 return true
20365 }
20366 if (state.eat(0x2F /* / */)) {
20367 state.lastIntValue = 0x2F; /* / */
20368 return true
20369 }
20370 return false
20371 }
20372
20373 var ch = state.current();
20374 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
20375 state.lastIntValue = ch;
20376 state.advance();
20377 return true
20378 }
20379
20380 return false
20381};
20382
20383// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
20384pp$1.regexp_eatDecimalEscape = function(state) {
20385 state.lastIntValue = 0;
20386 var ch = state.current();
20387 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
20388 do {
20389 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20390 state.advance();
20391 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
20392 return true
20393 }
20394 return false
20395};
20396
20397// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
20398pp$1.regexp_eatCharacterClassEscape = function(state) {
20399 var ch = state.current();
20400
20401 if (isCharacterClassEscape(ch)) {
20402 state.lastIntValue = -1;
20403 state.advance();
20404 return true
20405 }
20406
20407 if (
20408 state.switchU &&
20409 this.options.ecmaVersion >= 9 &&
20410 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
20411 ) {
20412 state.lastIntValue = -1;
20413 state.advance();
20414 if (
20415 state.eat(0x7B /* { */) &&
20416 this.regexp_eatUnicodePropertyValueExpression(state) &&
20417 state.eat(0x7D /* } */)
20418 ) {
20419 return true
20420 }
20421 state.raise("Invalid property name");
20422 }
20423
20424 return false
20425};
20426function isCharacterClassEscape(ch) {
20427 return (
20428 ch === 0x64 /* d */ ||
20429 ch === 0x44 /* D */ ||
20430 ch === 0x73 /* s */ ||
20431 ch === 0x53 /* S */ ||
20432 ch === 0x77 /* w */ ||
20433 ch === 0x57 /* W */
20434 )
20435}
20436
20437// UnicodePropertyValueExpression ::
20438// UnicodePropertyName `=` UnicodePropertyValue
20439// LoneUnicodePropertyNameOrValue
20440pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
20441 var start = state.pos;
20442
20443 // UnicodePropertyName `=` UnicodePropertyValue
20444 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
20445 var name = state.lastStringValue;
20446 if (this.regexp_eatUnicodePropertyValue(state)) {
20447 var value = state.lastStringValue;
20448 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
20449 return true
20450 }
20451 }
20452 state.pos = start;
20453
20454 // LoneUnicodePropertyNameOrValue
20455 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
20456 var nameOrValue = state.lastStringValue;
20457 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
20458 return true
20459 }
20460 return false
20461};
20462pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
20463 if (!hasOwn(state.unicodeProperties.nonBinary, name))
20464 { state.raise("Invalid property name"); }
20465 if (!state.unicodeProperties.nonBinary[name].test(value))
20466 { state.raise("Invalid property value"); }
20467};
20468pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
20469 if (!state.unicodeProperties.binary.test(nameOrValue))
20470 { state.raise("Invalid property name"); }
20471};
20472
20473// UnicodePropertyName ::
20474// UnicodePropertyNameCharacters
20475pp$1.regexp_eatUnicodePropertyName = function(state) {
20476 var ch = 0;
20477 state.lastStringValue = "";
20478 while (isUnicodePropertyNameCharacter(ch = state.current())) {
20479 state.lastStringValue += codePointToString(ch);
20480 state.advance();
20481 }
20482 return state.lastStringValue !== ""
20483};
20484function isUnicodePropertyNameCharacter(ch) {
20485 return isControlLetter(ch) || ch === 0x5F /* _ */
20486}
20487
20488// UnicodePropertyValue ::
20489// UnicodePropertyValueCharacters
20490pp$1.regexp_eatUnicodePropertyValue = function(state) {
20491 var ch = 0;
20492 state.lastStringValue = "";
20493 while (isUnicodePropertyValueCharacter(ch = state.current())) {
20494 state.lastStringValue += codePointToString(ch);
20495 state.advance();
20496 }
20497 return state.lastStringValue !== ""
20498};
20499function isUnicodePropertyValueCharacter(ch) {
20500 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
20501}
20502
20503// LoneUnicodePropertyNameOrValue ::
20504// UnicodePropertyValueCharacters
20505pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
20506 return this.regexp_eatUnicodePropertyValue(state)
20507};
20508
20509// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
20510pp$1.regexp_eatCharacterClass = function(state) {
20511 if (state.eat(0x5B /* [ */)) {
20512 state.eat(0x5E /* ^ */);
20513 this.regexp_classRanges(state);
20514 if (state.eat(0x5D /* ] */)) {
20515 return true
20516 }
20517 // Unreachable since it threw "unterminated regular expression" error before.
20518 state.raise("Unterminated character class");
20519 }
20520 return false
20521};
20522
20523// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
20524// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
20525// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
20526pp$1.regexp_classRanges = function(state) {
20527 while (this.regexp_eatClassAtom(state)) {
20528 var left = state.lastIntValue;
20529 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
20530 var right = state.lastIntValue;
20531 if (state.switchU && (left === -1 || right === -1)) {
20532 state.raise("Invalid character class");
20533 }
20534 if (left !== -1 && right !== -1 && left > right) {
20535 state.raise("Range out of order in character class");
20536 }
20537 }
20538 }
20539};
20540
20541// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
20542// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
20543pp$1.regexp_eatClassAtom = function(state) {
20544 var start = state.pos;
20545
20546 if (state.eat(0x5C /* \ */)) {
20547 if (this.regexp_eatClassEscape(state)) {
20548 return true
20549 }
20550 if (state.switchU) {
20551 // Make the same message as V8.
20552 var ch$1 = state.current();
20553 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
20554 state.raise("Invalid class escape");
20555 }
20556 state.raise("Invalid escape");
20557 }
20558 state.pos = start;
20559 }
20560
20561 var ch = state.current();
20562 if (ch !== 0x5D /* ] */) {
20563 state.lastIntValue = ch;
20564 state.advance();
20565 return true
20566 }
20567
20568 return false
20569};
20570
20571// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
20572pp$1.regexp_eatClassEscape = function(state) {
20573 var start = state.pos;
20574
20575 if (state.eat(0x62 /* b */)) {
20576 state.lastIntValue = 0x08; /* <BS> */
20577 return true
20578 }
20579
20580 if (state.switchU && state.eat(0x2D /* - */)) {
20581 state.lastIntValue = 0x2D; /* - */
20582 return true
20583 }
20584
20585 if (!state.switchU && state.eat(0x63 /* c */)) {
20586 if (this.regexp_eatClassControlLetter(state)) {
20587 return true
20588 }
20589 state.pos = start;
20590 }
20591
20592 return (
20593 this.regexp_eatCharacterClassEscape(state) ||
20594 this.regexp_eatCharacterEscape(state)
20595 )
20596};
20597
20598// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
20599pp$1.regexp_eatClassControlLetter = function(state) {
20600 var ch = state.current();
20601 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
20602 state.lastIntValue = ch % 0x20;
20603 state.advance();
20604 return true
20605 }
20606 return false
20607};
20608
20609// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20610pp$1.regexp_eatHexEscapeSequence = function(state) {
20611 var start = state.pos;
20612 if (state.eat(0x78 /* x */)) {
20613 if (this.regexp_eatFixedHexDigits(state, 2)) {
20614 return true
20615 }
20616 if (state.switchU) {
20617 state.raise("Invalid escape");
20618 }
20619 state.pos = start;
20620 }
20621 return false
20622};
20623
20624// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
20625pp$1.regexp_eatDecimalDigits = function(state) {
20626 var start = state.pos;
20627 var ch = 0;
20628 state.lastIntValue = 0;
20629 while (isDecimalDigit(ch = state.current())) {
20630 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20631 state.advance();
20632 }
20633 return state.pos !== start
20634};
20635function isDecimalDigit(ch) {
20636 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
20637}
20638
20639// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
20640pp$1.regexp_eatHexDigits = function(state) {
20641 var start = state.pos;
20642 var ch = 0;
20643 state.lastIntValue = 0;
20644 while (isHexDigit(ch = state.current())) {
20645 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
20646 state.advance();
20647 }
20648 return state.pos !== start
20649};
20650function isHexDigit(ch) {
20651 return (
20652 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
20653 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
20654 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
20655 )
20656}
20657function hexToInt(ch) {
20658 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
20659 return 10 + (ch - 0x41 /* A */)
20660 }
20661 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
20662 return 10 + (ch - 0x61 /* a */)
20663 }
20664 return ch - 0x30 /* 0 */
20665}
20666
20667// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
20668// Allows only 0-377(octal) i.e. 0-255(decimal).
20669pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
20670 if (this.regexp_eatOctalDigit(state)) {
20671 var n1 = state.lastIntValue;
20672 if (this.regexp_eatOctalDigit(state)) {
20673 var n2 = state.lastIntValue;
20674 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
20675 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
20676 } else {
20677 state.lastIntValue = n1 * 8 + n2;
20678 }
20679 } else {
20680 state.lastIntValue = n1;
20681 }
20682 return true
20683 }
20684 return false
20685};
20686
20687// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
20688pp$1.regexp_eatOctalDigit = function(state) {
20689 var ch = state.current();
20690 if (isOctalDigit(ch)) {
20691 state.lastIntValue = ch - 0x30; /* 0 */
20692 state.advance();
20693 return true
20694 }
20695 state.lastIntValue = 0;
20696 return false
20697};
20698function isOctalDigit(ch) {
20699 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
20700}
20701
20702// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
20703// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
20704// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20705pp$1.regexp_eatFixedHexDigits = function(state, length) {
20706 var start = state.pos;
20707 state.lastIntValue = 0;
20708 for (var i = 0; i < length; ++i) {
20709 var ch = state.current();
20710 if (!isHexDigit(ch)) {
20711 state.pos = start;
20712 return false
20713 }
20714 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
20715 state.advance();
20716 }
20717 return true
20718};
20719
20720// Object type used to represent tokens. Note that normally, tokens
20721// simply exist as properties on the parser object. This is only
20722// used for the onToken callback and the external tokenizer.
20723
20724var Token = function Token(p) {
20725 this.type = p.type;
20726 this.value = p.value;
20727 this.start = p.start;
20728 this.end = p.end;
20729 if (p.options.locations)
20730 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
20731 if (p.options.ranges)
20732 { this.range = [p.start, p.end]; }
20733};
20734
20735// ## Tokenizer
20736
20737var pp = Parser.prototype;
20738
20739// Move to the next token
20740
20741pp.next = function(ignoreEscapeSequenceInKeyword) {
20742 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
20743 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
20744 if (this.options.onToken)
20745 { this.options.onToken(new Token(this)); }
20746
20747 this.lastTokEnd = this.end;
20748 this.lastTokStart = this.start;
20749 this.lastTokEndLoc = this.endLoc;
20750 this.lastTokStartLoc = this.startLoc;
20751 this.nextToken();
20752};
20753
20754pp.getToken = function() {
20755 this.next();
20756 return new Token(this)
20757};
20758
20759// If we're in an ES6 environment, make parsers iterable
20760if (typeof Symbol !== "undefined")
20761 { pp[Symbol.iterator] = function() {
20762 var this$1$1 = this;
20763
20764 return {
20765 next: function () {
20766 var token = this$1$1.getToken();
20767 return {
20768 done: token.type === types$1.eof,
20769 value: token
20770 }
20771 }
20772 }
20773 }; }
20774
20775// Toggle strict mode. Re-reads the next number or string to please
20776// pedantic tests (`"use strict"; 010;` should fail).
20777
20778// Read a single token, updating the parser object's token-related
20779// properties.
20780
20781pp.nextToken = function() {
20782 var curContext = this.curContext();
20783 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
20784
20785 this.start = this.pos;
20786 if (this.options.locations) { this.startLoc = this.curPosition(); }
20787 if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
20788
20789 if (curContext.override) { return curContext.override(this) }
20790 else { this.readToken(this.fullCharCodeAtPos()); }
20791};
20792
20793pp.readToken = function(code) {
20794 // Identifier or keyword. '\uXXXX' sequences are allowed in
20795 // identifiers, so '\' also dispatches to that.
20796 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
20797 { return this.readWord() }
20798
20799 return this.getTokenFromCode(code)
20800};
20801
20802pp.fullCharCodeAtPos = function() {
20803 var code = this.input.charCodeAt(this.pos);
20804 if (code <= 0xd7ff || code >= 0xdc00) { return code }
20805 var next = this.input.charCodeAt(this.pos + 1);
20806 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
20807};
20808
20809pp.skipBlockComment = function() {
20810 var startLoc = this.options.onComment && this.curPosition();
20811 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
20812 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
20813 this.pos = end + 2;
20814 if (this.options.locations) {
20815 for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
20816 ++this.curLine;
20817 pos = this.lineStart = nextBreak;
20818 }
20819 }
20820 if (this.options.onComment)
20821 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
20822 startLoc, this.curPosition()); }
20823};
20824
20825pp.skipLineComment = function(startSkip) {
20826 var start = this.pos;
20827 var startLoc = this.options.onComment && this.curPosition();
20828 var ch = this.input.charCodeAt(this.pos += startSkip);
20829 while (this.pos < this.input.length && !isNewLine(ch)) {
20830 ch = this.input.charCodeAt(++this.pos);
20831 }
20832 if (this.options.onComment)
20833 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
20834 startLoc, this.curPosition()); }
20835};
20836
20837// Called at the start of the parse and after every token. Skips
20838// whitespace and comments, and.
20839
20840pp.skipSpace = function() {
20841 loop: while (this.pos < this.input.length) {
20842 var ch = this.input.charCodeAt(this.pos);
20843 switch (ch) {
20844 case 32: case 160: // ' '
20845 ++this.pos;
20846 break
20847 case 13:
20848 if (this.input.charCodeAt(this.pos + 1) === 10) {
20849 ++this.pos;
20850 }
20851 case 10: case 8232: case 8233:
20852 ++this.pos;
20853 if (this.options.locations) {
20854 ++this.curLine;
20855 this.lineStart = this.pos;
20856 }
20857 break
20858 case 47: // '/'
20859 switch (this.input.charCodeAt(this.pos + 1)) {
20860 case 42: // '*'
20861 this.skipBlockComment();
20862 break
20863 case 47:
20864 this.skipLineComment(2);
20865 break
20866 default:
20867 break loop
20868 }
20869 break
20870 default:
20871 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
20872 ++this.pos;
20873 } else {
20874 break loop
20875 }
20876 }
20877 }
20878};
20879
20880// Called at the end of every token. Sets `end`, `val`, and
20881// maintains `context` and `exprAllowed`, and skips the space after
20882// the token, so that the next one's `start` will point at the
20883// right position.
20884
20885pp.finishToken = function(type, val) {
20886 this.end = this.pos;
20887 if (this.options.locations) { this.endLoc = this.curPosition(); }
20888 var prevType = this.type;
20889 this.type = type;
20890 this.value = val;
20891
20892 this.updateContext(prevType);
20893};
20894
20895// ### Token reading
20896
20897// This is the function that is called to fetch the next token. It
20898// is somewhat obscure, because it works in character codes rather
20899// than characters, and because operator parsing has been inlined
20900// into it.
20901//
20902// All in the name of speed.
20903//
20904pp.readToken_dot = function() {
20905 var next = this.input.charCodeAt(this.pos + 1);
20906 if (next >= 48 && next <= 57) { return this.readNumber(true) }
20907 var next2 = this.input.charCodeAt(this.pos + 2);
20908 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
20909 this.pos += 3;
20910 return this.finishToken(types$1.ellipsis)
20911 } else {
20912 ++this.pos;
20913 return this.finishToken(types$1.dot)
20914 }
20915};
20916
20917pp.readToken_slash = function() { // '/'
20918 var next = this.input.charCodeAt(this.pos + 1);
20919 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
20920 if (next === 61) { return this.finishOp(types$1.assign, 2) }
20921 return this.finishOp(types$1.slash, 1)
20922};
20923
20924pp.readToken_mult_modulo_exp = function(code) { // '%*'
20925 var next = this.input.charCodeAt(this.pos + 1);
20926 var size = 1;
20927 var tokentype = code === 42 ? types$1.star : types$1.modulo;
20928
20929 // exponentiation operator ** and **=
20930 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
20931 ++size;
20932 tokentype = types$1.starstar;
20933 next = this.input.charCodeAt(this.pos + 2);
20934 }
20935
20936 if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
20937 return this.finishOp(tokentype, size)
20938};
20939
20940pp.readToken_pipe_amp = function(code) { // '|&'
20941 var next = this.input.charCodeAt(this.pos + 1);
20942 if (next === code) {
20943 if (this.options.ecmaVersion >= 12) {
20944 var next2 = this.input.charCodeAt(this.pos + 2);
20945 if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
20946 }
20947 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
20948 }
20949 if (next === 61) { return this.finishOp(types$1.assign, 2) }
20950 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
20951};
20952
20953pp.readToken_caret = function() { // '^'
20954 var next = this.input.charCodeAt(this.pos + 1);
20955 if (next === 61) { return this.finishOp(types$1.assign, 2) }
20956 return this.finishOp(types$1.bitwiseXOR, 1)
20957};
20958
20959pp.readToken_plus_min = function(code) { // '+-'
20960 var next = this.input.charCodeAt(this.pos + 1);
20961 if (next === code) {
20962 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
20963 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
20964 // A `-->` line comment
20965 this.skipLineComment(3);
20966 this.skipSpace();
20967 return this.nextToken()
20968 }
20969 return this.finishOp(types$1.incDec, 2)
20970 }
20971 if (next === 61) { return this.finishOp(types$1.assign, 2) }
20972 return this.finishOp(types$1.plusMin, 1)
20973};
20974
20975pp.readToken_lt_gt = function(code) { // '<>'
20976 var next = this.input.charCodeAt(this.pos + 1);
20977 var size = 1;
20978 if (next === code) {
20979 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
20980 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
20981 return this.finishOp(types$1.bitShift, size)
20982 }
20983 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
20984 this.input.charCodeAt(this.pos + 3) === 45) {
20985 // `<!--`, an XML-style comment that should be interpreted as a line comment
20986 this.skipLineComment(4);
20987 this.skipSpace();
20988 return this.nextToken()
20989 }
20990 if (next === 61) { size = 2; }
20991 return this.finishOp(types$1.relational, size)
20992};
20993
20994pp.readToken_eq_excl = function(code) { // '=!'
20995 var next = this.input.charCodeAt(this.pos + 1);
20996 if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
20997 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
20998 this.pos += 2;
20999 return this.finishToken(types$1.arrow)
21000 }
21001 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
21002};
21003
21004pp.readToken_question = function() { // '?'
21005 var ecmaVersion = this.options.ecmaVersion;
21006 if (ecmaVersion >= 11) {
21007 var next = this.input.charCodeAt(this.pos + 1);
21008 if (next === 46) {
21009 var next2 = this.input.charCodeAt(this.pos + 2);
21010 if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
21011 }
21012 if (next === 63) {
21013 if (ecmaVersion >= 12) {
21014 var next2$1 = this.input.charCodeAt(this.pos + 2);
21015 if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
21016 }
21017 return this.finishOp(types$1.coalesce, 2)
21018 }
21019 }
21020 return this.finishOp(types$1.question, 1)
21021};
21022
21023pp.readToken_numberSign = function() { // '#'
21024 var ecmaVersion = this.options.ecmaVersion;
21025 var code = 35; // '#'
21026 if (ecmaVersion >= 13) {
21027 ++this.pos;
21028 code = this.fullCharCodeAtPos();
21029 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
21030 return this.finishToken(types$1.privateId, this.readWord1())
21031 }
21032 }
21033
21034 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21035};
21036
21037pp.getTokenFromCode = function(code) {
21038 switch (code) {
21039 // The interpretation of a dot depends on whether it is followed
21040 // by a digit or another two dots.
21041 case 46: // '.'
21042 return this.readToken_dot()
21043
21044 // Punctuation tokens.
21045 case 40: ++this.pos; return this.finishToken(types$1.parenL)
21046 case 41: ++this.pos; return this.finishToken(types$1.parenR)
21047 case 59: ++this.pos; return this.finishToken(types$1.semi)
21048 case 44: ++this.pos; return this.finishToken(types$1.comma)
21049 case 91: ++this.pos; return this.finishToken(types$1.bracketL)
21050 case 93: ++this.pos; return this.finishToken(types$1.bracketR)
21051 case 123: ++this.pos; return this.finishToken(types$1.braceL)
21052 case 125: ++this.pos; return this.finishToken(types$1.braceR)
21053 case 58: ++this.pos; return this.finishToken(types$1.colon)
21054
21055 case 96: // '`'
21056 if (this.options.ecmaVersion < 6) { break }
21057 ++this.pos;
21058 return this.finishToken(types$1.backQuote)
21059
21060 case 48: // '0'
21061 var next = this.input.charCodeAt(this.pos + 1);
21062 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
21063 if (this.options.ecmaVersion >= 6) {
21064 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
21065 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
21066 }
21067
21068 // Anything else beginning with a digit is an integer, octal
21069 // number, or float.
21070 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
21071 return this.readNumber(false)
21072
21073 // Quotes produce strings.
21074 case 34: case 39: // '"', "'"
21075 return this.readString(code)
21076
21077 // Operators are parsed inline in tiny state machines. '=' (61) is
21078 // often referred to. `finishOp` simply skips the amount of
21079 // characters it is given as second argument, and returns a token
21080 // of the type given by its first argument.
21081 case 47: // '/'
21082 return this.readToken_slash()
21083
21084 case 37: case 42: // '%*'
21085 return this.readToken_mult_modulo_exp(code)
21086
21087 case 124: case 38: // '|&'
21088 return this.readToken_pipe_amp(code)
21089
21090 case 94: // '^'
21091 return this.readToken_caret()
21092
21093 case 43: case 45: // '+-'
21094 return this.readToken_plus_min(code)
21095
21096 case 60: case 62: // '<>'
21097 return this.readToken_lt_gt(code)
21098
21099 case 61: case 33: // '=!'
21100 return this.readToken_eq_excl(code)
21101
21102 case 63: // '?'
21103 return this.readToken_question()
21104
21105 case 126: // '~'
21106 return this.finishOp(types$1.prefix, 1)
21107
21108 case 35: // '#'
21109 return this.readToken_numberSign()
21110 }
21111
21112 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21113};
21114
21115pp.finishOp = function(type, size) {
21116 var str = this.input.slice(this.pos, this.pos + size);
21117 this.pos += size;
21118 return this.finishToken(type, str)
21119};
21120
21121pp.readRegexp = function() {
21122 var escaped, inClass, start = this.pos;
21123 for (;;) {
21124 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
21125 var ch = this.input.charAt(this.pos);
21126 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
21127 if (!escaped) {
21128 if (ch === "[") { inClass = true; }
21129 else if (ch === "]" && inClass) { inClass = false; }
21130 else if (ch === "/" && !inClass) { break }
21131 escaped = ch === "\\";
21132 } else { escaped = false; }
21133 ++this.pos;
21134 }
21135 var pattern = this.input.slice(start, this.pos);
21136 ++this.pos;
21137 var flagsStart = this.pos;
21138 var flags = this.readWord1();
21139 if (this.containsEsc) { this.unexpected(flagsStart); }
21140
21141 // Validate pattern
21142 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
21143 state.reset(start, pattern, flags);
21144 this.validateRegExpFlags(state);
21145 this.validateRegExpPattern(state);
21146
21147 // Create Literal#value property value.
21148 var value = null;
21149 try {
21150 value = new RegExp(pattern, flags);
21151 } catch (e) {
21152 // ESTree requires null if it failed to instantiate RegExp object.
21153 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
21154 }
21155
21156 return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
21157};
21158
21159// Read an integer in the given radix. Return null if zero digits
21160// were read, the integer value otherwise. When `len` is given, this
21161// will return `null` unless the integer has exactly `len` digits.
21162
21163pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
21164 // `len` is used for character escape sequences. In that case, disallow separators.
21165 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
21166
21167 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
21168 // and isn't fraction part nor exponent part. In that case, if the first digit
21169 // is zero then disallow separators.
21170 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
21171
21172 var start = this.pos, total = 0, lastCode = 0;
21173 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
21174 var code = this.input.charCodeAt(this.pos), val = (void 0);
21175
21176 if (allowSeparators && code === 95) {
21177 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
21178 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
21179 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
21180 lastCode = code;
21181 continue
21182 }
21183
21184 if (code >= 97) { val = code - 97 + 10; } // a
21185 else if (code >= 65) { val = code - 65 + 10; } // A
21186 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
21187 else { val = Infinity; }
21188 if (val >= radix) { break }
21189 lastCode = code;
21190 total = total * radix + val;
21191 }
21192
21193 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
21194 if (this.pos === start || len != null && this.pos - start !== len) { return null }
21195
21196 return total
21197};
21198
21199function stringToNumber(str, isLegacyOctalNumericLiteral) {
21200 if (isLegacyOctalNumericLiteral) {
21201 return parseInt(str, 8)
21202 }
21203
21204 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
21205 return parseFloat(str.replace(/_/g, ""))
21206}
21207
21208function stringToBigInt(str) {
21209 if (typeof BigInt !== "function") {
21210 return null
21211 }
21212
21213 // `BigInt(value)` throws syntax error if the string contains numeric separators.
21214 return BigInt(str.replace(/_/g, ""))
21215}
21216
21217pp.readRadixNumber = function(radix) {
21218 var start = this.pos;
21219 this.pos += 2; // 0x
21220 var val = this.readInt(radix);
21221 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
21222 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
21223 val = stringToBigInt(this.input.slice(start, this.pos));
21224 ++this.pos;
21225 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21226 return this.finishToken(types$1.num, val)
21227};
21228
21229// Read an integer, octal integer, or floating-point number.
21230
21231pp.readNumber = function(startsWithDot) {
21232 var start = this.pos;
21233 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
21234 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
21235 if (octal && this.strict) { this.raise(start, "Invalid number"); }
21236 var next = this.input.charCodeAt(this.pos);
21237 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
21238 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
21239 ++this.pos;
21240 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21241 return this.finishToken(types$1.num, val$1)
21242 }
21243 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
21244 if (next === 46 && !octal) { // '.'
21245 ++this.pos;
21246 this.readInt(10);
21247 next = this.input.charCodeAt(this.pos);
21248 }
21249 if ((next === 69 || next === 101) && !octal) { // 'eE'
21250 next = this.input.charCodeAt(++this.pos);
21251 if (next === 43 || next === 45) { ++this.pos; } // '+-'
21252 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
21253 }
21254 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21255
21256 var val = stringToNumber(this.input.slice(start, this.pos), octal);
21257 return this.finishToken(types$1.num, val)
21258};
21259
21260// Read a string value, interpreting backslash-escapes.
21261
21262pp.readCodePoint = function() {
21263 var ch = this.input.charCodeAt(this.pos), code;
21264
21265 if (ch === 123) { // '{'
21266 if (this.options.ecmaVersion < 6) { this.unexpected(); }
21267 var codePos = ++this.pos;
21268 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
21269 ++this.pos;
21270 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
21271 } else {
21272 code = this.readHexChar(4);
21273 }
21274 return code
21275};
21276
21277pp.readString = function(quote) {
21278 var out = "", chunkStart = ++this.pos;
21279 for (;;) {
21280 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
21281 var ch = this.input.charCodeAt(this.pos);
21282 if (ch === quote) { break }
21283 if (ch === 92) { // '\'
21284 out += this.input.slice(chunkStart, this.pos);
21285 out += this.readEscapedChar(false);
21286 chunkStart = this.pos;
21287 } else if (ch === 0x2028 || ch === 0x2029) {
21288 if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
21289 ++this.pos;
21290 if (this.options.locations) {
21291 this.curLine++;
21292 this.lineStart = this.pos;
21293 }
21294 } else {
21295 if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
21296 ++this.pos;
21297 }
21298 }
21299 out += this.input.slice(chunkStart, this.pos++);
21300 return this.finishToken(types$1.string, out)
21301};
21302
21303// Reads template string tokens.
21304
21305var INVALID_TEMPLATE_ESCAPE_ERROR = {};
21306
21307pp.tryReadTemplateToken = function() {
21308 this.inTemplateElement = true;
21309 try {
21310 this.readTmplToken();
21311 } catch (err) {
21312 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
21313 this.readInvalidTemplateToken();
21314 } else {
21315 throw err
21316 }
21317 }
21318
21319 this.inTemplateElement = false;
21320};
21321
21322pp.invalidStringToken = function(position, message) {
21323 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
21324 throw INVALID_TEMPLATE_ESCAPE_ERROR
21325 } else {
21326 this.raise(position, message);
21327 }
21328};
21329
21330pp.readTmplToken = function() {
21331 var out = "", chunkStart = this.pos;
21332 for (;;) {
21333 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
21334 var ch = this.input.charCodeAt(this.pos);
21335 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
21336 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
21337 if (ch === 36) {
21338 this.pos += 2;
21339 return this.finishToken(types$1.dollarBraceL)
21340 } else {
21341 ++this.pos;
21342 return this.finishToken(types$1.backQuote)
21343 }
21344 }
21345 out += this.input.slice(chunkStart, this.pos);
21346 return this.finishToken(types$1.template, out)
21347 }
21348 if (ch === 92) { // '\'
21349 out += this.input.slice(chunkStart, this.pos);
21350 out += this.readEscapedChar(true);
21351 chunkStart = this.pos;
21352 } else if (isNewLine(ch)) {
21353 out += this.input.slice(chunkStart, this.pos);
21354 ++this.pos;
21355 switch (ch) {
21356 case 13:
21357 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
21358 case 10:
21359 out += "\n";
21360 break
21361 default:
21362 out += String.fromCharCode(ch);
21363 break
21364 }
21365 if (this.options.locations) {
21366 ++this.curLine;
21367 this.lineStart = this.pos;
21368 }
21369 chunkStart = this.pos;
21370 } else {
21371 ++this.pos;
21372 }
21373 }
21374};
21375
21376// Reads a template token to search for the end, without validating any escape sequences
21377pp.readInvalidTemplateToken = function() {
21378 for (; this.pos < this.input.length; this.pos++) {
21379 switch (this.input[this.pos]) {
21380 case "\\":
21381 ++this.pos;
21382 break
21383
21384 case "$":
21385 if (this.input[this.pos + 1] !== "{") {
21386 break
21387 }
21388
21389 // falls through
21390 case "`":
21391 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
21392
21393 // no default
21394 }
21395 }
21396 this.raise(this.start, "Unterminated template");
21397};
21398
21399// Used to read escaped characters
21400
21401pp.readEscapedChar = function(inTemplate) {
21402 var ch = this.input.charCodeAt(++this.pos);
21403 ++this.pos;
21404 switch (ch) {
21405 case 110: return "\n" // 'n' -> '\n'
21406 case 114: return "\r" // 'r' -> '\r'
21407 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
21408 case 117: return codePointToString(this.readCodePoint()) // 'u'
21409 case 116: return "\t" // 't' -> '\t'
21410 case 98: return "\b" // 'b' -> '\b'
21411 case 118: return "\u000b" // 'v' -> '\u000b'
21412 case 102: return "\f" // 'f' -> '\f'
21413 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
21414 case 10: // ' \n'
21415 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
21416 return ""
21417 case 56:
21418 case 57:
21419 if (this.strict) {
21420 this.invalidStringToken(
21421 this.pos - 1,
21422 "Invalid escape sequence"
21423 );
21424 }
21425 if (inTemplate) {
21426 var codePos = this.pos - 1;
21427
21428 this.invalidStringToken(
21429 codePos,
21430 "Invalid escape sequence in template string"
21431 );
21432
21433 return null
21434 }
21435 default:
21436 if (ch >= 48 && ch <= 55) {
21437 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
21438 var octal = parseInt(octalStr, 8);
21439 if (octal > 255) {
21440 octalStr = octalStr.slice(0, -1);
21441 octal = parseInt(octalStr, 8);
21442 }
21443 this.pos += octalStr.length - 1;
21444 ch = this.input.charCodeAt(this.pos);
21445 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
21446 this.invalidStringToken(
21447 this.pos - 1 - octalStr.length,
21448 inTemplate
21449 ? "Octal literal in template string"
21450 : "Octal literal in strict mode"
21451 );
21452 }
21453 return String.fromCharCode(octal)
21454 }
21455 if (isNewLine(ch)) {
21456 // Unicode new line characters after \ get removed from output in both
21457 // template literals and strings
21458 return ""
21459 }
21460 return String.fromCharCode(ch)
21461 }
21462};
21463
21464// Used to read character escape sequences ('\x', '\u', '\U').
21465
21466pp.readHexChar = function(len) {
21467 var codePos = this.pos;
21468 var n = this.readInt(16, len);
21469 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
21470 return n
21471};
21472
21473// Read an identifier, and return it as a string. Sets `this.containsEsc`
21474// to whether the word contained a '\u' escape.
21475//
21476// Incrementally adds only escaped chars, adding other chunks as-is
21477// as a micro-optimization.
21478
21479pp.readWord1 = function() {
21480 this.containsEsc = false;
21481 var word = "", first = true, chunkStart = this.pos;
21482 var astral = this.options.ecmaVersion >= 6;
21483 while (this.pos < this.input.length) {
21484 var ch = this.fullCharCodeAtPos();
21485 if (isIdentifierChar(ch, astral)) {
21486 this.pos += ch <= 0xffff ? 1 : 2;
21487 } else if (ch === 92) { // "\"
21488 this.containsEsc = true;
21489 word += this.input.slice(chunkStart, this.pos);
21490 var escStart = this.pos;
21491 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
21492 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
21493 ++this.pos;
21494 var esc = this.readCodePoint();
21495 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
21496 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
21497 word += codePointToString(esc);
21498 chunkStart = this.pos;
21499 } else {
21500 break
21501 }
21502 first = false;
21503 }
21504 return word + this.input.slice(chunkStart, this.pos)
21505};
21506
21507// Read an identifier or keyword token. Will check for reserved
21508// words when necessary.
21509
21510pp.readWord = function() {
21511 var word = this.readWord1();
21512 var type = types$1.name;
21513 if (this.keywords.test(word)) {
21514 type = keywords[word];
21515 }
21516 return this.finishToken(type, word)
21517};
21518
21519// Acorn is a tiny, fast JavaScript parser written in JavaScript.
21520
21521var version = "8.7.1";
21522
21523Parser.acorn = {
21524 Parser: Parser,
21525 version: version,
21526 defaultOptions: defaultOptions,
21527 Position: Position,
21528 SourceLocation: SourceLocation,
21529 getLineInfo: getLineInfo,
21530 Node: Node,
21531 TokenType: TokenType,
21532 tokTypes: types$1,
21533 keywordTypes: keywords,
21534 TokContext: TokContext,
21535 tokContexts: types,
21536 isIdentifierChar: isIdentifierChar,
21537 isIdentifierStart: isIdentifierStart,
21538 Token: Token,
21539 isNewLine: isNewLine,
21540 lineBreak: lineBreak,
21541 lineBreakG: lineBreakG,
21542 nonASCIIwhitespace: nonASCIIwhitespace
21543};
21544
21545function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21546 let skipped = null;
21547 let replaceContext = null;
21548 if (skip) {
21549 skipped = new Set();
21550 for (const skippedCall of skip) {
21551 if (source === skippedCall.source && importer === skippedCall.importer) {
21552 skipped.add(skippedCall.plugin);
21553 }
21554 }
21555 replaceContext = (pluginContext, plugin) => ({
21556 ...pluginContext,
21557 resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
21558 return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
21559 }
21560 });
21561 }
21562 return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
21563}
21564
21565async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21566 const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
21567 if (pluginResult != null)
21568 return pluginResult;
21569 // external modules (non-entry modules that start with neither '.' or '/')
21570 // are skipped at this stage.
21571 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
21572 return null;
21573 // `resolve` processes paths from right to left, prepending them until an
21574 // absolute path is created. Absolute importees therefore shortcircuit the
21575 // resolve call and require no special handing on our part.
21576 // See https://nodejs.org/api/path.html#path_path_resolve_paths
21577 return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
21578}
21579async function addJsExtensionIfNecessary(file, preserveSymlinks) {
21580 var _a, _b;
21581 return ((_b = (_a = (await findFile(file, preserveSymlinks))) !== null && _a !== void 0 ? _a : (await findFile(file + '.mjs', preserveSymlinks))) !== null && _b !== void 0 ? _b : (await findFile(file + '.js', preserveSymlinks)));
21582}
21583async function findFile(file, preserveSymlinks) {
21584 try {
21585 const stats = await promises.lstat(file);
21586 if (!preserveSymlinks && stats.isSymbolicLink())
21587 return await findFile(await promises.realpath(file), preserveSymlinks);
21588 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
21589 // check case
21590 const name = basename(file);
21591 const files = await promises.readdir(dirname(file));
21592 if (files.includes(name))
21593 return file;
21594 }
21595 }
21596 catch (_a) {
21597 // suppress
21598 }
21599}
21600
21601const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
21602const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
21603function throwPluginError(err, plugin, { hook, id } = {}) {
21604 if (typeof err === 'string')
21605 err = { message: err };
21606 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
21607 err.pluginCode = err.code;
21608 }
21609 err.code = Errors.PLUGIN_ERROR;
21610 err.plugin = plugin;
21611 if (hook) {
21612 err.hook = hook;
21613 }
21614 if (id) {
21615 err.id = id;
21616 }
21617 return error(err);
21618}
21619const deprecatedHooks = [
21620 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
21621];
21622function warnDeprecatedHooks(plugins, options) {
21623 for (const { active, deprecated, replacement } of deprecatedHooks) {
21624 for (const plugin of plugins) {
21625 if (deprecated in plugin) {
21626 warnDeprecation({
21627 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
21628 plugin: plugin.name
21629 }, active, options);
21630 }
21631 }
21632 }
21633}
21634
21635function createPluginCache(cache) {
21636 return {
21637 delete(id) {
21638 return delete cache[id];
21639 },
21640 get(id) {
21641 const item = cache[id];
21642 if (!item)
21643 return undefined;
21644 item[0] = 0;
21645 return item[1];
21646 },
21647 has(id) {
21648 const item = cache[id];
21649 if (!item)
21650 return false;
21651 item[0] = 0;
21652 return true;
21653 },
21654 set(id, value) {
21655 cache[id] = [0, value];
21656 }
21657 };
21658}
21659function getTrackedPluginCache(pluginCache, onUse) {
21660 return {
21661 delete(id) {
21662 onUse();
21663 return pluginCache.delete(id);
21664 },
21665 get(id) {
21666 onUse();
21667 return pluginCache.get(id);
21668 },
21669 has(id) {
21670 onUse();
21671 return pluginCache.has(id);
21672 },
21673 set(id, value) {
21674 onUse();
21675 return pluginCache.set(id, value);
21676 }
21677 };
21678}
21679const NO_CACHE = {
21680 delete() {
21681 return false;
21682 },
21683 get() {
21684 return undefined;
21685 },
21686 has() {
21687 return false;
21688 },
21689 set() { }
21690};
21691function uncacheablePluginError(pluginName) {
21692 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
21693 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
21694 return error({
21695 code: 'ANONYMOUS_PLUGIN_CACHE',
21696 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
21697 });
21698 }
21699 return error({
21700 code: 'DUPLICATE_PLUGIN_NAME',
21701 message: `The plugin name ${pluginName} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
21702 });
21703}
21704function getCacheForUncacheablePlugin(pluginName) {
21705 return {
21706 delete() {
21707 return uncacheablePluginError(pluginName);
21708 },
21709 get() {
21710 return uncacheablePluginError(pluginName);
21711 },
21712 has() {
21713 return uncacheablePluginError(pluginName);
21714 },
21715 set() {
21716 return uncacheablePluginError(pluginName);
21717 }
21718 };
21719}
21720
21721async function transform(source, module, pluginDriver, warn) {
21722 const id = module.id;
21723 const sourcemapChain = [];
21724 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
21725 const originalCode = source.code;
21726 let ast = source.ast;
21727 const transformDependencies = [];
21728 const emittedFiles = [];
21729 let customTransformCache = false;
21730 const useCustomTransformCache = () => (customTransformCache = true);
21731 let pluginName = '';
21732 const curSource = source.code;
21733 function transformReducer(previousCode, result, plugin) {
21734 let code;
21735 let map;
21736 if (typeof result === 'string') {
21737 code = result;
21738 }
21739 else if (result && typeof result === 'object') {
21740 module.updateOptions(result);
21741 if (result.code == null) {
21742 if (result.map || result.ast) {
21743 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
21744 }
21745 return previousCode;
21746 }
21747 ({ code, map, ast } = result);
21748 }
21749 else {
21750 return previousCode;
21751 }
21752 // strict null check allows 'null' maps to not be pushed to the chain,
21753 // while 'undefined' gets the missing map warning
21754 if (map !== null) {
21755 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
21756 missing: true,
21757 plugin: plugin.name
21758 });
21759 }
21760 return code;
21761 }
21762 let code;
21763 try {
21764 code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
21765 pluginName = plugin.name;
21766 return {
21767 ...pluginContext,
21768 addWatchFile(id) {
21769 transformDependencies.push(id);
21770 pluginContext.addWatchFile(id);
21771 },
21772 cache: customTransformCache
21773 ? pluginContext.cache
21774 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
21775 emitAsset(name, source) {
21776 emittedFiles.push({ name, source, type: 'asset' });
21777 return pluginContext.emitAsset(name, source);
21778 },
21779 emitChunk(id, options) {
21780 emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
21781 return pluginContext.emitChunk(id, options);
21782 },
21783 emitFile(emittedFile) {
21784 emittedFiles.push(emittedFile);
21785 return pluginDriver.emitFile(emittedFile);
21786 },
21787 error(err, pos) {
21788 if (typeof err === 'string')
21789 err = { message: err };
21790 if (pos)
21791 augmentCodeLocation(err, pos, curSource, id);
21792 err.id = id;
21793 err.hook = 'transform';
21794 return pluginContext.error(err);
21795 },
21796 getCombinedSourcemap() {
21797 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
21798 if (!combinedMap) {
21799 const magicString = new MagicString(originalCode);
21800 return magicString.generateMap({ hires: true, includeContent: true, source: id });
21801 }
21802 if (originalSourcemap !== combinedMap) {
21803 originalSourcemap = combinedMap;
21804 sourcemapChain.length = 0;
21805 }
21806 return new SourceMap({
21807 ...combinedMap,
21808 file: null,
21809 sourcesContent: combinedMap.sourcesContent
21810 });
21811 },
21812 setAssetSource() {
21813 return this.error({
21814 code: 'INVALID_SETASSETSOURCE',
21815 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
21816 });
21817 },
21818 warn(warning, pos) {
21819 if (typeof warning === 'string')
21820 warning = { message: warning };
21821 if (pos)
21822 augmentCodeLocation(warning, pos, curSource, id);
21823 warning.id = id;
21824 warning.hook = 'transform';
21825 pluginContext.warn(warning);
21826 }
21827 };
21828 });
21829 }
21830 catch (err) {
21831 throwPluginError(err, pluginName, { hook: 'transform', id });
21832 }
21833 if (!customTransformCache) {
21834 // files emitted by a transform hook need to be emitted again if the hook is skipped
21835 if (emittedFiles.length)
21836 module.transformFiles = emittedFiles;
21837 }
21838 return {
21839 ast,
21840 code,
21841 customTransformCache,
21842 originalCode,
21843 originalSourcemap,
21844 sourcemapChain,
21845 transformDependencies
21846 };
21847}
21848
21849const RESOLVE_DEPENDENCIES = 'resolveDependencies';
21850class ModuleLoader {
21851 constructor(graph, modulesById, options, pluginDriver) {
21852 this.graph = graph;
21853 this.modulesById = modulesById;
21854 this.options = options;
21855 this.pluginDriver = pluginDriver;
21856 this.implicitEntryModules = new Set();
21857 this.indexedEntryModules = [];
21858 this.latestLoadModulesPromise = Promise.resolve();
21859 this.moduleLoadPromises = new Map();
21860 this.modulesWithLoadedDependencies = new Set();
21861 this.nextChunkNamePriority = 0;
21862 this.nextEntryModuleIndex = 0;
21863 this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
21864 return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
21865 ? false
21866 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
21867 };
21868 this.hasModuleSideEffects = options.treeshake
21869 ? options.treeshake.moduleSideEffects
21870 : () => true;
21871 }
21872 async addAdditionalModules(unresolvedModules) {
21873 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
21874 await this.awaitLoadModulesPromise();
21875 return result;
21876 }
21877 async addEntryModules(unresolvedEntryModules, isUserDefined) {
21878 const firstEntryModuleIndex = this.nextEntryModuleIndex;
21879 this.nextEntryModuleIndex += unresolvedEntryModules.length;
21880 const firstChunkNamePriority = this.nextChunkNamePriority;
21881 this.nextChunkNamePriority += unresolvedEntryModules.length;
21882 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
21883 for (let index = 0; index < entryModules.length; index++) {
21884 const entryModule = entryModules[index];
21885 entryModule.isUserDefinedEntryPoint =
21886 entryModule.isUserDefinedEntryPoint || isUserDefined;
21887 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
21888 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
21889 if (!existingIndexedModule) {
21890 this.indexedEntryModules.push({
21891 index: firstEntryModuleIndex + index,
21892 module: entryModule
21893 });
21894 }
21895 else {
21896 existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
21897 }
21898 }
21899 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
21900 return entryModules;
21901 }));
21902 await this.awaitLoadModulesPromise();
21903 return {
21904 entryModules: this.indexedEntryModules.map(({ module }) => module),
21905 implicitEntryModules: [...this.implicitEntryModules],
21906 newEntryModules
21907 };
21908 }
21909 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
21910 const unresolvedModule = {
21911 fileName: fileName || null,
21912 id,
21913 importer,
21914 name: name || null
21915 };
21916 const module = implicitlyLoadedAfterOneOf
21917 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
21918 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
21919 if (preserveSignature != null) {
21920 module.preserveSignature = preserveSignature;
21921 }
21922 return module;
21923 }
21924 async preloadModule(resolvedId) {
21925 const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
21926 return module.info;
21927 }
21928 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
21929 const chunkNamePriority = this.nextChunkNamePriority++;
21930 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
21931 addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
21932 if (!entryModule.info.isEntry) {
21933 this.implicitEntryModules.add(entryModule);
21934 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
21935 for (const module of implicitlyLoadedAfterModules) {
21936 entryModule.implicitlyLoadedAfter.add(module);
21937 }
21938 for (const dependant of entryModule.implicitlyLoadedAfter) {
21939 dependant.implicitlyLoadedBefore.add(entryModule);
21940 }
21941 }
21942 return entryModule;
21943 }));
21944 }
21945 async addModuleSource(id, importer, module) {
21946 timeStart('load modules', 3);
21947 let source;
21948 try {
21949 source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await promises.readFile(id, 'utf8')); });
21950 }
21951 catch (err) {
21952 timeEnd('load modules', 3);
21953 let msg = `Could not load ${id}`;
21954 if (importer)
21955 msg += ` (imported by ${relativeId(importer)})`;
21956 msg += `: ${err.message}`;
21957 err.message = msg;
21958 throw err;
21959 }
21960 timeEnd('load modules', 3);
21961 const sourceDescription = typeof source === 'string'
21962 ? { code: source }
21963 : source != null && typeof source === 'object' && typeof source.code === 'string'
21964 ? source
21965 : error(errBadLoader(id));
21966 const cachedModule = this.graph.cachedModules.get(id);
21967 if (cachedModule &&
21968 !cachedModule.customTransformCache &&
21969 cachedModule.originalCode === sourceDescription.code &&
21970 !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
21971 {
21972 ast: cachedModule.ast,
21973 code: cachedModule.code,
21974 id: cachedModule.id,
21975 meta: cachedModule.meta,
21976 moduleSideEffects: cachedModule.moduleSideEffects,
21977 resolvedSources: cachedModule.resolvedIds,
21978 syntheticNamedExports: cachedModule.syntheticNamedExports
21979 }
21980 ]))) {
21981 if (cachedModule.transformFiles) {
21982 for (const emittedFile of cachedModule.transformFiles)
21983 this.pluginDriver.emitFile(emittedFile);
21984 }
21985 module.setSource(cachedModule);
21986 }
21987 else {
21988 module.updateOptions(sourceDescription);
21989 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
21990 }
21991 }
21992 async awaitLoadModulesPromise() {
21993 let startingPromise;
21994 do {
21995 startingPromise = this.latestLoadModulesPromise;
21996 await startingPromise;
21997 } while (startingPromise !== this.latestLoadModulesPromise);
21998 }
21999 extendLoadModulesPromise(loadNewModulesPromise) {
22000 this.latestLoadModulesPromise = Promise.all([
22001 loadNewModulesPromise,
22002 this.latestLoadModulesPromise
22003 ]);
22004 this.latestLoadModulesPromise.catch(() => {
22005 /* Avoid unhandled Promise rejections */
22006 });
22007 return loadNewModulesPromise;
22008 }
22009 async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
22010 const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
22011 if (resolvedId === null)
22012 return null;
22013 if (typeof resolvedId === 'string') {
22014 dynamicImport.resolution = resolvedId;
22015 return null;
22016 }
22017 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
22018 })));
22019 for (const dependency of dependencies) {
22020 if (dependency) {
22021 module.dynamicDependencies.add(dependency);
22022 dependency.dynamicImporters.push(module.id);
22023 }
22024 }
22025 }
22026 // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
22027 // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
22028 // Otherwise it returns immediately.
22029 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
22030 const existingModule = this.modulesById.get(id);
22031 if (existingModule instanceof Module) {
22032 await this.handleExistingModule(existingModule, isEntry, isPreload);
22033 return existingModule;
22034 }
22035 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
22036 this.modulesById.set(id, module);
22037 this.graph.watchFiles[id] = true;
22038 const loadPromise = this.addModuleSource(id, importer, module).then(() => [
22039 this.getResolveStaticDependencyPromises(module),
22040 this.getResolveDynamicImportPromises(module),
22041 loadAndResolveDependenciesPromise
22042 ]);
22043 const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
22044 loadAndResolveDependenciesPromise.catch(() => {
22045 /* avoid unhandled promise rejections */
22046 });
22047 this.moduleLoadPromises.set(module, loadPromise);
22048 const resolveDependencyPromises = await loadPromise;
22049 if (!isPreload) {
22050 await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
22051 }
22052 else if (isPreload === RESOLVE_DEPENDENCIES) {
22053 await loadAndResolveDependenciesPromise;
22054 }
22055 return module;
22056 }
22057 async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
22058 if (this.modulesWithLoadedDependencies.has(module)) {
22059 return;
22060 }
22061 this.modulesWithLoadedDependencies.add(module);
22062 await Promise.all([
22063 this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
22064 this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
22065 ]);
22066 module.linkImports();
22067 // To handle errors when resolving dependencies or in moduleParsed
22068 await loadAndResolveDependenciesPromise;
22069 }
22070 fetchResolvedDependency(source, importer, resolvedId) {
22071 if (resolvedId.external) {
22072 const { external, id, moduleSideEffects, meta } = resolvedId;
22073 if (!this.modulesById.has(id)) {
22074 this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
22075 }
22076 const externalModule = this.modulesById.get(id);
22077 if (!(externalModule instanceof ExternalModule)) {
22078 return error(errInternalIdCannotBeExternal(source, importer));
22079 }
22080 return Promise.resolve(externalModule);
22081 }
22082 return this.fetchModule(resolvedId, importer, false, false);
22083 }
22084 async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
22085 for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
22086 module.dependencies.add(dependency);
22087 dependency.importers.push(module.id);
22088 }
22089 if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
22090 for (const dependency of module.dependencies) {
22091 if (dependency instanceof Module) {
22092 dependency.importedFromNotTreeshaken = true;
22093 }
22094 }
22095 }
22096 }
22097 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
22098 const { makeAbsoluteExternalsRelative } = this.options;
22099 if (resolveIdResult) {
22100 if (typeof resolveIdResult === 'object') {
22101 const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
22102 return {
22103 ...resolveIdResult,
22104 external: external &&
22105 (external === 'relative' ||
22106 !isAbsolute(resolveIdResult.id) ||
22107 (external === true &&
22108 isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
22109 'absolute')
22110 };
22111 }
22112 const external = this.options.external(resolveIdResult, importer, true);
22113 return {
22114 external: external &&
22115 (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
22116 'absolute'),
22117 id: external && makeAbsoluteExternalsRelative
22118 ? normalizeRelativeExternalId(resolveIdResult, importer)
22119 : resolveIdResult
22120 };
22121 }
22122 const id = makeAbsoluteExternalsRelative
22123 ? normalizeRelativeExternalId(source, importer)
22124 : source;
22125 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
22126 return null;
22127 }
22128 return {
22129 external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
22130 id
22131 };
22132 }
22133 getResolveDynamicImportPromises(module) {
22134 return module.dynamicImports.map(async (dynamicImport) => {
22135 const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
22136 ? dynamicImport.argument
22137 : dynamicImport.argument.esTreeNode, module.id);
22138 if (resolvedId && typeof resolvedId === 'object') {
22139 dynamicImport.id = resolvedId.id;
22140 }
22141 return [dynamicImport, resolvedId];
22142 });
22143 }
22144 getResolveStaticDependencyPromises(module) {
22145 return Array.from(module.sources, async (source) => [
22146 source,
22147 (module.resolvedIds[source] =
22148 module.resolvedIds[source] ||
22149 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
22150 ]);
22151 }
22152 getResolvedIdWithDefaults(resolvedId) {
22153 var _a, _b;
22154 if (!resolvedId) {
22155 return null;
22156 }
22157 const external = resolvedId.external || false;
22158 return {
22159 external,
22160 id: resolvedId.id,
22161 meta: resolvedId.meta || {},
22162 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
22163 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
22164 };
22165 }
22166 async handleExistingModule(module, isEntry, isPreload) {
22167 const loadPromise = this.moduleLoadPromises.get(module);
22168 if (isPreload) {
22169 return isPreload === RESOLVE_DEPENDENCIES
22170 ? waitForDependencyResolution(loadPromise)
22171 : loadPromise;
22172 }
22173 if (isEntry) {
22174 module.info.isEntry = true;
22175 this.implicitEntryModules.delete(module);
22176 for (const dependant of module.implicitlyLoadedAfter) {
22177 dependant.implicitlyLoadedBefore.delete(module);
22178 }
22179 module.implicitlyLoadedAfter.clear();
22180 }
22181 return this.fetchModuleDependencies(module, ...(await loadPromise));
22182 }
22183 handleResolveId(resolvedId, source, importer) {
22184 if (resolvedId === null) {
22185 if (isRelative(source)) {
22186 return error(errUnresolvedImport(source, importer));
22187 }
22188 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
22189 return {
22190 external: true,
22191 id: source,
22192 meta: {},
22193 moduleSideEffects: this.hasModuleSideEffects(source, true),
22194 syntheticNamedExports: false
22195 };
22196 }
22197 else if (resolvedId.external && resolvedId.syntheticNamedExports) {
22198 this.options.onwarn(errExternalSyntheticExports(source, importer));
22199 }
22200 return resolvedId;
22201 }
22202 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
22203 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
22204 if (resolveIdResult == null) {
22205 return error(implicitlyLoadedBefore === null
22206 ? errUnresolvedEntry(unresolvedId)
22207 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
22208 }
22209 if (resolveIdResult === false ||
22210 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
22211 return error(implicitlyLoadedBefore === null
22212 ? errEntryCannotBeExternal(unresolvedId)
22213 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
22214 }
22215 return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
22216 ? resolveIdResult
22217 : { id: resolveIdResult }), undefined, isEntry, false);
22218 }
22219 async resolveDynamicImport(module, specifier, importer) {
22220 var _a;
22221 var _b;
22222 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
22223 specifier,
22224 importer
22225 ]);
22226 if (typeof specifier !== 'string') {
22227 if (typeof resolution === 'string') {
22228 return resolution;
22229 }
22230 if (!resolution) {
22231 return null;
22232 }
22233 return {
22234 external: false,
22235 moduleSideEffects: true,
22236 ...resolution
22237 };
22238 }
22239 if (resolution == null) {
22240 return ((_a = (_b = module.resolvedIds)[specifier]) !== null && _a !== void 0 ? _a : (_b[specifier] = this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false), specifier, module.id)));
22241 }
22242 return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
22243 }
22244}
22245function normalizeRelativeExternalId(source, importer) {
22246 return isRelative(source)
22247 ? importer
22248 ? resolve(importer, '..', source)
22249 : resolve(source)
22250 : source;
22251}
22252function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
22253 var _a;
22254 if (fileName !== null) {
22255 module.chunkFileNames.add(fileName);
22256 }
22257 else if (name !== null) {
22258 // Always keep chunkNames sorted by priority
22259 let namePosition = 0;
22260 while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
22261 namePosition++;
22262 module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
22263 }
22264}
22265function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
22266 return (makeAbsoluteExternalsRelative === true ||
22267 (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
22268 !isAbsolute(id));
22269}
22270async function waitForDependencyResolution(loadPromise) {
22271 const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
22272 return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
22273}
22274
22275class GlobalScope extends Scope$1 {
22276 constructor() {
22277 super();
22278 this.parent = null;
22279 this.variables.set('undefined', new UndefinedVariable());
22280 }
22281 findVariable(name) {
22282 let variable = this.variables.get(name);
22283 if (!variable) {
22284 variable = new GlobalVariable(name);
22285 this.variables.set(name, variable);
22286 }
22287 return variable;
22288 }
22289}
22290
22291function generateAssetFileName(name, source, outputOptions, bundle) {
22292 const emittedName = outputOptions.sanitizeFileName(name || 'asset');
22293 return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
22294 ? outputOptions.assetFileNames({ name, source, type: 'asset' })
22295 : outputOptions.assetFileNames, 'output.assetFileNames', {
22296 ext: () => extname(emittedName).substring(1),
22297 extname: () => extname(emittedName),
22298 hash() {
22299 return createHash()
22300 .update(emittedName)
22301 .update(':')
22302 .update(source)
22303 .digest('hex')
22304 .substring(0, 8);
22305 },
22306 name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
22307 }), bundle);
22308}
22309function reserveFileNameInBundle(fileName, bundle, warn) {
22310 const lowercaseFileName = fileName.toLowerCase();
22311 if (bundle[lowercaseBundleKeys].has(lowercaseFileName)) {
22312 warn(errFileNameConflict(fileName));
22313 }
22314 else {
22315 bundle[fileName] = FILE_PLACEHOLDER;
22316 }
22317}
22318function hasValidType(emittedFile) {
22319 return Boolean(emittedFile &&
22320 (emittedFile.type === 'asset' ||
22321 emittedFile.type === 'chunk'));
22322}
22323function hasValidName(emittedFile) {
22324 const validatedName = emittedFile.fileName || emittedFile.name;
22325 return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
22326}
22327function getValidSource(source, emittedFile, fileReferenceId) {
22328 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
22329 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
22330 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
22331 }
22332 return source;
22333}
22334function getAssetFileName(file, referenceId) {
22335 if (typeof file.fileName !== 'string') {
22336 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
22337 }
22338 return file.fileName;
22339}
22340function getChunkFileName(file, facadeChunkByModule) {
22341 var _a;
22342 const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
22343 if (!fileName)
22344 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
22345 return fileName;
22346}
22347class FileEmitter {
22348 constructor(graph, options, baseFileEmitter) {
22349 this.graph = graph;
22350 this.options = options;
22351 this.bundle = null;
22352 this.facadeChunkByModule = null;
22353 this.outputOptions = null;
22354 this.assertAssetsFinalized = () => {
22355 for (const [referenceId, emittedFile] of this.filesByReferenceId) {
22356 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
22357 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
22358 }
22359 };
22360 this.emitFile = (emittedFile) => {
22361 if (!hasValidType(emittedFile)) {
22362 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
22363 }
22364 if (!hasValidName(emittedFile)) {
22365 return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
22366 }
22367 if (emittedFile.type === 'chunk') {
22368 return this.emitChunk(emittedFile);
22369 }
22370 return this.emitAsset(emittedFile);
22371 };
22372 this.getFileName = (fileReferenceId) => {
22373 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
22374 if (!emittedFile)
22375 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
22376 if (emittedFile.type === 'chunk') {
22377 return getChunkFileName(emittedFile, this.facadeChunkByModule);
22378 }
22379 return getAssetFileName(emittedFile, fileReferenceId);
22380 };
22381 this.setAssetSource = (referenceId, requestedSource) => {
22382 const consumedFile = this.filesByReferenceId.get(referenceId);
22383 if (!consumedFile)
22384 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
22385 if (consumedFile.type !== 'asset') {
22386 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
22387 }
22388 if (consumedFile.source !== undefined) {
22389 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
22390 }
22391 const source = getValidSource(requestedSource, consumedFile, referenceId);
22392 if (this.bundle) {
22393 this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
22394 }
22395 else {
22396 consumedFile.source = source;
22397 }
22398 };
22399 this.setOutputBundle = (bundle, outputOptions, facadeChunkByModule) => {
22400 this.outputOptions = outputOptions;
22401 this.bundle = bundle;
22402 this.facadeChunkByModule = facadeChunkByModule;
22403 for (const { fileName } of this.filesByReferenceId.values()) {
22404 if (fileName) {
22405 reserveFileNameInBundle(fileName, bundle, this.options.onwarn);
22406 }
22407 }
22408 for (const [referenceId, consumedFile] of this.filesByReferenceId) {
22409 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
22410 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, bundle);
22411 }
22412 }
22413 };
22414 this.filesByReferenceId = baseFileEmitter
22415 ? new Map(baseFileEmitter.filesByReferenceId)
22416 : new Map();
22417 }
22418 assignReferenceId(file, idBase) {
22419 let referenceId;
22420 do {
22421 referenceId = createHash()
22422 .update(referenceId || idBase)
22423 .digest('hex')
22424 .substring(0, 8);
22425 } while (this.filesByReferenceId.has(referenceId));
22426 this.filesByReferenceId.set(referenceId, file);
22427 return referenceId;
22428 }
22429 emitAsset(emittedAsset) {
22430 const source = typeof emittedAsset.source !== 'undefined'
22431 ? getValidSource(emittedAsset.source, emittedAsset, null)
22432 : undefined;
22433 const consumedAsset = {
22434 fileName: emittedAsset.fileName,
22435 name: emittedAsset.name,
22436 source,
22437 type: 'asset'
22438 };
22439 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
22440 if (this.bundle) {
22441 if (emittedAsset.fileName) {
22442 reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
22443 }
22444 if (source !== undefined) {
22445 this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
22446 }
22447 }
22448 return referenceId;
22449 }
22450 emitChunk(emittedChunk) {
22451 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
22452 return error(errInvalidRollupPhaseForChunkEmission());
22453 }
22454 if (typeof emittedChunk.id !== 'string') {
22455 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
22456 }
22457 const consumedChunk = {
22458 fileName: emittedChunk.fileName,
22459 module: null,
22460 name: emittedChunk.name || emittedChunk.id,
22461 type: 'chunk'
22462 };
22463 this.graph.moduleLoader
22464 .emitChunk(emittedChunk)
22465 .then(module => (consumedChunk.module = module))
22466 .catch(() => {
22467 // Avoid unhandled Promise rejection as the error will be thrown later
22468 // once module loading has finished
22469 });
22470 return this.assignReferenceId(consumedChunk, emittedChunk.id);
22471 }
22472 finalizeAsset(consumedFile, source, referenceId, bundle) {
22473 const fileName = consumedFile.fileName ||
22474 findExistingAssetFileNameWithSource(bundle, source) ||
22475 generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
22476 // We must not modify the original assets to avoid interaction between outputs
22477 const assetWithFileName = { ...consumedFile, fileName, source };
22478 this.filesByReferenceId.set(referenceId, assetWithFileName);
22479 const { options } = this;
22480 bundle[fileName] = {
22481 fileName,
22482 get isAsset() {
22483 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
22484 return true;
22485 },
22486 name: consumedFile.name,
22487 source,
22488 type: 'asset'
22489 };
22490 }
22491}
22492// TODO This can lead to a performance problem when many assets are emitted.
22493// Instead, we should only deduplicate string assets and use their sources as
22494// object keys for better performance.
22495function findExistingAssetFileNameWithSource(bundle, source) {
22496 for (const [fileName, outputFile] of Object.entries(bundle)) {
22497 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
22498 return fileName;
22499 }
22500 return null;
22501}
22502function areSourcesEqual(sourceA, sourceB) {
22503 if (typeof sourceA === 'string') {
22504 return sourceA === sourceB;
22505 }
22506 if (typeof sourceB === 'string') {
22507 return false;
22508 }
22509 if ('equals' in sourceA) {
22510 return sourceA.equals(sourceB);
22511 }
22512 if (sourceA.length !== sourceB.length) {
22513 return false;
22514 }
22515 for (let index = 0; index < sourceA.length; index++) {
22516 if (sourceA[index] !== sourceB[index]) {
22517 return false;
22518 }
22519 }
22520 return true;
22521}
22522
22523function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
22524 let deprecationWarningShown = false;
22525 return ((...args) => {
22526 if (!deprecationWarningShown) {
22527 deprecationWarningShown = true;
22528 warnDeprecation({
22529 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
22530 plugin: pluginName
22531 }, activeDeprecation, options);
22532 }
22533 return handler(...args);
22534 });
22535}
22536function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
22537 let cacheable = true;
22538 if (typeof plugin.cacheKey !== 'string') {
22539 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
22540 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
22541 existingPluginNames.has(plugin.name)) {
22542 cacheable = false;
22543 }
22544 else {
22545 existingPluginNames.add(plugin.name);
22546 }
22547 }
22548 let cacheInstance;
22549 if (!pluginCache) {
22550 cacheInstance = NO_CACHE;
22551 }
22552 else if (cacheable) {
22553 const cacheKey = plugin.cacheKey || plugin.name;
22554 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
22555 }
22556 else {
22557 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
22558 }
22559 return {
22560 addWatchFile(id) {
22561 if (graph.phase >= BuildPhase.GENERATE) {
22562 return this.error(errInvalidRollupPhaseForAddWatchFile());
22563 }
22564 graph.watchFiles[id] = true;
22565 },
22566 cache: cacheInstance,
22567 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
22568 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
22569 emitFile: fileEmitter.emitFile.bind(fileEmitter),
22570 error(err) {
22571 return throwPluginError(err, plugin.name);
22572 },
22573 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
22574 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
22575 getFileName: fileEmitter.getFileName,
22576 getModuleIds: () => graph.modulesById.keys(),
22577 getModuleInfo: graph.getModuleInfo,
22578 getWatchFiles: () => Object.keys(graph.watchFiles),
22579 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
22580 load(resolvedId) {
22581 return graph.moduleLoader.preloadModule(resolvedId);
22582 },
22583 meta: {
22584 rollupVersion: version$1,
22585 watchMode: graph.watchMode
22586 },
22587 get moduleIds() {
22588 function* wrappedModuleIds() {
22589 // We are wrapping this in a generator to only show the message once we are actually iterating
22590 warnDeprecation({
22591 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
22592 plugin: plugin.name
22593 }, false, options);
22594 yield* moduleIds;
22595 }
22596 const moduleIds = graph.modulesById.keys();
22597 return wrappedModuleIds();
22598 },
22599 parse: graph.contextParse.bind(graph),
22600 resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
22601 return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
22602 },
22603 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
22604 .resolveId(source, importer, BLANK, undefined)
22605 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
22606 setAssetSource: fileEmitter.setAssetSource,
22607 warn(warning) {
22608 if (typeof warning === 'string')
22609 warning = { message: warning };
22610 if (warning.code)
22611 warning.pluginCode = warning.code;
22612 warning.code = 'PLUGIN_WARNING';
22613 warning.plugin = plugin.name;
22614 options.onwarn(warning);
22615 }
22616 };
22617}
22618
22619// This will make sure no input hook is omitted
22620const inputHookNames = {
22621 buildEnd: 1,
22622 buildStart: 1,
22623 closeBundle: 1,
22624 closeWatcher: 1,
22625 load: 1,
22626 moduleParsed: 1,
22627 options: 1,
22628 resolveDynamicImport: 1,
22629 resolveId: 1,
22630 shouldTransformCachedModule: 1,
22631 transform: 1,
22632 watchChange: 1
22633};
22634const inputHooks = Object.keys(inputHookNames);
22635class PluginDriver {
22636 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
22637 this.graph = graph;
22638 this.options = options;
22639 this.pluginCache = pluginCache;
22640 this.sortedPlugins = new Map();
22641 this.unfulfilledActions = new Set();
22642 warnDeprecatedHooks(userPlugins, options);
22643 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
22644 this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
22645 this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
22646 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
22647 this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22648 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
22649 const existingPluginNames = new Set();
22650 this.pluginContexts = new Map(this.plugins.map(plugin => [
22651 plugin,
22652 getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
22653 ]));
22654 if (basePluginDriver) {
22655 for (const plugin of userPlugins) {
22656 for (const hook of inputHooks) {
22657 if (hook in plugin) {
22658 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
22659 }
22660 }
22661 }
22662 }
22663 }
22664 createOutputPluginDriver(plugins) {
22665 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
22666 }
22667 getUnfulfilledHookActions() {
22668 return this.unfulfilledActions;
22669 }
22670 // chains, first non-null result stops and returns
22671 hookFirst(hookName, args, replaceContext, skipped) {
22672 let promise = Promise.resolve(null);
22673 for (const plugin of this.getSortedPlugins(hookName)) {
22674 if (skipped && skipped.has(plugin))
22675 continue;
22676 promise = promise.then(result => {
22677 if (result != null)
22678 return result;
22679 return this.runHook(hookName, args, plugin, replaceContext);
22680 });
22681 }
22682 return promise;
22683 }
22684 // chains synchronously, first non-null result stops and returns
22685 hookFirstSync(hookName, args, replaceContext) {
22686 for (const plugin of this.getSortedPlugins(hookName)) {
22687 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22688 if (result != null)
22689 return result;
22690 }
22691 return null;
22692 }
22693 // parallel, ignores returns
22694 async hookParallel(hookName, args, replaceContext) {
22695 const parallelPromises = [];
22696 for (const plugin of this.getSortedPlugins(hookName)) {
22697 if (plugin[hookName].sequential) {
22698 await Promise.all(parallelPromises);
22699 parallelPromises.length = 0;
22700 await this.runHook(hookName, args, plugin, replaceContext);
22701 }
22702 else {
22703 parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
22704 }
22705 }
22706 await Promise.all(parallelPromises);
22707 }
22708 // chains, reduces returned value, handling the reduced value as the first hook argument
22709 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
22710 let promise = Promise.resolve(arg0);
22711 for (const plugin of this.getSortedPlugins(hookName)) {
22712 promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
22713 }
22714 return promise;
22715 }
22716 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
22717 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
22718 for (const plugin of this.getSortedPlugins(hookName)) {
22719 const args = [arg0, ...rest];
22720 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22721 arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
22722 }
22723 return arg0;
22724 }
22725 // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
22726 async hookReduceValue(hookName, initialValue, args, reducer) {
22727 const results = [];
22728 const parallelResults = [];
22729 for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
22730 if (plugin[hookName].sequential) {
22731 results.push(...(await Promise.all(parallelResults)));
22732 parallelResults.length = 0;
22733 results.push(await this.runHook(hookName, args, plugin));
22734 }
22735 else {
22736 parallelResults.push(this.runHook(hookName, args, plugin));
22737 }
22738 }
22739 results.push(...(await Promise.all(parallelResults)));
22740 return results.reduce(reducer, await initialValue);
22741 }
22742 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
22743 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
22744 let acc = initialValue;
22745 for (const plugin of this.getSortedPlugins(hookName)) {
22746 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22747 acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
22748 }
22749 return acc;
22750 }
22751 // chains, ignores returns
22752 hookSeq(hookName, args, replaceContext) {
22753 let promise = Promise.resolve();
22754 for (const plugin of this.getSortedPlugins(hookName)) {
22755 promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
22756 }
22757 return promise.then(noReturn);
22758 }
22759 getSortedPlugins(hookName, validateHandler) {
22760 return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
22761 }
22762 // Implementation signature
22763 runHook(hookName, args, plugin, replaceContext) {
22764 // We always filter for plugins that support the hook before running it
22765 const hook = plugin[hookName];
22766 const handler = typeof hook === 'object' ? hook.handler : hook;
22767 let context = this.pluginContexts.get(plugin);
22768 if (replaceContext) {
22769 context = replaceContext(context, plugin);
22770 }
22771 let action = null;
22772 return Promise.resolve()
22773 .then(() => {
22774 if (typeof handler !== 'function') {
22775 return handler;
22776 }
22777 // eslint-disable-next-line @typescript-eslint/ban-types
22778 const hookResult = handler.apply(context, args);
22779 if (!(hookResult === null || hookResult === void 0 ? void 0 : hookResult.then)) {
22780 // short circuit for non-thenables and non-Promises
22781 return hookResult;
22782 }
22783 // Track pending hook actions to properly error out when
22784 // unfulfilled promises cause rollup to abruptly and confusingly
22785 // exit with a successful 0 return code but without producing any
22786 // output, errors or warnings.
22787 action = [plugin.name, hookName, args];
22788 this.unfulfilledActions.add(action);
22789 // Although it would be more elegant to just return hookResult here
22790 // and put the .then() handler just above the .catch() handler below,
22791 // doing so would subtly change the defacto async event dispatch order
22792 // which at least one test and some plugins in the wild may depend on.
22793 return Promise.resolve(hookResult).then(result => {
22794 // action was fulfilled
22795 this.unfulfilledActions.delete(action);
22796 return result;
22797 });
22798 })
22799 .catch(err => {
22800 if (action !== null) {
22801 // action considered to be fulfilled since error being handled
22802 this.unfulfilledActions.delete(action);
22803 }
22804 return throwPluginError(err, plugin.name, { hook: hookName });
22805 });
22806 }
22807 /**
22808 * Run a sync plugin hook and return the result.
22809 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
22810 * @param args Arguments passed to the plugin hook.
22811 * @param plugin The acutal plugin
22812 * @param replaceContext When passed, the plugin context can be overridden.
22813 */
22814 runHookSync(hookName, args, plugin, replaceContext) {
22815 const hook = plugin[hookName];
22816 const handler = typeof hook === 'object' ? hook.handler : hook;
22817 let context = this.pluginContexts.get(plugin);
22818 if (replaceContext) {
22819 context = replaceContext(context, plugin);
22820 }
22821 try {
22822 // eslint-disable-next-line @typescript-eslint/ban-types
22823 return handler.apply(context, args);
22824 }
22825 catch (err) {
22826 return throwPluginError(err, plugin.name, { hook: hookName });
22827 }
22828 }
22829}
22830function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
22831 const pre = [];
22832 const normal = [];
22833 const post = [];
22834 for (const plugin of plugins) {
22835 const hook = plugin[hookName];
22836 if (hook) {
22837 if (typeof hook === 'object') {
22838 validateHandler(hook.handler, hookName, plugin);
22839 if (hook.order === 'pre') {
22840 pre.push(plugin);
22841 continue;
22842 }
22843 if (hook.order === 'post') {
22844 post.push(plugin);
22845 continue;
22846 }
22847 }
22848 else {
22849 validateHandler(hook, hookName, plugin);
22850 }
22851 normal.push(plugin);
22852 }
22853 }
22854 return [...pre, ...normal, ...post];
22855}
22856function validateFunctionPluginHandler(handler, hookName, plugin) {
22857 if (typeof handler !== 'function') {
22858 error(errInvalidFunctionPluginHook(hookName, plugin.name));
22859 }
22860}
22861function validateAddonPluginHandler(handler, hookName, plugin) {
22862 if (typeof handler !== 'string' && typeof handler !== 'function') {
22863 return error(errInvalidAddonPluginHook(hookName, plugin.name));
22864 }
22865}
22866function noReturn() { }
22867
22868class Queue {
22869 constructor(maxParallel) {
22870 this.maxParallel = maxParallel;
22871 this.queue = [];
22872 this.workerCount = 0;
22873 }
22874 run(task) {
22875 return new Promise((resolve, reject) => {
22876 this.queue.push({ reject, resolve, task });
22877 this.work();
22878 });
22879 }
22880 async work() {
22881 if (this.workerCount >= this.maxParallel)
22882 return;
22883 this.workerCount++;
22884 let entry;
22885 while ((entry = this.queue.shift())) {
22886 const { reject, resolve, task } = entry;
22887 try {
22888 const result = await task();
22889 resolve(result);
22890 }
22891 catch (err) {
22892 reject(err);
22893 }
22894 }
22895 this.workerCount--;
22896 }
22897}
22898
22899function normalizeEntryModules(entryModules) {
22900 if (Array.isArray(entryModules)) {
22901 return entryModules.map(id => ({
22902 fileName: null,
22903 id,
22904 implicitlyLoadedAfter: [],
22905 importer: undefined,
22906 name: null
22907 }));
22908 }
22909 return Object.entries(entryModules).map(([name, id]) => ({
22910 fileName: null,
22911 id,
22912 implicitlyLoadedAfter: [],
22913 importer: undefined,
22914 name
22915 }));
22916}
22917class Graph {
22918 constructor(options, watcher) {
22919 var _a, _b;
22920 this.options = options;
22921 this.cachedModules = new Map();
22922 this.deoptimizationTracker = new PathTracker();
22923 this.entryModules = [];
22924 this.modulesById = new Map();
22925 this.needsTreeshakingPass = false;
22926 this.phase = BuildPhase.LOAD_AND_PARSE;
22927 this.scope = new GlobalScope();
22928 this.watchFiles = Object.create(null);
22929 this.watchMode = false;
22930 this.externalModules = [];
22931 this.implicitEntryModules = [];
22932 this.modules = [];
22933 this.getModuleInfo = (moduleId) => {
22934 const foundModule = this.modulesById.get(moduleId);
22935 if (!foundModule)
22936 return null;
22937 return foundModule.info;
22938 };
22939 if (options.cache !== false) {
22940 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
22941 for (const module of options.cache.modules)
22942 this.cachedModules.set(module.id, module);
22943 }
22944 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
22945 // increment access counter
22946 for (const name in this.pluginCache) {
22947 const cache = this.pluginCache[name];
22948 for (const value of Object.values(cache))
22949 value[0]++;
22950 }
22951 }
22952 if (watcher) {
22953 this.watchMode = true;
22954 const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
22955 const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
22956 watcher.onCurrentAwaited('change', handleChange);
22957 watcher.onCurrentAwaited('close', handleClose);
22958 }
22959 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
22960 this.acornParser = Parser.extend(...options.acornInjectPlugins);
22961 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
22962 this.fileOperationQueue = new Queue(options.maxParallelFileOps);
22963 }
22964 async build() {
22965 timeStart('generate module graph', 2);
22966 await this.generateModuleGraph();
22967 timeEnd('generate module graph', 2);
22968 timeStart('sort modules', 2);
22969 this.phase = BuildPhase.ANALYSE;
22970 this.sortModules();
22971 timeEnd('sort modules', 2);
22972 timeStart('mark included statements', 2);
22973 this.includeStatements();
22974 timeEnd('mark included statements', 2);
22975 this.phase = BuildPhase.GENERATE;
22976 }
22977 contextParse(code, options = {}) {
22978 const onCommentOrig = options.onComment;
22979 const comments = [];
22980 if (onCommentOrig && typeof onCommentOrig == 'function') {
22981 options.onComment = (block, text, start, end, ...args) => {
22982 comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
22983 return onCommentOrig.call(options, block, text, start, end, ...args);
22984 };
22985 }
22986 else {
22987 options.onComment = comments;
22988 }
22989 const ast = this.acornParser.parse(code, {
22990 ...this.options.acorn,
22991 ...options
22992 });
22993 if (typeof onCommentOrig == 'object') {
22994 onCommentOrig.push(...comments);
22995 }
22996 options.onComment = onCommentOrig;
22997 addAnnotations(comments, ast, code);
22998 return ast;
22999 }
23000 getCache() {
23001 // handle plugin cache eviction
23002 for (const name in this.pluginCache) {
23003 const cache = this.pluginCache[name];
23004 let allDeleted = true;
23005 for (const [key, value] of Object.entries(cache)) {
23006 if (value[0] >= this.options.experimentalCacheExpiry)
23007 delete cache[key];
23008 else
23009 allDeleted = false;
23010 }
23011 if (allDeleted)
23012 delete this.pluginCache[name];
23013 }
23014 return {
23015 modules: this.modules.map(module => module.toJSON()),
23016 plugins: this.pluginCache
23017 };
23018 }
23019 async generateModuleGraph() {
23020 ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
23021 await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
23022 if (this.entryModules.length === 0) {
23023 throw new Error('You must supply options.input to rollup');
23024 }
23025 for (const module of this.modulesById.values()) {
23026 if (module instanceof Module) {
23027 this.modules.push(module);
23028 }
23029 else {
23030 this.externalModules.push(module);
23031 }
23032 }
23033 }
23034 includeStatements() {
23035 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23036 markModuleAndImpureDependenciesAsExecuted(module);
23037 }
23038 if (this.options.treeshake) {
23039 let treeshakingPass = 1;
23040 do {
23041 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
23042 this.needsTreeshakingPass = false;
23043 for (const module of this.modules) {
23044 if (module.isExecuted) {
23045 if (module.info.moduleSideEffects === 'no-treeshake') {
23046 module.includeAllInBundle();
23047 }
23048 else {
23049 module.include();
23050 }
23051 }
23052 }
23053 if (treeshakingPass === 1) {
23054 // We only include exports after the first pass to avoid issues with
23055 // the TDZ detection logic
23056 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23057 if (module.preserveSignature !== false) {
23058 module.includeAllExports(false);
23059 this.needsTreeshakingPass = true;
23060 }
23061 }
23062 }
23063 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
23064 } while (this.needsTreeshakingPass);
23065 }
23066 else {
23067 for (const module of this.modules)
23068 module.includeAllInBundle();
23069 }
23070 for (const externalModule of this.externalModules)
23071 externalModule.warnUnusedImports();
23072 for (const module of this.implicitEntryModules) {
23073 for (const dependant of module.implicitlyLoadedAfter) {
23074 if (!(dependant.info.isEntry || dependant.isIncluded())) {
23075 error(errImplicitDependantIsNotIncluded(dependant));
23076 }
23077 }
23078 }
23079 }
23080 sortModules() {
23081 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
23082 for (const cyclePath of cyclePaths) {
23083 this.options.onwarn({
23084 code: 'CIRCULAR_DEPENDENCY',
23085 cycle: cyclePath,
23086 importer: cyclePath[0],
23087 message: `Circular dependency: ${cyclePath.join(' -> ')}`
23088 });
23089 }
23090 this.modules = orderedModules;
23091 for (const module of this.modules) {
23092 module.bindReferences();
23093 }
23094 this.warnForMissingExports();
23095 }
23096 warnForMissingExports() {
23097 for (const module of this.modules) {
23098 for (const importDescription of module.importDescriptions.values()) {
23099 if (importDescription.name !== '*' &&
23100 !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
23101 module.warn({
23102 code: 'NON_EXISTENT_EXPORT',
23103 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
23104 name: importDescription.name,
23105 source: importDescription.module.id
23106 }, importDescription.start);
23107 }
23108 }
23109 }
23110 }
23111}
23112
23113function ensureArray(items) {
23114 if (Array.isArray(items)) {
23115 return items.filter(Boolean);
23116 }
23117 if (items) {
23118 return [items];
23119 }
23120 return [];
23121}
23122
23123function formatAction([pluginName, hookName, args]) {
23124 const action = `(${pluginName}) ${hookName}`;
23125 const s = JSON.stringify;
23126 switch (hookName) {
23127 case 'resolveId':
23128 return `${action} ${s(args[0])} ${s(args[1])}`;
23129 case 'load':
23130 return `${action} ${s(args[0])}`;
23131 case 'transform':
23132 return `${action} ${s(args[1])}`;
23133 case 'shouldTransformCachedModule':
23134 return `${action} ${s(args[0].id)}`;
23135 case 'moduleParsed':
23136 return `${action} ${s(args[0].id)}`;
23137 }
23138 return action;
23139}
23140// We do not directly listen on process to avoid max listeners warnings for
23141// complicated build processes
23142const beforeExitEvent = 'beforeExit';
23143const beforeExitEmitter = new EventEmitter();
23144beforeExitEmitter.setMaxListeners(0);
23145process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
23146async function catchUnfinishedHookActions(pluginDriver, callback) {
23147 let handleEmptyEventLoop;
23148 const emptyEventLoopPromise = new Promise((_, reject) => {
23149 handleEmptyEventLoop = () => {
23150 const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
23151 reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
23152 [...unfulfilledActions].map(formatAction).join('\n')));
23153 };
23154 beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
23155 });
23156 const result = await Promise.race([callback(), emptyEventLoopPromise]);
23157 beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
23158 return result;
23159}
23160
23161const defaultOnWarn = warning => console.warn(warning.message || warning);
23162function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
23163 const validOptionSet = new Set(validOptions);
23164 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
23165 if (unknownOptions.length > 0) {
23166 warn({
23167 code: 'UNKNOWN_OPTION',
23168 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
23169 ...validOptionSet
23170 ]
23171 .sort()
23172 .join(', ')}`
23173 });
23174 }
23175}
23176const treeshakePresets = {
23177 recommended: {
23178 annotations: true,
23179 correctVarValueBeforeDeclaration: false,
23180 moduleSideEffects: () => true,
23181 propertyReadSideEffects: true,
23182 tryCatchDeoptimization: true,
23183 unknownGlobalSideEffects: false
23184 },
23185 safest: {
23186 annotations: true,
23187 correctVarValueBeforeDeclaration: true,
23188 moduleSideEffects: () => true,
23189 propertyReadSideEffects: true,
23190 tryCatchDeoptimization: true,
23191 unknownGlobalSideEffects: true
23192 },
23193 smallest: {
23194 annotations: true,
23195 correctVarValueBeforeDeclaration: false,
23196 moduleSideEffects: () => false,
23197 propertyReadSideEffects: false,
23198 tryCatchDeoptimization: false,
23199 unknownGlobalSideEffects: false
23200 }
23201};
23202const generatedCodePresets = {
23203 es2015: {
23204 arrowFunctions: true,
23205 constBindings: true,
23206 objectShorthand: true,
23207 reservedNamesAsProps: true,
23208 symbols: true
23209 },
23210 es5: {
23211 arrowFunctions: false,
23212 constBindings: false,
23213 objectShorthand: false,
23214 reservedNamesAsProps: true,
23215 symbols: false
23216 }
23217};
23218const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
23219const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
23220 if (typeof value === 'string') {
23221 const preset = presets[value];
23222 if (preset) {
23223 return preset;
23224 }
23225 error(errInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
23226 }
23227 return objectifyOption(value);
23228};
23229const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
23230 const presetName = value === null || value === void 0 ? void 0 : value.preset;
23231 if (presetName) {
23232 const preset = presets[presetName];
23233 if (preset) {
23234 return { ...preset, ...value };
23235 }
23236 else {
23237 error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
23238 }
23239 }
23240 return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
23241};
23242const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
23243
23244function normalizeInputOptions(config) {
23245 var _a, _b, _c;
23246 // These are options that may trigger special warnings or behaviour later
23247 // if the user did not select an explicit value
23248 const unsetOptions = new Set();
23249 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
23250 const onwarn = getOnwarn(config);
23251 const strictDeprecations = config.strictDeprecations || false;
23252 const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
23253 const options = {
23254 acorn: getAcorn(config),
23255 acornInjectPlugins: getAcornInjectPlugins(config),
23256 cache: getCache(config),
23257 context,
23258 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
23259 external: getIdMatcher(config.external),
23260 inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
23261 input: getInput(config),
23262 makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
23263 manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
23264 maxParallelFileOps,
23265 maxParallelFileReads: maxParallelFileOps,
23266 moduleContext: getModuleContext(config, context),
23267 onwarn,
23268 perf: config.perf || false,
23269 plugins: ensureArray(config.plugins),
23270 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
23271 preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
23272 preserveSymlinks: config.preserveSymlinks || false,
23273 shimMissingExports: config.shimMissingExports || false,
23274 strictDeprecations,
23275 treeshake: getTreeshake(config, onwarn, strictDeprecations)
23276 };
23277 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
23278 return { options, unsetOptions };
23279}
23280const getOnwarn = (config) => {
23281 const { onwarn } = config;
23282 return onwarn
23283 ? warning => {
23284 warning.toString = () => {
23285 let str = '';
23286 if (warning.plugin)
23287 str += `(${warning.plugin} plugin) `;
23288 if (warning.loc)
23289 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
23290 str += warning.message;
23291 return str;
23292 };
23293 onwarn(warning, defaultOnWarn);
23294 }
23295 : defaultOnWarn;
23296};
23297const getAcorn = (config) => ({
23298 allowAwaitOutsideFunction: true,
23299 ecmaVersion: 'latest',
23300 preserveParens: false,
23301 sourceType: 'module',
23302 ...config.acorn
23303});
23304const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
23305const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
23306const getIdMatcher = (option) => {
23307 if (option === true) {
23308 return () => true;
23309 }
23310 if (typeof option === 'function') {
23311 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
23312 }
23313 if (option) {
23314 const ids = new Set();
23315 const matchers = [];
23316 for (const value of ensureArray(option)) {
23317 if (value instanceof RegExp) {
23318 matchers.push(value);
23319 }
23320 else {
23321 ids.add(value);
23322 }
23323 }
23324 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
23325 }
23326 return () => false;
23327};
23328const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
23329 const configInlineDynamicImports = config.inlineDynamicImports;
23330 if (configInlineDynamicImports) {
23331 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
23332 }
23333 return configInlineDynamicImports;
23334};
23335const getInput = (config) => {
23336 const configInput = config.input;
23337 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
23338};
23339const getManualChunks$1 = (config, warn, strictDeprecations) => {
23340 const configManualChunks = config.manualChunks;
23341 if (configManualChunks) {
23342 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
23343 }
23344 return configManualChunks;
23345};
23346const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
23347 var _a;
23348 const maxParallelFileReads = config.maxParallelFileReads;
23349 if (typeof maxParallelFileReads === 'number') {
23350 warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
23351 }
23352 const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
23353 if (typeof maxParallelFileOps === 'number') {
23354 if (maxParallelFileOps <= 0)
23355 return Infinity;
23356 return maxParallelFileOps;
23357 }
23358 return 20;
23359};
23360const getModuleContext = (config, context) => {
23361 const configModuleContext = config.moduleContext;
23362 if (typeof configModuleContext === 'function') {
23363 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
23364 }
23365 if (configModuleContext) {
23366 const contextByModuleId = Object.create(null);
23367 for (const [key, moduleContext] of Object.entries(configModuleContext)) {
23368 contextByModuleId[resolve(key)] = moduleContext;
23369 }
23370 return id => contextByModuleId[id] || context;
23371 }
23372 return () => context;
23373};
23374const getPreserveEntrySignatures = (config, unsetOptions) => {
23375 const configPreserveEntrySignatures = config.preserveEntrySignatures;
23376 if (configPreserveEntrySignatures == null) {
23377 unsetOptions.add('preserveEntrySignatures');
23378 }
23379 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
23380};
23381const getPreserveModules$1 = (config, warn, strictDeprecations) => {
23382 const configPreserveModules = config.preserveModules;
23383 if (configPreserveModules) {
23384 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
23385 }
23386 return configPreserveModules;
23387};
23388const getTreeshake = (config, warn, strictDeprecations) => {
23389 const configTreeshake = config.treeshake;
23390 if (configTreeshake === false) {
23391 return false;
23392 }
23393 const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
23394 if (typeof configWithPreset.pureExternalModules !== 'undefined') {
23395 warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
23396 }
23397 return {
23398 annotations: configWithPreset.annotations !== false,
23399 correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
23400 moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
23401 ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
23402 : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
23403 propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
23404 ? 'always'
23405 : configWithPreset.propertyReadSideEffects !== false,
23406 tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
23407 unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
23408 };
23409};
23410const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
23411 if (typeof moduleSideEffectsOption === 'boolean') {
23412 return () => moduleSideEffectsOption;
23413 }
23414 if (moduleSideEffectsOption === 'no-external') {
23415 return (_id, external) => !external;
23416 }
23417 if (typeof moduleSideEffectsOption === 'function') {
23418 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
23419 }
23420 if (Array.isArray(moduleSideEffectsOption)) {
23421 const ids = new Set(moduleSideEffectsOption);
23422 return id => ids.has(id);
23423 }
23424 if (moduleSideEffectsOption) {
23425 error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23426 }
23427 const isPureExternalModule = getIdMatcher(pureExternalModules);
23428 return (id, external) => !(external && isPureExternalModule(id));
23429};
23430
23431// https://datatracker.ietf.org/doc/html/rfc2396
23432// eslint-disable-next-line no-control-regex
23433const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
23434const DRIVE_LETTER_REGEX = /^[a-z]:/i;
23435function sanitizeFileName(name) {
23436 const match = DRIVE_LETTER_REGEX.exec(name);
23437 const driveLetter = match ? match[0] : '';
23438 // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
23439 // Otherwise, avoid them because they can refer to NTFS alternate data streams.
23440 return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
23441}
23442
23443function isValidUrl(url) {
23444 try {
23445 new URL(url);
23446 }
23447 catch (_) {
23448 return false;
23449 }
23450 return true;
23451}
23452
23453function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23454 var _a, _b, _c, _d, _e, _f, _g;
23455 // These are options that may trigger special warnings or behaviour later
23456 // if the user did not select an explicit value
23457 const unsetOptions = new Set(unsetInputOptions);
23458 const compact = config.compact || false;
23459 const format = getFormat(config);
23460 const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
23461 const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
23462 const file = getFile(config, preserveModules, inputOptions);
23463 const preferConst = getPreferConst(config, inputOptions);
23464 const generatedCode = getGeneratedCode(config, preferConst);
23465 const outputOptions = {
23466 amd: getAmd(config),
23467 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
23468 banner: getAddon(config, 'banner'),
23469 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
23470 compact,
23471 dir: getDir(config, file),
23472 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
23473 entryFileNames: getEntryFileNames(config, unsetOptions),
23474 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
23475 exports: getExports(config, unsetOptions),
23476 extend: config.extend || false,
23477 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
23478 file,
23479 footer: getAddon(config, 'footer'),
23480 format,
23481 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
23482 generatedCode,
23483 globals: config.globals || {},
23484 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
23485 indent: getIndent(config, compact),
23486 inlineDynamicImports,
23487 interop: getInterop(config, inputOptions),
23488 intro: getAddon(config, 'intro'),
23489 manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
23490 minifyInternalExports: getMinifyInternalExports(config, format, compact),
23491 name: config.name,
23492 namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
23493 noConflict: config.noConflict || false,
23494 outro: getAddon(config, 'outro'),
23495 paths: config.paths || {},
23496 plugins: ensureArray(config.plugins),
23497 preferConst,
23498 preserveModules,
23499 preserveModulesRoot: getPreserveModulesRoot(config),
23500 sanitizeFileName: typeof config.sanitizeFileName === 'function'
23501 ? config.sanitizeFileName
23502 : config.sanitizeFileName === false
23503 ? id => id
23504 : sanitizeFileName,
23505 sourcemap: config.sourcemap || false,
23506 sourcemapBaseUrl: getSourcemapBaseUrl(config),
23507 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
23508 sourcemapFile: config.sourcemapFile,
23509 sourcemapPathTransform: config.sourcemapPathTransform,
23510 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
23511 systemNullSetters: config.systemNullSetters || false,
23512 validate: config.validate || false
23513 };
23514 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
23515 return { options: outputOptions, unsetOptions };
23516}
23517const getFile = (config, preserveModules, inputOptions) => {
23518 const { file } = config;
23519 if (typeof file === 'string') {
23520 if (preserveModules) {
23521 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
23522 }
23523 if (!Array.isArray(inputOptions.input))
23524 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
23525 }
23526 return file;
23527};
23528const getFormat = (config) => {
23529 const configFormat = config.format;
23530 switch (configFormat) {
23531 case undefined:
23532 case 'es':
23533 case 'esm':
23534 case 'module':
23535 return 'es';
23536 case 'cjs':
23537 case 'commonjs':
23538 return 'cjs';
23539 case 'system':
23540 case 'systemjs':
23541 return 'system';
23542 case 'amd':
23543 case 'iife':
23544 case 'umd':
23545 return configFormat;
23546 default:
23547 return error({
23548 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
23549 url: `https://rollupjs.org/guide/en/#outputformat`
23550 });
23551 }
23552};
23553const getInlineDynamicImports = (config, inputOptions) => {
23554 var _a;
23555 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
23556 const { input } = inputOptions;
23557 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
23558 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
23559 }
23560 return inlineDynamicImports;
23561};
23562const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
23563 var _a;
23564 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
23565 if (preserveModules) {
23566 if (inlineDynamicImports) {
23567 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
23568 }
23569 if (inputOptions.preserveEntrySignatures === false) {
23570 return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
23571 }
23572 }
23573 return preserveModules;
23574};
23575const getPreferConst = (config, inputOptions) => {
23576 const configPreferConst = config.preferConst;
23577 if (configPreferConst != null) {
23578 warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
23579 }
23580 return !!configPreferConst;
23581};
23582const getPreserveModulesRoot = (config) => {
23583 const { preserveModulesRoot } = config;
23584 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
23585 return undefined;
23586 }
23587 return resolve(preserveModulesRoot);
23588};
23589const getAmd = (config) => {
23590 const mergedOption = {
23591 autoId: false,
23592 basePath: '',
23593 define: 'define',
23594 forceJsExtensionForImports: false,
23595 ...config.amd
23596 };
23597 if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
23598 return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
23599 }
23600 if (mergedOption.basePath && !mergedOption.autoId) {
23601 return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
23602 }
23603 let normalized;
23604 if (mergedOption.autoId) {
23605 normalized = {
23606 autoId: true,
23607 basePath: mergedOption.basePath,
23608 define: mergedOption.define,
23609 forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
23610 };
23611 }
23612 else {
23613 normalized = {
23614 autoId: false,
23615 define: mergedOption.define,
23616 forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
23617 id: mergedOption.id
23618 };
23619 }
23620 return normalized;
23621};
23622const getAddon = (config, name) => {
23623 const configAddon = config[name];
23624 if (typeof configAddon === 'function') {
23625 return configAddon;
23626 }
23627 return () => configAddon || '';
23628};
23629const getDir = (config, file) => {
23630 const { dir } = config;
23631 if (typeof dir === 'string' && typeof file === 'string') {
23632 return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
23633 }
23634 return dir;
23635};
23636const getDynamicImportFunction = (config, inputOptions) => {
23637 const configDynamicImportFunction = config.dynamicImportFunction;
23638 if (configDynamicImportFunction) {
23639 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
23640 }
23641 return configDynamicImportFunction;
23642};
23643const getEntryFileNames = (config, unsetOptions) => {
23644 const configEntryFileNames = config.entryFileNames;
23645 if (configEntryFileNames == null) {
23646 unsetOptions.add('entryFileNames');
23647 }
23648 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
23649};
23650function getExports(config, unsetOptions) {
23651 const configExports = config.exports;
23652 if (configExports == null) {
23653 unsetOptions.add('exports');
23654 }
23655 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
23656 return error(errInvalidExportOptionValue(configExports));
23657 }
23658 return configExports || 'auto';
23659}
23660const getGeneratedCode = (config, preferConst) => {
23661 const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
23662 return {
23663 arrowFunctions: configWithPreset.arrowFunctions === true,
23664 constBindings: configWithPreset.constBindings === true || preferConst,
23665 objectShorthand: configWithPreset.objectShorthand === true,
23666 reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
23667 symbols: configWithPreset.symbols === true
23668 };
23669};
23670const getIndent = (config, compact) => {
23671 if (compact) {
23672 return '';
23673 }
23674 const configIndent = config.indent;
23675 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
23676};
23677const ALLOWED_INTEROP_TYPES = new Set([
23678 'auto',
23679 'esModule',
23680 'default',
23681 'defaultOnly',
23682 true,
23683 false
23684]);
23685const getInterop = (config, inputOptions) => {
23686 const configInterop = config.interop;
23687 const validatedInteropTypes = new Set();
23688 const validateInterop = (interop) => {
23689 if (!validatedInteropTypes.has(interop)) {
23690 validatedInteropTypes.add(interop);
23691 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
23692 return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
23693 }
23694 if (typeof interop === 'boolean') {
23695 warnDeprecation({
23696 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
23697 url: 'https://rollupjs.org/guide/en/#outputinterop'
23698 }, false, inputOptions);
23699 }
23700 }
23701 return interop;
23702 };
23703 if (typeof configInterop === 'function') {
23704 const interopPerId = Object.create(null);
23705 let defaultInterop = null;
23706 return id => id === null
23707 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
23708 : id in interopPerId
23709 ? interopPerId[id]
23710 : validateInterop((interopPerId[id] = configInterop(id)));
23711 }
23712 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
23713};
23714const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
23715 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
23716 if (configManualChunks) {
23717 if (inlineDynamicImports) {
23718 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
23719 }
23720 if (preserveModules) {
23721 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
23722 }
23723 }
23724 return configManualChunks || {};
23725};
23726const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
23727const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
23728 const configNamespaceToStringTag = config.namespaceToStringTag;
23729 if (configNamespaceToStringTag != null) {
23730 warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
23731 return configNamespaceToStringTag;
23732 }
23733 return generatedCode.symbols || false;
23734};
23735const getSourcemapBaseUrl = (config) => {
23736 const { sourcemapBaseUrl } = config;
23737 if (sourcemapBaseUrl) {
23738 if (isValidUrl(sourcemapBaseUrl)) {
23739 return sourcemapBaseUrl;
23740 }
23741 return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
23742 }
23743};
23744
23745function rollup(rawInputOptions) {
23746 return rollupInternal(rawInputOptions, null);
23747}
23748async function rollupInternal(rawInputOptions, watcher) {
23749 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
23750 initialiseTimers(inputOptions);
23751 const graph = new Graph(inputOptions, watcher);
23752 // remove the cache option from the memory after graph creation (cache is not used anymore)
23753 const useCache = rawInputOptions.cache !== false;
23754 delete inputOptions.cache;
23755 delete rawInputOptions.cache;
23756 timeStart('BUILD', 1);
23757 await catchUnfinishedHookActions(graph.pluginDriver, async () => {
23758 try {
23759 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
23760 await graph.build();
23761 }
23762 catch (err) {
23763 const watchFiles = Object.keys(graph.watchFiles);
23764 if (watchFiles.length > 0) {
23765 err.watchFiles = watchFiles;
23766 }
23767 await graph.pluginDriver.hookParallel('buildEnd', [err]);
23768 await graph.pluginDriver.hookParallel('closeBundle', []);
23769 throw err;
23770 }
23771 await graph.pluginDriver.hookParallel('buildEnd', []);
23772 });
23773 timeEnd('BUILD', 1);
23774 const result = {
23775 cache: useCache ? graph.getCache() : undefined,
23776 async close() {
23777 if (result.closed)
23778 return;
23779 result.closed = true;
23780 await graph.pluginDriver.hookParallel('closeBundle', []);
23781 },
23782 closed: false,
23783 async generate(rawOutputOptions) {
23784 if (result.closed)
23785 return error(errAlreadyClosed());
23786 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23787 },
23788 watchFiles: Object.keys(graph.watchFiles),
23789 async write(rawOutputOptions) {
23790 if (result.closed)
23791 return error(errAlreadyClosed());
23792 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23793 }
23794 };
23795 if (inputOptions.perf)
23796 result.getTimings = getTimings;
23797 return result;
23798}
23799async function getInputOptions(rawInputOptions, watchMode) {
23800 if (!rawInputOptions) {
23801 throw new Error('You must supply an options object to rollup');
23802 }
23803 const rawPlugins = getSortedValidatedPlugins('options', ensureArray(rawInputOptions.plugins));
23804 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
23805 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
23806 return { options, unsetOptions };
23807}
23808function applyOptionHook(watchMode) {
23809 return async (inputOptions, plugin) => {
23810 const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
23811 return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
23812 };
23813}
23814function normalizePlugins(plugins, anonymousPrefix) {
23815 plugins.forEach((plugin, index) => {
23816 if (!plugin.name) {
23817 plugin.name = `${anonymousPrefix}${index + 1}`;
23818 }
23819 });
23820}
23821function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
23822 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
23823 return catchUnfinishedHookActions(outputPluginDriver, async () => {
23824 const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
23825 const generated = await bundle.generate(isWrite);
23826 if (isWrite) {
23827 if (!outputOptions.dir && !outputOptions.file) {
23828 return error({
23829 code: 'MISSING_OPTION',
23830 message: 'You must specify "output.file" or "output.dir" for the build.'
23831 });
23832 }
23833 await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
23834 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
23835 }
23836 return createOutput(generated);
23837 });
23838}
23839function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
23840 if (!rawOutputOptions) {
23841 throw new Error('You must supply an options object');
23842 }
23843 const rawPlugins = ensureArray(rawOutputOptions.plugins);
23844 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
23845 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
23846 return {
23847 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
23848 outputPluginDriver
23849 };
23850}
23851function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
23852 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
23853 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
23854 return {
23855 ...pluginContext,
23856 emitFile: emitError,
23857 setAssetSource: emitError
23858 };
23859 }), inputOptions, unsetInputOptions);
23860}
23861function createOutput(outputBundle) {
23862 return {
23863 output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
23864 };
23865}
23866var SortingFileType;
23867(function (SortingFileType) {
23868 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
23869 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
23870 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
23871})(SortingFileType || (SortingFileType = {}));
23872function getSortingFileType(file) {
23873 if (file.type === 'asset') {
23874 return SortingFileType.ASSET;
23875 }
23876 if (file.isEntry) {
23877 return SortingFileType.ENTRY_CHUNK;
23878 }
23879 return SortingFileType.SECONDARY_CHUNK;
23880}
23881async function writeOutputFile(outputFile, outputOptions) {
23882 const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
23883 // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
23884 await promises.mkdir(dirname(fileName), { recursive: true });
23885 let writeSourceMapPromise;
23886 let source;
23887 if (outputFile.type === 'asset') {
23888 source = outputFile.source;
23889 }
23890 else {
23891 source = outputFile.code;
23892 if (outputOptions.sourcemap && outputFile.map) {
23893 let url;
23894 if (outputOptions.sourcemap === 'inline') {
23895 url = outputFile.map.toUrl();
23896 }
23897 else {
23898 const { sourcemapBaseUrl } = outputOptions;
23899 const sourcemapFileName = `${basename(outputFile.fileName)}.map`;
23900 url = sourcemapBaseUrl
23901 ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
23902 : sourcemapFileName;
23903 writeSourceMapPromise = promises.writeFile(`${fileName}.map`, outputFile.map.toString());
23904 }
23905 if (outputOptions.sourcemap !== 'hidden') {
23906 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
23907 }
23908 }
23909 }
23910 return Promise.all([promises.writeFile(fileName, source), writeSourceMapPromise]);
23911}
23912/**
23913 * Auxiliary function for defining rollup configuration
23914 * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
23915 * @param options
23916 */
23917function defineConfig(options) {
23918 return options;
23919}
23920
23921class WatchEmitter extends EventEmitter {
23922 constructor() {
23923 super();
23924 this.awaitedHandlers = Object.create(null);
23925 // Allows more than 10 bundles to be watched without
23926 // showing the `MaxListenersExceededWarning` to the user.
23927 this.setMaxListeners(Infinity);
23928 }
23929 // Will be overwritten by Rollup
23930 async close() { }
23931 emitAndAwait(event, ...args) {
23932 this.emit(event, ...args);
23933 return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
23934 }
23935 onCurrentAwaited(event, listener) {
23936 this.getHandlers(event).push(listener);
23937 return this;
23938 }
23939 removeAwaited() {
23940 this.awaitedHandlers = {};
23941 return this;
23942 }
23943 getHandlers(event) {
23944 return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
23945 }
23946}
23947
23948let fsEvents;
23949let fsEventsImportError;
23950async function loadFsEvents() {
23951 try {
23952 ({ default: fsEvents } = await import('fsevents'));
23953 }
23954 catch (err) {
23955 fsEventsImportError = err;
23956 }
23957}
23958// A call to this function will be injected into the chokidar code
23959function getFsEvents() {
23960 if (fsEventsImportError)
23961 throw fsEventsImportError;
23962 return fsEvents;
23963}
23964
23965const fseventsImporter = /*#__PURE__*/Object.defineProperty({
23966 __proto__: null,
23967 loadFsEvents,
23968 getFsEvents
23969}, Symbol.toStringTag, { value: 'Module' });
23970
23971function watch(configs) {
23972 const emitter = new WatchEmitter();
23973 const configArray = ensureArray(configs);
23974 const watchConfigs = configArray.filter(config => config.watch !== false);
23975 if (watchConfigs.length === 0) {
23976 return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
23977 }
23978 loadFsEvents()
23979 .then(() => import('./watch.js'))
23980 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
23981 return emitter;
23982}
23983
23984export { createFilter, defaultOnWarn, defineConfig, ensureArray, fseventsImporter, generatedCodePresets, getAugmentedNamespace, objectifyOption, objectifyOptionWithPresets, picomatch$1 as picomatch, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };
Note: See TracBrowser for help on using the repository browser.