1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | 'use strict';
|
12 |
|
13 | var fs = require('fs');
|
14 | var sysPath = require('path');
|
15 | var crypto = require('crypto');
|
16 | var require$$0$1 = require('events');
|
17 |
|
18 | function _interopNamespaceDefaultOnly(e) {
|
19 | return {__proto__: null, 'default': e};
|
20 | }
|
21 |
|
22 | var version = "2.33.1";
|
23 |
|
24 | function ensureArray(items) {
|
25 | if (Array.isArray(items)) {
|
26 | return items.filter(Boolean);
|
27 | }
|
28 | if (items) {
|
29 | return [items];
|
30 | }
|
31 | return [];
|
32 | }
|
33 |
|
34 | const defaultOnWarn = warning => console.warn(warning.message || warning);
|
35 | function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
|
36 | const validOptionSet = new Set(validOptions);
|
37 | const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
|
38 | if (unknownOptions.length > 0) {
|
39 | warn({
|
40 | code: 'UNKNOWN_OPTION',
|
41 | message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
|
42 | ...validOptionSet
|
43 | ]
|
44 | .sort()
|
45 | .join(', ')}`
|
46 | });
|
47 | }
|
48 | }
|
49 |
|
50 | const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
|
51 | const relativePath = /^\.?\.\//;
|
52 | function isAbsolute(path) {
|
53 | return absolutePath.test(path);
|
54 | }
|
55 | function isRelative(path) {
|
56 | return relativePath.test(path);
|
57 | }
|
58 | function normalize(path) {
|
59 | if (path.indexOf('\\') == -1)
|
60 | return path;
|
61 | return path.replace(/\\/g, '/');
|
62 | }
|
63 |
|
64 | function sanitizeFileName(name) {
|
65 | return name.replace(/[\0?*]/g, '_');
|
66 | }
|
67 |
|
68 | function getAliasName(id) {
|
69 | const base = sysPath.basename(id);
|
70 | return base.substr(0, base.length - sysPath.extname(id).length);
|
71 | }
|
72 | function relativeId(id) {
|
73 | if (typeof process === 'undefined' || !isAbsolute(id))
|
74 | return id;
|
75 | return sysPath.relative(process.cwd(), id);
|
76 | }
|
77 | function isPlainPathFragment(name) {
|
78 |
|
79 | return (name[0] !== '/' &&
|
80 | !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
|
81 | sanitizeFileName(name) === name &&
|
82 | !isAbsolute(name));
|
83 | }
|
84 |
|
85 | let fsEvents;
|
86 | let fsEventsImportError;
|
87 | function loadFsEvents() {
|
88 | return Promise.resolve().then(function () { return _interopNamespaceDefaultOnly(require('fsevents')); })
|
89 | .then(namespace => {
|
90 | fsEvents = namespace.default;
|
91 | })
|
92 | .catch(err => {
|
93 | fsEventsImportError = err;
|
94 | });
|
95 | }
|
96 |
|
97 | function getFsEvents() {
|
98 | if (fsEventsImportError)
|
99 | throw fsEventsImportError;
|
100 | return fsEvents;
|
101 | }
|
102 |
|
103 | var fseventsImporter = {
|
104 | __proto__: null,
|
105 | loadFsEvents: loadFsEvents,
|
106 | getFsEvents: getFsEvents
|
107 | };
|
108 |
|
109 | var charToInteger = {};
|
110 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
|
111 | for (var i = 0; i < chars.length; i++) {
|
112 | charToInteger[chars.charCodeAt(i)] = i;
|
113 | }
|
114 | function decode(mappings) {
|
115 | var decoded = [];
|
116 | var line = [];
|
117 | var segment = [
|
118 | 0,
|
119 | 0,
|
120 | 0,
|
121 | 0,
|
122 | 0,
|
123 | ];
|
124 | var j = 0;
|
125 | for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
|
126 | var c = mappings.charCodeAt(i);
|
127 | if (c === 44) {
|
128 | segmentify(line, segment, j);
|
129 | j = 0;
|
130 | }
|
131 | else if (c === 59) {
|
132 | segmentify(line, segment, j);
|
133 | j = 0;
|
134 | decoded.push(line);
|
135 | line = [];
|
136 | segment[0] = 0;
|
137 | }
|
138 | else {
|
139 | var integer = charToInteger[c];
|
140 | if (integer === undefined) {
|
141 | throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
|
142 | }
|
143 | var hasContinuationBit = integer & 32;
|
144 | integer &= 31;
|
145 | value += integer << shift;
|
146 | if (hasContinuationBit) {
|
147 | shift += 5;
|
148 | }
|
149 | else {
|
150 | var shouldNegate = value & 1;
|
151 | value >>>= 1;
|
152 | if (shouldNegate) {
|
153 | value = value === 0 ? -0x80000000 : -value;
|
154 | }
|
155 | segment[j] += value;
|
156 | j++;
|
157 | value = shift = 0;
|
158 | }
|
159 | }
|
160 | }
|
161 | segmentify(line, segment, j);
|
162 | decoded.push(line);
|
163 | return decoded;
|
164 | }
|
165 | function segmentify(line, segment, j) {
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 | if (j === 4)
|
174 | line.push([segment[0], segment[1], segment[2], segment[3]]);
|
175 | else if (j === 5)
|
176 | line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
|
177 | else if (j === 1)
|
178 | line.push([segment[0]]);
|
179 | }
|
180 | function encode(decoded) {
|
181 | var sourceFileIndex = 0;
|
182 | var sourceCodeLine = 0;
|
183 | var sourceCodeColumn = 0;
|
184 | var nameIndex = 0;
|
185 | var mappings = '';
|
186 | for (var i = 0; i < decoded.length; i++) {
|
187 | var line = decoded[i];
|
188 | if (i > 0)
|
189 | mappings += ';';
|
190 | if (line.length === 0)
|
191 | continue;
|
192 | var generatedCodeColumn = 0;
|
193 | var lineMappings = [];
|
194 | for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
|
195 | var segment = line_1[_i];
|
196 | var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
|
197 | generatedCodeColumn = segment[0];
|
198 | if (segment.length > 1) {
|
199 | segmentMappings +=
|
200 | encodeInteger(segment[1] - sourceFileIndex) +
|
201 | encodeInteger(segment[2] - sourceCodeLine) +
|
202 | encodeInteger(segment[3] - sourceCodeColumn);
|
203 | sourceFileIndex = segment[1];
|
204 | sourceCodeLine = segment[2];
|
205 | sourceCodeColumn = segment[3];
|
206 | }
|
207 | if (segment.length === 5) {
|
208 | segmentMappings += encodeInteger(segment[4] - nameIndex);
|
209 | nameIndex = segment[4];
|
210 | }
|
211 | lineMappings.push(segmentMappings);
|
212 | }
|
213 | mappings += lineMappings.join(',');
|
214 | }
|
215 | return mappings;
|
216 | }
|
217 | function encodeInteger(num) {
|
218 | var result = '';
|
219 | num = num < 0 ? (-num << 1) | 1 : num << 1;
|
220 | do {
|
221 | var clamped = num & 31;
|
222 | num >>>= 5;
|
223 | if (num > 0) {
|
224 | clamped |= 32;
|
225 | }
|
226 | result += chars[clamped];
|
227 | } while (num > 0);
|
228 | return result;
|
229 | }
|
230 |
|
231 | var BitSet = function BitSet(arg) {
|
232 | this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
|
233 | };
|
234 |
|
235 | BitSet.prototype.add = function add (n) {
|
236 | this.bits[n >> 5] |= 1 << (n & 31);
|
237 | };
|
238 |
|
239 | BitSet.prototype.has = function has (n) {
|
240 | return !!(this.bits[n >> 5] & (1 << (n & 31)));
|
241 | };
|
242 |
|
243 | var Chunk = function Chunk(start, end, content) {
|
244 | this.start = start;
|
245 | this.end = end;
|
246 | this.original = content;
|
247 |
|
248 | this.intro = '';
|
249 | this.outro = '';
|
250 |
|
251 | this.content = content;
|
252 | this.storeName = false;
|
253 | this.edited = false;
|
254 |
|
255 |
|
256 | Object.defineProperties(this, {
|
257 | previous: { writable: true, value: null },
|
258 | next: { writable: true, value: null }
|
259 | });
|
260 | };
|
261 |
|
262 | Chunk.prototype.appendLeft = function appendLeft (content) {
|
263 | this.outro += content;
|
264 | };
|
265 |
|
266 | Chunk.prototype.appendRight = function appendRight (content) {
|
267 | this.intro = this.intro + content;
|
268 | };
|
269 |
|
270 | Chunk.prototype.clone = function clone () {
|
271 | var chunk = new Chunk(this.start, this.end, this.original);
|
272 |
|
273 | chunk.intro = this.intro;
|
274 | chunk.outro = this.outro;
|
275 | chunk.content = this.content;
|
276 | chunk.storeName = this.storeName;
|
277 | chunk.edited = this.edited;
|
278 |
|
279 | return chunk;
|
280 | };
|
281 |
|
282 | Chunk.prototype.contains = function contains (index) {
|
283 | return this.start < index && index < this.end;
|
284 | };
|
285 |
|
286 | Chunk.prototype.eachNext = function eachNext (fn) {
|
287 | var chunk = this;
|
288 | while (chunk) {
|
289 | fn(chunk);
|
290 | chunk = chunk.next;
|
291 | }
|
292 | };
|
293 |
|
294 | Chunk.prototype.eachPrevious = function eachPrevious (fn) {
|
295 | var chunk = this;
|
296 | while (chunk) {
|
297 | fn(chunk);
|
298 | chunk = chunk.previous;
|
299 | }
|
300 | };
|
301 |
|
302 | Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
|
303 | this.content = content;
|
304 | if (!contentOnly) {
|
305 | this.intro = '';
|
306 | this.outro = '';
|
307 | }
|
308 | this.storeName = storeName;
|
309 |
|
310 | this.edited = true;
|
311 |
|
312 | return this;
|
313 | };
|
314 |
|
315 | Chunk.prototype.prependLeft = function prependLeft (content) {
|
316 | this.outro = content + this.outro;
|
317 | };
|
318 |
|
319 | Chunk.prototype.prependRight = function prependRight (content) {
|
320 | this.intro = content + this.intro;
|
321 | };
|
322 |
|
323 | Chunk.prototype.split = function split (index) {
|
324 | var sliceIndex = index - this.start;
|
325 |
|
326 | var originalBefore = this.original.slice(0, sliceIndex);
|
327 | var originalAfter = this.original.slice(sliceIndex);
|
328 |
|
329 | this.original = originalBefore;
|
330 |
|
331 | var newChunk = new Chunk(index, this.end, originalAfter);
|
332 | newChunk.outro = this.outro;
|
333 | this.outro = '';
|
334 |
|
335 | this.end = index;
|
336 |
|
337 | if (this.edited) {
|
338 |
|
339 | newChunk.edit('', false);
|
340 | this.content = '';
|
341 | } else {
|
342 | this.content = originalBefore;
|
343 | }
|
344 |
|
345 | newChunk.next = this.next;
|
346 | if (newChunk.next) { newChunk.next.previous = newChunk; }
|
347 | newChunk.previous = this;
|
348 | this.next = newChunk;
|
349 |
|
350 | return newChunk;
|
351 | };
|
352 |
|
353 | Chunk.prototype.toString = function toString () {
|
354 | return this.intro + this.content + this.outro;
|
355 | };
|
356 |
|
357 | Chunk.prototype.trimEnd = function trimEnd (rx) {
|
358 | this.outro = this.outro.replace(rx, '');
|
359 | if (this.outro.length) { return true; }
|
360 |
|
361 | var trimmed = this.content.replace(rx, '');
|
362 |
|
363 | if (trimmed.length) {
|
364 | if (trimmed !== this.content) {
|
365 | this.split(this.start + trimmed.length).edit('', undefined, true);
|
366 | }
|
367 | return true;
|
368 |
|
369 | } else {
|
370 | this.edit('', undefined, true);
|
371 |
|
372 | this.intro = this.intro.replace(rx, '');
|
373 | if (this.intro.length) { return true; }
|
374 | }
|
375 | };
|
376 |
|
377 | Chunk.prototype.trimStart = function trimStart (rx) {
|
378 | this.intro = this.intro.replace(rx, '');
|
379 | if (this.intro.length) { return true; }
|
380 |
|
381 | var trimmed = this.content.replace(rx, '');
|
382 |
|
383 | if (trimmed.length) {
|
384 | if (trimmed !== this.content) {
|
385 | this.split(this.end - trimmed.length);
|
386 | this.edit('', undefined, true);
|
387 | }
|
388 | return true;
|
389 |
|
390 | } else {
|
391 | this.edit('', undefined, true);
|
392 |
|
393 | this.outro = this.outro.replace(rx, '');
|
394 | if (this.outro.length) { return true; }
|
395 | }
|
396 | };
|
397 |
|
398 | var btoa = function () {
|
399 | throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
|
400 | };
|
401 | if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
|
402 | btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
|
403 | } else if (typeof Buffer === 'function') {
|
404 | btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
|
405 | }
|
406 |
|
407 | var SourceMap = function SourceMap(properties) {
|
408 | this.version = 3;
|
409 | this.file = properties.file;
|
410 | this.sources = properties.sources;
|
411 | this.sourcesContent = properties.sourcesContent;
|
412 | this.names = properties.names;
|
413 | this.mappings = encode(properties.mappings);
|
414 | };
|
415 |
|
416 | SourceMap.prototype.toString = function toString () {
|
417 | return JSON.stringify(this);
|
418 | };
|
419 |
|
420 | SourceMap.prototype.toUrl = function toUrl () {
|
421 | return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
|
422 | };
|
423 |
|
424 | function guessIndent(code) {
|
425 | var lines = code.split('\n');
|
426 |
|
427 | var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
|
428 | var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
|
429 |
|
430 | if (tabbed.length === 0 && spaced.length === 0) {
|
431 | return null;
|
432 | }
|
433 |
|
434 |
|
435 |
|
436 |
|
437 | if (tabbed.length >= spaced.length) {
|
438 | return '\t';
|
439 | }
|
440 |
|
441 |
|
442 | var min = spaced.reduce(function (previous, current) {
|
443 | var numSpaces = /^ +/.exec(current)[0].length;
|
444 | return Math.min(numSpaces, previous);
|
445 | }, Infinity);
|
446 |
|
447 | return new Array(min + 1).join(' ');
|
448 | }
|
449 |
|
450 | function getRelativePath(from, to) {
|
451 | var fromParts = from.split(/[/\\]/);
|
452 | var toParts = to.split(/[/\\]/);
|
453 |
|
454 | fromParts.pop();
|
455 |
|
456 | while (fromParts[0] === toParts[0]) {
|
457 | fromParts.shift();
|
458 | toParts.shift();
|
459 | }
|
460 |
|
461 | if (fromParts.length) {
|
462 | var i = fromParts.length;
|
463 | while (i--) { fromParts[i] = '..'; }
|
464 | }
|
465 |
|
466 | return fromParts.concat(toParts).join('/');
|
467 | }
|
468 |
|
469 | var toString = Object.prototype.toString;
|
470 |
|
471 | function isObject(thing) {
|
472 | return toString.call(thing) === '[object Object]';
|
473 | }
|
474 |
|
475 | function getLocator(source) {
|
476 | var originalLines = source.split('\n');
|
477 | var lineOffsets = [];
|
478 |
|
479 | for (var i = 0, pos = 0; i < originalLines.length; i++) {
|
480 | lineOffsets.push(pos);
|
481 | pos += originalLines[i].length + 1;
|
482 | }
|
483 |
|
484 | return function locate(index) {
|
485 | var i = 0;
|
486 | var j = lineOffsets.length;
|
487 | while (i < j) {
|
488 | var m = (i + j) >> 1;
|
489 | if (index < lineOffsets[m]) {
|
490 | j = m;
|
491 | } else {
|
492 | i = m + 1;
|
493 | }
|
494 | }
|
495 | var line = i - 1;
|
496 | var column = index - lineOffsets[line];
|
497 | return { line: line, column: column };
|
498 | };
|
499 | }
|
500 |
|
501 | var Mappings = function Mappings(hires) {
|
502 | this.hires = hires;
|
503 | this.generatedCodeLine = 0;
|
504 | this.generatedCodeColumn = 0;
|
505 | this.raw = [];
|
506 | this.rawSegments = this.raw[this.generatedCodeLine] = [];
|
507 | this.pending = null;
|
508 | };
|
509 |
|
510 | Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
|
511 | if (content.length) {
|
512 | var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
513 | if (nameIndex >= 0) {
|
514 | segment.push(nameIndex);
|
515 | }
|
516 | this.rawSegments.push(segment);
|
517 | } else if (this.pending) {
|
518 | this.rawSegments.push(this.pending);
|
519 | }
|
520 |
|
521 | this.advance(content);
|
522 | this.pending = null;
|
523 | };
|
524 |
|
525 | Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
|
526 | var originalCharIndex = chunk.start;
|
527 | var first = true;
|
528 |
|
529 | while (originalCharIndex < chunk.end) {
|
530 | if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
|
531 | this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
|
532 | }
|
533 |
|
534 | if (original[originalCharIndex] === '\n') {
|
535 | loc.line += 1;
|
536 | loc.column = 0;
|
537 | this.generatedCodeLine += 1;
|
538 | this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
539 | this.generatedCodeColumn = 0;
|
540 | first = true;
|
541 | } else {
|
542 | loc.column += 1;
|
543 | this.generatedCodeColumn += 1;
|
544 | first = false;
|
545 | }
|
546 |
|
547 | originalCharIndex += 1;
|
548 | }
|
549 |
|
550 | this.pending = null;
|
551 | };
|
552 |
|
553 | Mappings.prototype.advance = function advance (str) {
|
554 | if (!str) { return; }
|
555 |
|
556 | var lines = str.split('\n');
|
557 |
|
558 | if (lines.length > 1) {
|
559 | for (var i = 0; i < lines.length - 1; i++) {
|
560 | this.generatedCodeLine++;
|
561 | this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
562 | }
|
563 | this.generatedCodeColumn = 0;
|
564 | }
|
565 |
|
566 | this.generatedCodeColumn += lines[lines.length - 1].length;
|
567 | };
|
568 |
|
569 | var n = '\n';
|
570 |
|
571 | var warned = {
|
572 | insertLeft: false,
|
573 | insertRight: false,
|
574 | storeName: false
|
575 | };
|
576 |
|
577 | var MagicString = function MagicString(string, options) {
|
578 | if ( options === void 0 ) options = {};
|
579 |
|
580 | var chunk = new Chunk(0, string.length, string);
|
581 |
|
582 | Object.defineProperties(this, {
|
583 | original: { writable: true, value: string },
|
584 | outro: { writable: true, value: '' },
|
585 | intro: { writable: true, value: '' },
|
586 | firstChunk: { writable: true, value: chunk },
|
587 | lastChunk: { writable: true, value: chunk },
|
588 | lastSearchedChunk: { writable: true, value: chunk },
|
589 | byStart: { writable: true, value: {} },
|
590 | byEnd: { writable: true, value: {} },
|
591 | filename: { writable: true, value: options.filename },
|
592 | indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
|
593 | sourcemapLocations: { writable: true, value: new BitSet() },
|
594 | storedNames: { writable: true, value: {} },
|
595 | indentStr: { writable: true, value: guessIndent(string) }
|
596 | });
|
597 |
|
598 | this.byStart[0] = chunk;
|
599 | this.byEnd[string.length] = chunk;
|
600 | };
|
601 |
|
602 | MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
|
603 | this.sourcemapLocations.add(char);
|
604 | };
|
605 |
|
606 | MagicString.prototype.append = function append (content) {
|
607 | if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
|
608 |
|
609 | this.outro += content;
|
610 | return this;
|
611 | };
|
612 |
|
613 | MagicString.prototype.appendLeft = function appendLeft (index, content) {
|
614 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
615 |
|
616 | this._split(index);
|
617 |
|
618 | var chunk = this.byEnd[index];
|
619 |
|
620 | if (chunk) {
|
621 | chunk.appendLeft(content);
|
622 | } else {
|
623 | this.intro += content;
|
624 | }
|
625 | return this;
|
626 | };
|
627 |
|
628 | MagicString.prototype.appendRight = function appendRight (index, content) {
|
629 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
630 |
|
631 | this._split(index);
|
632 |
|
633 | var chunk = this.byStart[index];
|
634 |
|
635 | if (chunk) {
|
636 | chunk.appendRight(content);
|
637 | } else {
|
638 | this.outro += content;
|
639 | }
|
640 | return this;
|
641 | };
|
642 |
|
643 | MagicString.prototype.clone = function clone () {
|
644 | var cloned = new MagicString(this.original, { filename: this.filename });
|
645 |
|
646 | var originalChunk = this.firstChunk;
|
647 | var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
|
648 |
|
649 | while (originalChunk) {
|
650 | cloned.byStart[clonedChunk.start] = clonedChunk;
|
651 | cloned.byEnd[clonedChunk.end] = clonedChunk;
|
652 |
|
653 | var nextOriginalChunk = originalChunk.next;
|
654 | var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
|
655 |
|
656 | if (nextClonedChunk) {
|
657 | clonedChunk.next = nextClonedChunk;
|
658 | nextClonedChunk.previous = clonedChunk;
|
659 |
|
660 | clonedChunk = nextClonedChunk;
|
661 | }
|
662 |
|
663 | originalChunk = nextOriginalChunk;
|
664 | }
|
665 |
|
666 | cloned.lastChunk = clonedChunk;
|
667 |
|
668 | if (this.indentExclusionRanges) {
|
669 | cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
|
670 | }
|
671 |
|
672 | cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
|
673 |
|
674 | cloned.intro = this.intro;
|
675 | cloned.outro = this.outro;
|
676 |
|
677 | return cloned;
|
678 | };
|
679 |
|
680 | MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
|
681 | var this$1 = this;
|
682 |
|
683 | options = options || {};
|
684 |
|
685 | var sourceIndex = 0;
|
686 | var names = Object.keys(this.storedNames);
|
687 | var mappings = new Mappings(options.hires);
|
688 |
|
689 | var locate = getLocator(this.original);
|
690 |
|
691 | if (this.intro) {
|
692 | mappings.advance(this.intro);
|
693 | }
|
694 |
|
695 | this.firstChunk.eachNext(function (chunk) {
|
696 | var loc = locate(chunk.start);
|
697 |
|
698 | if (chunk.intro.length) { mappings.advance(chunk.intro); }
|
699 |
|
700 | if (chunk.edited) {
|
701 | mappings.addEdit(
|
702 | sourceIndex,
|
703 | chunk.content,
|
704 | loc,
|
705 | chunk.storeName ? names.indexOf(chunk.original) : -1
|
706 | );
|
707 | } else {
|
708 | mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
|
709 | }
|
710 |
|
711 | if (chunk.outro.length) { mappings.advance(chunk.outro); }
|
712 | });
|
713 |
|
714 | return {
|
715 | file: options.file ? options.file.split(/[/\\]/).pop() : null,
|
716 | sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
|
717 | sourcesContent: options.includeContent ? [this.original] : [null],
|
718 | names: names,
|
719 | mappings: mappings.raw
|
720 | };
|
721 | };
|
722 |
|
723 | MagicString.prototype.generateMap = function generateMap (options) {
|
724 | return new SourceMap(this.generateDecodedMap(options));
|
725 | };
|
726 |
|
727 | MagicString.prototype.getIndentString = function getIndentString () {
|
728 | return this.indentStr === null ? '\t' : this.indentStr;
|
729 | };
|
730 |
|
731 | MagicString.prototype.indent = function indent (indentStr, options) {
|
732 | var pattern = /^[^\r\n]/gm;
|
733 |
|
734 | if (isObject(indentStr)) {
|
735 | options = indentStr;
|
736 | indentStr = undefined;
|
737 | }
|
738 |
|
739 | indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
|
740 |
|
741 | if (indentStr === '') { return this; }
|
742 |
|
743 | options = options || {};
|
744 |
|
745 |
|
746 | var isExcluded = {};
|
747 |
|
748 | if (options.exclude) {
|
749 | var exclusions =
|
750 | typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
|
751 | exclusions.forEach(function (exclusion) {
|
752 | for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
|
753 | isExcluded[i] = true;
|
754 | }
|
755 | });
|
756 | }
|
757 |
|
758 | var shouldIndentNextCharacter = options.indentStart !== false;
|
759 | var replacer = function (match) {
|
760 | if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
|
761 | shouldIndentNextCharacter = true;
|
762 | return match;
|
763 | };
|
764 |
|
765 | this.intro = this.intro.replace(pattern, replacer);
|
766 |
|
767 | var charIndex = 0;
|
768 | var chunk = this.firstChunk;
|
769 |
|
770 | while (chunk) {
|
771 | var end = chunk.end;
|
772 |
|
773 | if (chunk.edited) {
|
774 | if (!isExcluded[charIndex]) {
|
775 | chunk.content = chunk.content.replace(pattern, replacer);
|
776 |
|
777 | if (chunk.content.length) {
|
778 | shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
|
779 | }
|
780 | }
|
781 | } else {
|
782 | charIndex = chunk.start;
|
783 |
|
784 | while (charIndex < end) {
|
785 | if (!isExcluded[charIndex]) {
|
786 | var char = this.original[charIndex];
|
787 |
|
788 | if (char === '\n') {
|
789 | shouldIndentNextCharacter = true;
|
790 | } else if (char !== '\r' && shouldIndentNextCharacter) {
|
791 | shouldIndentNextCharacter = false;
|
792 |
|
793 | if (charIndex === chunk.start) {
|
794 | chunk.prependRight(indentStr);
|
795 | } else {
|
796 | this._splitChunk(chunk, charIndex);
|
797 | chunk = chunk.next;
|
798 | chunk.prependRight(indentStr);
|
799 | }
|
800 | }
|
801 | }
|
802 |
|
803 | charIndex += 1;
|
804 | }
|
805 | }
|
806 |
|
807 | charIndex = chunk.end;
|
808 | chunk = chunk.next;
|
809 | }
|
810 |
|
811 | this.outro = this.outro.replace(pattern, replacer);
|
812 |
|
813 | return this;
|
814 | };
|
815 |
|
816 | MagicString.prototype.insert = function insert () {
|
817 | throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
|
818 | };
|
819 |
|
820 | MagicString.prototype.insertLeft = function insertLeft (index, content) {
|
821 | if (!warned.insertLeft) {
|
822 | console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead');
|
823 | warned.insertLeft = true;
|
824 | }
|
825 |
|
826 | return this.appendLeft(index, content);
|
827 | };
|
828 |
|
829 | MagicString.prototype.insertRight = function insertRight (index, content) {
|
830 | if (!warned.insertRight) {
|
831 | console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead');
|
832 | warned.insertRight = true;
|
833 | }
|
834 |
|
835 | return this.prependRight(index, content);
|
836 | };
|
837 |
|
838 | MagicString.prototype.move = function move (start, end, index) {
|
839 | if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
|
840 |
|
841 | this._split(start);
|
842 | this._split(end);
|
843 | this._split(index);
|
844 |
|
845 | var first = this.byStart[start];
|
846 | var last = this.byEnd[end];
|
847 |
|
848 | var oldLeft = first.previous;
|
849 | var oldRight = last.next;
|
850 |
|
851 | var newRight = this.byStart[index];
|
852 | if (!newRight && last === this.lastChunk) { return this; }
|
853 | var newLeft = newRight ? newRight.previous : this.lastChunk;
|
854 |
|
855 | if (oldLeft) { oldLeft.next = oldRight; }
|
856 | if (oldRight) { oldRight.previous = oldLeft; }
|
857 |
|
858 | if (newLeft) { newLeft.next = first; }
|
859 | if (newRight) { newRight.previous = last; }
|
860 |
|
861 | if (!first.previous) { this.firstChunk = last.next; }
|
862 | if (!last.next) {
|
863 | this.lastChunk = first.previous;
|
864 | this.lastChunk.next = null;
|
865 | }
|
866 |
|
867 | first.previous = newLeft;
|
868 | last.next = newRight || null;
|
869 |
|
870 | if (!newLeft) { this.firstChunk = first; }
|
871 | if (!newRight) { this.lastChunk = last; }
|
872 | return this;
|
873 | };
|
874 |
|
875 | MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
|
876 | if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
|
877 |
|
878 | while (start < 0) { start += this.original.length; }
|
879 | while (end < 0) { end += this.original.length; }
|
880 |
|
881 | if (end > this.original.length) { throw new Error('end is out of bounds'); }
|
882 | if (start === end)
|
883 | { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
|
884 |
|
885 | this._split(start);
|
886 | this._split(end);
|
887 |
|
888 | if (options === true) {
|
889 | if (!warned.storeName) {
|
890 | console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string');
|
891 | warned.storeName = true;
|
892 | }
|
893 |
|
894 | options = { storeName: true };
|
895 | }
|
896 | var storeName = options !== undefined ? options.storeName : false;
|
897 | var contentOnly = options !== undefined ? options.contentOnly : false;
|
898 |
|
899 | if (storeName) {
|
900 | var original = this.original.slice(start, end);
|
901 | this.storedNames[original] = true;
|
902 | }
|
903 |
|
904 | var first = this.byStart[start];
|
905 | var last = this.byEnd[end];
|
906 |
|
907 | if (first) {
|
908 | if (end > first.end && first.next !== this.byStart[first.end]) {
|
909 | throw new Error('Cannot overwrite across a split point');
|
910 | }
|
911 |
|
912 | first.edit(content, storeName, contentOnly);
|
913 |
|
914 | if (first !== last) {
|
915 | var chunk = first.next;
|
916 | while (chunk !== last) {
|
917 | chunk.edit('', false);
|
918 | chunk = chunk.next;
|
919 | }
|
920 |
|
921 | chunk.edit('', false);
|
922 | }
|
923 | } else {
|
924 |
|
925 | var newChunk = new Chunk(start, end, '').edit(content, storeName);
|
926 |
|
927 |
|
928 | last.next = newChunk;
|
929 | newChunk.previous = last;
|
930 | }
|
931 | return this;
|
932 | };
|
933 |
|
934 | MagicString.prototype.prepend = function prepend (content) {
|
935 | if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
|
936 |
|
937 | this.intro = content + this.intro;
|
938 | return this;
|
939 | };
|
940 |
|
941 | MagicString.prototype.prependLeft = function prependLeft (index, content) {
|
942 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
943 |
|
944 | this._split(index);
|
945 |
|
946 | var chunk = this.byEnd[index];
|
947 |
|
948 | if (chunk) {
|
949 | chunk.prependLeft(content);
|
950 | } else {
|
951 | this.intro = content + this.intro;
|
952 | }
|
953 | return this;
|
954 | };
|
955 |
|
956 | MagicString.prototype.prependRight = function prependRight (index, content) {
|
957 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
958 |
|
959 | this._split(index);
|
960 |
|
961 | var chunk = this.byStart[index];
|
962 |
|
963 | if (chunk) {
|
964 | chunk.prependRight(content);
|
965 | } else {
|
966 | this.outro = content + this.outro;
|
967 | }
|
968 | return this;
|
969 | };
|
970 |
|
971 | MagicString.prototype.remove = function remove (start, end) {
|
972 | while (start < 0) { start += this.original.length; }
|
973 | while (end < 0) { end += this.original.length; }
|
974 |
|
975 | if (start === end) { return this; }
|
976 |
|
977 | if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
|
978 | if (start > end) { throw new Error('end must be greater than start'); }
|
979 |
|
980 | this._split(start);
|
981 | this._split(end);
|
982 |
|
983 | var chunk = this.byStart[start];
|
984 |
|
985 | while (chunk) {
|
986 | chunk.intro = '';
|
987 | chunk.outro = '';
|
988 | chunk.edit('');
|
989 |
|
990 | chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
991 | }
|
992 | return this;
|
993 | };
|
994 |
|
995 | MagicString.prototype.lastChar = function lastChar () {
|
996 | if (this.outro.length)
|
997 | { return this.outro[this.outro.length - 1]; }
|
998 | var chunk = this.lastChunk;
|
999 | do {
|
1000 | if (chunk.outro.length)
|
1001 | { return chunk.outro[chunk.outro.length - 1]; }
|
1002 | if (chunk.content.length)
|
1003 | { return chunk.content[chunk.content.length - 1]; }
|
1004 | if (chunk.intro.length)
|
1005 | { return chunk.intro[chunk.intro.length - 1]; }
|
1006 | } while (chunk = chunk.previous);
|
1007 | if (this.intro.length)
|
1008 | { return this.intro[this.intro.length - 1]; }
|
1009 | return '';
|
1010 | };
|
1011 |
|
1012 | MagicString.prototype.lastLine = function lastLine () {
|
1013 | var lineIndex = this.outro.lastIndexOf(n);
|
1014 | if (lineIndex !== -1)
|
1015 | { return this.outro.substr(lineIndex + 1); }
|
1016 | var lineStr = this.outro;
|
1017 | var chunk = this.lastChunk;
|
1018 | do {
|
1019 | if (chunk.outro.length > 0) {
|
1020 | lineIndex = chunk.outro.lastIndexOf(n);
|
1021 | if (lineIndex !== -1)
|
1022 | { return chunk.outro.substr(lineIndex + 1) + lineStr; }
|
1023 | lineStr = chunk.outro + lineStr;
|
1024 | }
|
1025 |
|
1026 | if (chunk.content.length > 0) {
|
1027 | lineIndex = chunk.content.lastIndexOf(n);
|
1028 | if (lineIndex !== -1)
|
1029 | { return chunk.content.substr(lineIndex + 1) + lineStr; }
|
1030 | lineStr = chunk.content + lineStr;
|
1031 | }
|
1032 |
|
1033 | if (chunk.intro.length > 0) {
|
1034 | lineIndex = chunk.intro.lastIndexOf(n);
|
1035 | if (lineIndex !== -1)
|
1036 | { return chunk.intro.substr(lineIndex + 1) + lineStr; }
|
1037 | lineStr = chunk.intro + lineStr;
|
1038 | }
|
1039 | } while (chunk = chunk.previous);
|
1040 | lineIndex = this.intro.lastIndexOf(n);
|
1041 | if (lineIndex !== -1)
|
1042 | { return this.intro.substr(lineIndex + 1) + lineStr; }
|
1043 | return this.intro + lineStr;
|
1044 | };
|
1045 |
|
1046 | MagicString.prototype.slice = function slice (start, end) {
|
1047 | if ( start === void 0 ) start = 0;
|
1048 | if ( end === void 0 ) end = this.original.length;
|
1049 |
|
1050 | while (start < 0) { start += this.original.length; }
|
1051 | while (end < 0) { end += this.original.length; }
|
1052 |
|
1053 | var result = '';
|
1054 |
|
1055 |
|
1056 | var chunk = this.firstChunk;
|
1057 | while (chunk && (chunk.start > start || chunk.end <= start)) {
|
1058 |
|
1059 | if (chunk.start < end && chunk.end >= end) {
|
1060 | return result;
|
1061 | }
|
1062 |
|
1063 | chunk = chunk.next;
|
1064 | }
|
1065 |
|
1066 | if (chunk && chunk.edited && chunk.start !== start)
|
1067 | { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
|
1068 |
|
1069 | var startChunk = chunk;
|
1070 | while (chunk) {
|
1071 | if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
|
1072 | result += chunk.intro;
|
1073 | }
|
1074 |
|
1075 | var containsEnd = chunk.start < end && chunk.end >= end;
|
1076 | if (containsEnd && chunk.edited && chunk.end !== end)
|
1077 | { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
|
1078 |
|
1079 | var sliceStart = startChunk === chunk ? start - chunk.start : 0;
|
1080 | var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
|
1081 |
|
1082 | result += chunk.content.slice(sliceStart, sliceEnd);
|
1083 |
|
1084 | if (chunk.outro && (!containsEnd || chunk.end === end)) {
|
1085 | result += chunk.outro;
|
1086 | }
|
1087 |
|
1088 | if (containsEnd) {
|
1089 | break;
|
1090 | }
|
1091 |
|
1092 | chunk = chunk.next;
|
1093 | }
|
1094 |
|
1095 | return result;
|
1096 | };
|
1097 |
|
1098 |
|
1099 | MagicString.prototype.snip = function snip (start, end) {
|
1100 | var clone = this.clone();
|
1101 | clone.remove(0, start);
|
1102 | clone.remove(end, clone.original.length);
|
1103 |
|
1104 | return clone;
|
1105 | };
|
1106 |
|
1107 | MagicString.prototype._split = function _split (index) {
|
1108 | if (this.byStart[index] || this.byEnd[index]) { return; }
|
1109 |
|
1110 | var chunk = this.lastSearchedChunk;
|
1111 | var searchForward = index > chunk.end;
|
1112 |
|
1113 | while (chunk) {
|
1114 | if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
|
1115 |
|
1116 | chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
|
1117 | }
|
1118 | };
|
1119 |
|
1120 | MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
|
1121 | if (chunk.edited && chunk.content.length) {
|
1122 |
|
1123 | var loc = getLocator(this.original)(index);
|
1124 | throw new Error(
|
1125 | ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
|
1126 | );
|
1127 | }
|
1128 |
|
1129 | var newChunk = chunk.split(index);
|
1130 |
|
1131 | this.byEnd[index] = chunk;
|
1132 | this.byStart[index] = newChunk;
|
1133 | this.byEnd[newChunk.end] = newChunk;
|
1134 |
|
1135 | if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
|
1136 |
|
1137 | this.lastSearchedChunk = chunk;
|
1138 | return true;
|
1139 | };
|
1140 |
|
1141 | MagicString.prototype.toString = function toString () {
|
1142 | var str = this.intro;
|
1143 |
|
1144 | var chunk = this.firstChunk;
|
1145 | while (chunk) {
|
1146 | str += chunk.toString();
|
1147 | chunk = chunk.next;
|
1148 | }
|
1149 |
|
1150 | return str + this.outro;
|
1151 | };
|
1152 |
|
1153 | MagicString.prototype.isEmpty = function isEmpty () {
|
1154 | var chunk = this.firstChunk;
|
1155 | do {
|
1156 | if (chunk.intro.length && chunk.intro.trim() ||
|
1157 | chunk.content.length && chunk.content.trim() ||
|
1158 | chunk.outro.length && chunk.outro.trim())
|
1159 | { return false; }
|
1160 | } while (chunk = chunk.next);
|
1161 | return true;
|
1162 | };
|
1163 |
|
1164 | MagicString.prototype.length = function length () {
|
1165 | var chunk = this.firstChunk;
|
1166 | var length = 0;
|
1167 | do {
|
1168 | length += chunk.intro.length + chunk.content.length + chunk.outro.length;
|
1169 | } while (chunk = chunk.next);
|
1170 | return length;
|
1171 | };
|
1172 |
|
1173 | MagicString.prototype.trimLines = function trimLines () {
|
1174 | return this.trim('[\\r\\n]');
|
1175 | };
|
1176 |
|
1177 | MagicString.prototype.trim = function trim (charType) {
|
1178 | return this.trimStart(charType).trimEnd(charType);
|
1179 | };
|
1180 |
|
1181 | MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
|
1182 | var rx = new RegExp((charType || '\\s') + '+$');
|
1183 |
|
1184 | this.outro = this.outro.replace(rx, '');
|
1185 | if (this.outro.length) { return true; }
|
1186 |
|
1187 | var chunk = this.lastChunk;
|
1188 |
|
1189 | do {
|
1190 | var end = chunk.end;
|
1191 | var aborted = chunk.trimEnd(rx);
|
1192 |
|
1193 |
|
1194 | if (chunk.end !== end) {
|
1195 | if (this.lastChunk === chunk) {
|
1196 | this.lastChunk = chunk.next;
|
1197 | }
|
1198 |
|
1199 | this.byEnd[chunk.end] = chunk;
|
1200 | this.byStart[chunk.next.start] = chunk.next;
|
1201 | this.byEnd[chunk.next.end] = chunk.next;
|
1202 | }
|
1203 |
|
1204 | if (aborted) { return true; }
|
1205 | chunk = chunk.previous;
|
1206 | } while (chunk);
|
1207 |
|
1208 | return false;
|
1209 | };
|
1210 |
|
1211 | MagicString.prototype.trimEnd = function trimEnd (charType) {
|
1212 | this.trimEndAborted(charType);
|
1213 | return this;
|
1214 | };
|
1215 | MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
|
1216 | var rx = new RegExp('^' + (charType || '\\s') + '+');
|
1217 |
|
1218 | this.intro = this.intro.replace(rx, '');
|
1219 | if (this.intro.length) { return true; }
|
1220 |
|
1221 | var chunk = this.firstChunk;
|
1222 |
|
1223 | do {
|
1224 | var end = chunk.end;
|
1225 | var aborted = chunk.trimStart(rx);
|
1226 |
|
1227 | if (chunk.end !== end) {
|
1228 |
|
1229 | if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
|
1230 |
|
1231 | this.byEnd[chunk.end] = chunk;
|
1232 | this.byStart[chunk.next.start] = chunk.next;
|
1233 | this.byEnd[chunk.next.end] = chunk.next;
|
1234 | }
|
1235 |
|
1236 | if (aborted) { return true; }
|
1237 | chunk = chunk.next;
|
1238 | } while (chunk);
|
1239 |
|
1240 | return false;
|
1241 | };
|
1242 |
|
1243 | MagicString.prototype.trimStart = function trimStart (charType) {
|
1244 | this.trimStartAborted(charType);
|
1245 | return this;
|
1246 | };
|
1247 |
|
1248 | var hasOwnProp = Object.prototype.hasOwnProperty;
|
1249 |
|
1250 | var Bundle = function Bundle(options) {
|
1251 | if ( options === void 0 ) options = {};
|
1252 |
|
1253 | this.intro = options.intro || '';
|
1254 | this.separator = options.separator !== undefined ? options.separator : '\n';
|
1255 | this.sources = [];
|
1256 | this.uniqueSources = [];
|
1257 | this.uniqueSourceIndexByFilename = {};
|
1258 | };
|
1259 |
|
1260 | Bundle.prototype.addSource = function addSource (source) {
|
1261 | if (source instanceof MagicString) {
|
1262 | return this.addSource({
|
1263 | content: source,
|
1264 | filename: source.filename,
|
1265 | separator: this.separator
|
1266 | });
|
1267 | }
|
1268 |
|
1269 | if (!isObject(source) || !source.content) {
|
1270 | throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
|
1271 | }
|
1272 |
|
1273 | ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
|
1274 | if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
|
1275 | });
|
1276 |
|
1277 | if (source.separator === undefined) {
|
1278 |
|
1279 | source.separator = this.separator;
|
1280 | }
|
1281 |
|
1282 | if (source.filename) {
|
1283 | if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
|
1284 | this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
|
1285 | this.uniqueSources.push({ filename: source.filename, content: source.content.original });
|
1286 | } else {
|
1287 | var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
|
1288 | if (source.content.original !== uniqueSource.content) {
|
1289 | throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
|
1290 | }
|
1291 | }
|
1292 | }
|
1293 |
|
1294 | this.sources.push(source);
|
1295 | return this;
|
1296 | };
|
1297 |
|
1298 | Bundle.prototype.append = function append (str, options) {
|
1299 | this.addSource({
|
1300 | content: new MagicString(str),
|
1301 | separator: (options && options.separator) || ''
|
1302 | });
|
1303 |
|
1304 | return this;
|
1305 | };
|
1306 |
|
1307 | Bundle.prototype.clone = function clone () {
|
1308 | var bundle = new Bundle({
|
1309 | intro: this.intro,
|
1310 | separator: this.separator
|
1311 | });
|
1312 |
|
1313 | this.sources.forEach(function (source) {
|
1314 | bundle.addSource({
|
1315 | filename: source.filename,
|
1316 | content: source.content.clone(),
|
1317 | separator: source.separator
|
1318 | });
|
1319 | });
|
1320 |
|
1321 | return bundle;
|
1322 | };
|
1323 |
|
1324 | Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
|
1325 | var this$1 = this;
|
1326 | if ( options === void 0 ) options = {};
|
1327 |
|
1328 | var names = [];
|
1329 | this.sources.forEach(function (source) {
|
1330 | Object.keys(source.content.storedNames).forEach(function (name) {
|
1331 | if (!~names.indexOf(name)) { names.push(name); }
|
1332 | });
|
1333 | });
|
1334 |
|
1335 | var mappings = new Mappings(options.hires);
|
1336 |
|
1337 | if (this.intro) {
|
1338 | mappings.advance(this.intro);
|
1339 | }
|
1340 |
|
1341 | this.sources.forEach(function (source, i) {
|
1342 | if (i > 0) {
|
1343 | mappings.advance(this$1.separator);
|
1344 | }
|
1345 |
|
1346 | var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
|
1347 | var magicString = source.content;
|
1348 | var locate = getLocator(magicString.original);
|
1349 |
|
1350 | if (magicString.intro) {
|
1351 | mappings.advance(magicString.intro);
|
1352 | }
|
1353 |
|
1354 | magicString.firstChunk.eachNext(function (chunk) {
|
1355 | var loc = locate(chunk.start);
|
1356 |
|
1357 | if (chunk.intro.length) { mappings.advance(chunk.intro); }
|
1358 |
|
1359 | if (source.filename) {
|
1360 | if (chunk.edited) {
|
1361 | mappings.addEdit(
|
1362 | sourceIndex,
|
1363 | chunk.content,
|
1364 | loc,
|
1365 | chunk.storeName ? names.indexOf(chunk.original) : -1
|
1366 | );
|
1367 | } else {
|
1368 | mappings.addUneditedChunk(
|
1369 | sourceIndex,
|
1370 | chunk,
|
1371 | magicString.original,
|
1372 | loc,
|
1373 | magicString.sourcemapLocations
|
1374 | );
|
1375 | }
|
1376 | } else {
|
1377 | mappings.advance(chunk.content);
|
1378 | }
|
1379 |
|
1380 | if (chunk.outro.length) { mappings.advance(chunk.outro); }
|
1381 | });
|
1382 |
|
1383 | if (magicString.outro) {
|
1384 | mappings.advance(magicString.outro);
|
1385 | }
|
1386 | });
|
1387 |
|
1388 | return {
|
1389 | file: options.file ? options.file.split(/[/\\]/).pop() : null,
|
1390 | sources: this.uniqueSources.map(function (source) {
|
1391 | return options.file ? getRelativePath(options.file, source.filename) : source.filename;
|
1392 | }),
|
1393 | sourcesContent: this.uniqueSources.map(function (source) {
|
1394 | return options.includeContent ? source.content : null;
|
1395 | }),
|
1396 | names: names,
|
1397 | mappings: mappings.raw
|
1398 | };
|
1399 | };
|
1400 |
|
1401 | Bundle.prototype.generateMap = function generateMap (options) {
|
1402 | return new SourceMap(this.generateDecodedMap(options));
|
1403 | };
|
1404 |
|
1405 | Bundle.prototype.getIndentString = function getIndentString () {
|
1406 | var indentStringCounts = {};
|
1407 |
|
1408 | this.sources.forEach(function (source) {
|
1409 | var indentStr = source.content.indentStr;
|
1410 |
|
1411 | if (indentStr === null) { return; }
|
1412 |
|
1413 | if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
|
1414 | indentStringCounts[indentStr] += 1;
|
1415 | });
|
1416 |
|
1417 | return (
|
1418 | Object.keys(indentStringCounts).sort(function (a, b) {
|
1419 | return indentStringCounts[a] - indentStringCounts[b];
|
1420 | })[0] || '\t'
|
1421 | );
|
1422 | };
|
1423 |
|
1424 | Bundle.prototype.indent = function indent (indentStr) {
|
1425 | var this$1 = this;
|
1426 |
|
1427 | if (!arguments.length) {
|
1428 | indentStr = this.getIndentString();
|
1429 | }
|
1430 |
|
1431 | if (indentStr === '') { return this; }
|
1432 |
|
1433 | var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
|
1434 |
|
1435 | this.sources.forEach(function (source, i) {
|
1436 | var separator = source.separator !== undefined ? source.separator : this$1.separator;
|
1437 | var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
|
1438 |
|
1439 | source.content.indent(indentStr, {
|
1440 | exclude: source.indentExclusionRanges,
|
1441 | indentStart: indentStart
|
1442 | });
|
1443 |
|
1444 | trailingNewline = source.content.lastChar() === '\n';
|
1445 | });
|
1446 |
|
1447 | if (this.intro) {
|
1448 | this.intro =
|
1449 | indentStr +
|
1450 | this.intro.replace(/^[^\n]/gm, function (match, index) {
|
1451 | return index > 0 ? indentStr + match : match;
|
1452 | });
|
1453 | }
|
1454 |
|
1455 | return this;
|
1456 | };
|
1457 |
|
1458 | Bundle.prototype.prepend = function prepend (str) {
|
1459 | this.intro = str + this.intro;
|
1460 | return this;
|
1461 | };
|
1462 |
|
1463 | Bundle.prototype.toString = function toString () {
|
1464 | var this$1 = this;
|
1465 |
|
1466 | var body = this.sources
|
1467 | .map(function (source, i) {
|
1468 | var separator = source.separator !== undefined ? source.separator : this$1.separator;
|
1469 | var str = (i > 0 ? separator : '') + source.content.toString();
|
1470 |
|
1471 | return str;
|
1472 | })
|
1473 | .join('');
|
1474 |
|
1475 | return this.intro + body;
|
1476 | };
|
1477 |
|
1478 | Bundle.prototype.isEmpty = function isEmpty () {
|
1479 | if (this.intro.length && this.intro.trim())
|
1480 | { return false; }
|
1481 | if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
|
1482 | { return false; }
|
1483 | return true;
|
1484 | };
|
1485 |
|
1486 | Bundle.prototype.length = function length () {
|
1487 | return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
|
1488 | };
|
1489 |
|
1490 | Bundle.prototype.trimLines = function trimLines () {
|
1491 | return this.trim('[\\r\\n]');
|
1492 | };
|
1493 |
|
1494 | Bundle.prototype.trim = function trim (charType) {
|
1495 | return this.trimStart(charType).trimEnd(charType);
|
1496 | };
|
1497 |
|
1498 | Bundle.prototype.trimStart = function trimStart (charType) {
|
1499 | var rx = new RegExp('^' + (charType || '\\s') + '+');
|
1500 | this.intro = this.intro.replace(rx, '');
|
1501 |
|
1502 | if (!this.intro) {
|
1503 | var source;
|
1504 | var i = 0;
|
1505 |
|
1506 | do {
|
1507 | source = this.sources[i++];
|
1508 | if (!source) {
|
1509 | break;
|
1510 | }
|
1511 | } while (!source.content.trimStartAborted(charType));
|
1512 | }
|
1513 |
|
1514 | return this;
|
1515 | };
|
1516 |
|
1517 | Bundle.prototype.trimEnd = function trimEnd (charType) {
|
1518 | var rx = new RegExp((charType || '\\s') + '+$');
|
1519 |
|
1520 | var source;
|
1521 | var i = this.sources.length - 1;
|
1522 |
|
1523 | do {
|
1524 | source = this.sources[i--];
|
1525 | if (!source) {
|
1526 | this.intro = this.intro.replace(rx, '');
|
1527 | break;
|
1528 | }
|
1529 | } while (!source.content.trimEndAborted(charType));
|
1530 |
|
1531 | return this;
|
1532 | };
|
1533 |
|
1534 | function relative(from, to) {
|
1535 | const fromParts = from.split(/[/\\]/).filter(Boolean);
|
1536 | const toParts = to.split(/[/\\]/).filter(Boolean);
|
1537 | if (fromParts[0] === '.')
|
1538 | fromParts.shift();
|
1539 | if (toParts[0] === '.')
|
1540 | toParts.shift();
|
1541 | while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
|
1542 | fromParts.shift();
|
1543 | toParts.shift();
|
1544 | }
|
1545 | while (toParts[0] === '..' && fromParts.length > 0) {
|
1546 | toParts.shift();
|
1547 | fromParts.pop();
|
1548 | }
|
1549 | while (fromParts.pop()) {
|
1550 | toParts.unshift('..');
|
1551 | }
|
1552 | return toParts.join('/');
|
1553 | }
|
1554 |
|
1555 | const ArrowFunctionExpression = 'ArrowFunctionExpression';
|
1556 | const BlockStatement = 'BlockStatement';
|
1557 | const CallExpression = 'CallExpression';
|
1558 | const ExpressionStatement = 'ExpressionStatement';
|
1559 | const FunctionExpression = 'FunctionExpression';
|
1560 | const Identifier = 'Identifier';
|
1561 | const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
|
1562 | const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
|
1563 | const Program = 'Program';
|
1564 | const Property = 'Property';
|
1565 | const ReturnStatement = 'ReturnStatement';
|
1566 |
|
1567 | function treeshakeNode(node, code, start, end) {
|
1568 | code.remove(start, end);
|
1569 | if (node.annotations) {
|
1570 | for (const annotation of node.annotations) {
|
1571 | if (annotation.start < start) {
|
1572 | code.remove(annotation.start, annotation.end);
|
1573 | }
|
1574 | else {
|
1575 | return;
|
1576 | }
|
1577 | }
|
1578 | }
|
1579 | }
|
1580 | function removeAnnotations(node, code) {
|
1581 | if (!node.annotations && node.parent.type === ExpressionStatement) {
|
1582 | node = node.parent;
|
1583 | }
|
1584 | if (node.annotations) {
|
1585 | for (const annotation of node.annotations) {
|
1586 | code.remove(annotation.start, annotation.end);
|
1587 | }
|
1588 | }
|
1589 | }
|
1590 |
|
1591 | const NO_SEMICOLON = { isNoStatement: true };
|
1592 |
|
1593 | function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
|
1594 | let searchPos, charCodeAfterSlash;
|
1595 | searchPos = code.indexOf(searchString, start);
|
1596 | while (true) {
|
1597 | start = code.indexOf('/', start);
|
1598 | if (start === -1 || start >= searchPos)
|
1599 | return searchPos;
|
1600 | charCodeAfterSlash = code.charCodeAt(++start);
|
1601 | ++start;
|
1602 |
|
1603 | start =
|
1604 | charCodeAfterSlash === 47
|
1605 | ? code.indexOf('\n', start) + 1
|
1606 | : code.indexOf('*/', start) + 2;
|
1607 | if (start > searchPos) {
|
1608 | searchPos = code.indexOf(searchString, start);
|
1609 | }
|
1610 | }
|
1611 | }
|
1612 | const WHITESPACE = /\s/;
|
1613 | function findNonWhiteSpace(code, index) {
|
1614 | while (index < code.length && WHITESPACE.test(code[index]))
|
1615 | index++;
|
1616 | return index;
|
1617 | }
|
1618 |
|
1619 |
|
1620 | function findFirstLineBreakOutsideComment(code) {
|
1621 | let lineBreakPos, charCodeAfterSlash, start = 0;
|
1622 | lineBreakPos = code.indexOf('\n', start);
|
1623 | while (true) {
|
1624 | start = code.indexOf('/', start);
|
1625 | if (start === -1 || start > lineBreakPos)
|
1626 | return [lineBreakPos, lineBreakPos + 1];
|
1627 |
|
1628 | charCodeAfterSlash = code.charCodeAt(start + 1);
|
1629 | if (charCodeAfterSlash === 47 )
|
1630 | return [start, lineBreakPos + 1];
|
1631 | start = code.indexOf('*/', start + 3) + 2;
|
1632 | if (start > lineBreakPos) {
|
1633 | lineBreakPos = code.indexOf('\n', start);
|
1634 | }
|
1635 | }
|
1636 | }
|
1637 | function renderStatementList(statements, code, start, end, options) {
|
1638 | let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
|
1639 | let nextNode = statements[0];
|
1640 | let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
|
1641 | if (nextNodeNeedsBoundaries) {
|
1642 | nextNodeStart =
|
1643 | start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
|
1644 | }
|
1645 | for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
|
1646 | currentNode = nextNode;
|
1647 | currentNodeStart = nextNodeStart;
|
1648 | currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
|
1649 | nextNode = statements[nextIndex];
|
1650 | nextNodeNeedsBoundaries =
|
1651 | nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
|
1652 | if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
|
1653 | nextNodeStart =
|
1654 | currentNode.end +
|
1655 | findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
|
1656 | if (currentNode.included) {
|
1657 | currentNodeNeedsBoundaries
|
1658 | ? currentNode.render(code, options, {
|
1659 | end: nextNodeStart,
|
1660 | start: currentNodeStart
|
1661 | })
|
1662 | : currentNode.render(code, options);
|
1663 | }
|
1664 | else {
|
1665 | treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
|
1666 | }
|
1667 | }
|
1668 | else {
|
1669 | currentNode.render(code, options);
|
1670 | }
|
1671 | }
|
1672 | }
|
1673 |
|
1674 | function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
|
1675 | const splitUpNodes = [];
|
1676 | let node, nextNode, nextNodeStart, contentEnd, char;
|
1677 | let separator = start - 1;
|
1678 | for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
|
1679 | nextNode = nodes[nextIndex];
|
1680 | if (node !== undefined) {
|
1681 | separator =
|
1682 | node.end +
|
1683 | findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
|
1684 | }
|
1685 | nextNodeStart = contentEnd =
|
1686 | separator +
|
1687 | 1 +
|
1688 | findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
|
1689 | while (((char = code.original.charCodeAt(nextNodeStart)),
|
1690 | char === 32 || char === 9 || char === 10 || char === 13) )
|
1691 | nextNodeStart++;
|
1692 | if (node !== undefined) {
|
1693 | splitUpNodes.push({
|
1694 | contentEnd,
|
1695 | end: nextNodeStart,
|
1696 | node,
|
1697 | separator,
|
1698 | start
|
1699 | });
|
1700 | }
|
1701 | node = nextNode;
|
1702 | start = nextNodeStart;
|
1703 | }
|
1704 | splitUpNodes.push({
|
1705 | contentEnd: end,
|
1706 | end,
|
1707 | node: node,
|
1708 | separator: null,
|
1709 | start
|
1710 | });
|
1711 | return splitUpNodes;
|
1712 | }
|
1713 |
|
1714 | function removeLineBreaks(code, start, end) {
|
1715 | while (true) {
|
1716 | const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
|
1717 | if (removeStart === -1) {
|
1718 | break;
|
1719 | }
|
1720 | code.remove(start + removeStart, (start += removeEnd));
|
1721 | }
|
1722 | }
|
1723 |
|
1724 | function getSystemExportStatement(exportedVariables, options) {
|
1725 | const _ = options.compact ? '' : ' ';
|
1726 | if (exportedVariables.length === 1 &&
|
1727 | options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
|
1728 | const variable = exportedVariables[0];
|
1729 | return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
|
1730 | }
|
1731 | else {
|
1732 | return `exports({${_}${exportedVariables
|
1733 | .map(variable => {
|
1734 | return options.exportNamesByVariable
|
1735 | .get(variable)
|
1736 | .map(exportName => `${exportName}:${_}${variable.getName()}`)
|
1737 | .join(`,${_}`);
|
1738 | })
|
1739 | .join(`,${_}`)}${_}})`;
|
1740 | }
|
1741 | }
|
1742 | function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
|
1743 | const _ = options.compact ? '' : ' ';
|
1744 | const s = options.compact ? '' : ';';
|
1745 | return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
|
1746 | .map(variable => {
|
1747 | return options.exportNamesByVariable
|
1748 | .get(variable)
|
1749 | .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
|
1750 | .join(`,${_}`);
|
1751 | })
|
1752 | .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
|
1753 | }
|
1754 |
|
1755 | const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
|
1756 | const base = 64;
|
1757 | function toBase64(num) {
|
1758 | let outStr = '';
|
1759 | do {
|
1760 | const curDigit = num % base;
|
1761 | num = Math.floor(num / base);
|
1762 | outStr = chars$1[curDigit] + outStr;
|
1763 | } while (num !== 0);
|
1764 | return outStr;
|
1765 | }
|
1766 |
|
1767 | const RESERVED_NAMES = {
|
1768 |
|
1769 | __proto__: null,
|
1770 | await: true,
|
1771 | break: true,
|
1772 | case: true,
|
1773 | catch: true,
|
1774 | class: true,
|
1775 | const: true,
|
1776 | continue: true,
|
1777 | debugger: true,
|
1778 | default: true,
|
1779 | delete: true,
|
1780 | do: true,
|
1781 | else: true,
|
1782 | enum: true,
|
1783 | eval: true,
|
1784 | export: true,
|
1785 | extends: true,
|
1786 | false: true,
|
1787 | finally: true,
|
1788 | for: true,
|
1789 | function: true,
|
1790 | if: true,
|
1791 | implements: true,
|
1792 | import: true,
|
1793 | in: true,
|
1794 | instanceof: true,
|
1795 | interface: true,
|
1796 | let: true,
|
1797 | new: true,
|
1798 | null: true,
|
1799 | package: true,
|
1800 | private: true,
|
1801 | protected: true,
|
1802 | public: true,
|
1803 | return: true,
|
1804 | static: true,
|
1805 | super: true,
|
1806 | switch: true,
|
1807 | this: true,
|
1808 | throw: true,
|
1809 | true: true,
|
1810 | try: true,
|
1811 | typeof: true,
|
1812 | undefined: true,
|
1813 | var: true,
|
1814 | void: true,
|
1815 | while: true,
|
1816 | with: true,
|
1817 | yield: true
|
1818 | };
|
1819 |
|
1820 | function getSafeName(baseName, usedNames) {
|
1821 | let safeName = baseName;
|
1822 | let count = 1;
|
1823 | while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
|
1824 | safeName = `${baseName}$${toBase64(count++)}`;
|
1825 | }
|
1826 | usedNames.add(safeName);
|
1827 | return safeName;
|
1828 | }
|
1829 |
|
1830 | const NO_ARGS = [];
|
1831 |
|
1832 | function getOrCreate(map, key, init) {
|
1833 | const existing = map.get(key);
|
1834 | if (existing) {
|
1835 | return existing;
|
1836 | }
|
1837 | const value = init();
|
1838 | map.set(key, value);
|
1839 | return value;
|
1840 | }
|
1841 |
|
1842 | const UnknownKey = Symbol('Unknown Key');
|
1843 | const EMPTY_PATH = [];
|
1844 | const UNKNOWN_PATH = [UnknownKey];
|
1845 | const EntitiesKey = Symbol('Entities');
|
1846 | class PathTracker {
|
1847 | constructor() {
|
1848 | this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
|
1849 | }
|
1850 | getEntities(path) {
|
1851 | let currentPaths = this.entityPaths;
|
1852 | for (const pathSegment of path) {
|
1853 | currentPaths = currentPaths[pathSegment] =
|
1854 | currentPaths[pathSegment] ||
|
1855 | Object.create(null, { [EntitiesKey]: { value: new Set() } });
|
1856 | }
|
1857 | return currentPaths[EntitiesKey];
|
1858 | }
|
1859 | }
|
1860 | const SHARED_RECURSION_TRACKER = new PathTracker();
|
1861 | class DiscriminatedPathTracker {
|
1862 | constructor() {
|
1863 | this.entityPaths = Object.create(null, {
|
1864 | [EntitiesKey]: { value: new Map() }
|
1865 | });
|
1866 | }
|
1867 | getEntities(path, discriminator) {
|
1868 | let currentPaths = this.entityPaths;
|
1869 | for (const pathSegment of path) {
|
1870 | currentPaths = currentPaths[pathSegment] =
|
1871 | currentPaths[pathSegment] ||
|
1872 | Object.create(null, { [EntitiesKey]: { value: new Map() } });
|
1873 | }
|
1874 | return getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
|
1875 | }
|
1876 | }
|
1877 |
|
1878 | function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
|
1879 | return Object.create(inheritedDescriptions, memberDescriptions);
|
1880 | }
|
1881 | const UnknownValue = Symbol('Unknown Value');
|
1882 | const UNKNOWN_EXPRESSION = {
|
1883 | deoptimizePath: () => { },
|
1884 | getLiteralValueAtPath: () => UnknownValue,
|
1885 | getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
|
1886 | hasEffectsWhenAccessedAtPath: path => path.length > 0,
|
1887 | hasEffectsWhenAssignedAtPath: path => path.length > 0,
|
1888 | hasEffectsWhenCalledAtPath: () => true,
|
1889 | include: () => { },
|
1890 | includeCallArguments(context, args) {
|
1891 | for (const arg of args) {
|
1892 | arg.include(context, false);
|
1893 | }
|
1894 | },
|
1895 | included: true,
|
1896 | toString: () => '[[UNKNOWN]]'
|
1897 | };
|
1898 | const UNDEFINED_EXPRESSION = {
|
1899 | deoptimizePath: () => { },
|
1900 | getLiteralValueAtPath: () => undefined,
|
1901 | getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
|
1902 | hasEffectsWhenAccessedAtPath: path => path.length > 0,
|
1903 | hasEffectsWhenAssignedAtPath: path => path.length > 0,
|
1904 | hasEffectsWhenCalledAtPath: () => true,
|
1905 | include: () => { },
|
1906 | includeCallArguments() { },
|
1907 | included: true,
|
1908 | toString: () => 'undefined'
|
1909 | };
|
1910 | const returnsUnknown = {
|
1911 | value: {
|
1912 | callsArgs: null,
|
1913 | mutatesSelf: false,
|
1914 | returns: null,
|
1915 | returnsPrimitive: UNKNOWN_EXPRESSION
|
1916 | }
|
1917 | };
|
1918 | const mutatesSelfReturnsUnknown = {
|
1919 | value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
|
1920 | };
|
1921 | const callsArgReturnsUnknown = {
|
1922 | value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
|
1923 | };
|
1924 | class UnknownArrayExpression {
|
1925 | constructor() {
|
1926 | this.included = false;
|
1927 | }
|
1928 | deoptimizePath() { }
|
1929 | getLiteralValueAtPath() {
|
1930 | return UnknownValue;
|
1931 | }
|
1932 | getReturnExpressionWhenCalledAtPath(path) {
|
1933 | if (path.length === 1) {
|
1934 | return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
|
1935 | }
|
1936 | return UNKNOWN_EXPRESSION;
|
1937 | }
|
1938 | hasEffectsWhenAccessedAtPath(path) {
|
1939 | return path.length > 1;
|
1940 | }
|
1941 | hasEffectsWhenAssignedAtPath(path) {
|
1942 | return path.length > 1;
|
1943 | }
|
1944 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
1945 | if (path.length === 1) {
|
1946 | return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
|
1947 | }
|
1948 | return true;
|
1949 | }
|
1950 | include() {
|
1951 | this.included = true;
|
1952 | }
|
1953 | includeCallArguments(context, args) {
|
1954 | for (const arg of args) {
|
1955 | arg.include(context, false);
|
1956 | }
|
1957 | }
|
1958 | toString() {
|
1959 | return '[[UNKNOWN ARRAY]]';
|
1960 | }
|
1961 | }
|
1962 | const returnsArray = {
|
1963 | value: {
|
1964 | callsArgs: null,
|
1965 | mutatesSelf: false,
|
1966 | returns: UnknownArrayExpression,
|
1967 | returnsPrimitive: null
|
1968 | }
|
1969 | };
|
1970 | const mutatesSelfReturnsArray = {
|
1971 | value: {
|
1972 | callsArgs: null,
|
1973 | mutatesSelf: true,
|
1974 | returns: UnknownArrayExpression,
|
1975 | returnsPrimitive: null
|
1976 | }
|
1977 | };
|
1978 | const callsArgReturnsArray = {
|
1979 | value: {
|
1980 | callsArgs: [0],
|
1981 | mutatesSelf: false,
|
1982 | returns: UnknownArrayExpression,
|
1983 | returnsPrimitive: null
|
1984 | }
|
1985 | };
|
1986 | const callsArgMutatesSelfReturnsArray = {
|
1987 | value: {
|
1988 | callsArgs: [0],
|
1989 | mutatesSelf: true,
|
1990 | returns: UnknownArrayExpression,
|
1991 | returnsPrimitive: null
|
1992 | }
|
1993 | };
|
1994 | const UNKNOWN_LITERAL_BOOLEAN = {
|
1995 | deoptimizePath: () => { },
|
1996 | getLiteralValueAtPath: () => UnknownValue,
|
1997 | getReturnExpressionWhenCalledAtPath: path => {
|
1998 | if (path.length === 1) {
|
1999 | return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
|
2000 | }
|
2001 | return UNKNOWN_EXPRESSION;
|
2002 | },
|
2003 | hasEffectsWhenAccessedAtPath: path => path.length > 1,
|
2004 | hasEffectsWhenAssignedAtPath: path => path.length > 0,
|
2005 | hasEffectsWhenCalledAtPath: path => {
|
2006 | if (path.length === 1) {
|
2007 | const subPath = path[0];
|
2008 | return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
|
2009 | }
|
2010 | return true;
|
2011 | },
|
2012 | include: () => { },
|
2013 | includeCallArguments(context, args) {
|
2014 | for (const arg of args) {
|
2015 | arg.include(context, false);
|
2016 | }
|
2017 | },
|
2018 | included: true,
|
2019 | toString: () => '[[UNKNOWN BOOLEAN]]'
|
2020 | };
|
2021 | const returnsBoolean = {
|
2022 | value: {
|
2023 | callsArgs: null,
|
2024 | mutatesSelf: false,
|
2025 | returns: null,
|
2026 | returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
|
2027 | }
|
2028 | };
|
2029 | const callsArgReturnsBoolean = {
|
2030 | value: {
|
2031 | callsArgs: [0],
|
2032 | mutatesSelf: false,
|
2033 | returns: null,
|
2034 | returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
|
2035 | }
|
2036 | };
|
2037 | const UNKNOWN_LITERAL_NUMBER = {
|
2038 | deoptimizePath: () => { },
|
2039 | getLiteralValueAtPath: () => UnknownValue,
|
2040 | getReturnExpressionWhenCalledAtPath: path => {
|
2041 | if (path.length === 1) {
|
2042 | return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
|
2043 | }
|
2044 | return UNKNOWN_EXPRESSION;
|
2045 | },
|
2046 | hasEffectsWhenAccessedAtPath: path => path.length > 1,
|
2047 | hasEffectsWhenAssignedAtPath: path => path.length > 0,
|
2048 | hasEffectsWhenCalledAtPath: path => {
|
2049 | if (path.length === 1) {
|
2050 | const subPath = path[0];
|
2051 | return typeof subPath !== 'string' || !literalNumberMembers[subPath];
|
2052 | }
|
2053 | return true;
|
2054 | },
|
2055 | include: () => { },
|
2056 | includeCallArguments(context, args) {
|
2057 | for (const arg of args) {
|
2058 | arg.include(context, false);
|
2059 | }
|
2060 | },
|
2061 | included: true,
|
2062 | toString: () => '[[UNKNOWN NUMBER]]'
|
2063 | };
|
2064 | const returnsNumber = {
|
2065 | value: {
|
2066 | callsArgs: null,
|
2067 | mutatesSelf: false,
|
2068 | returns: null,
|
2069 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2070 | }
|
2071 | };
|
2072 | const mutatesSelfReturnsNumber = {
|
2073 | value: {
|
2074 | callsArgs: null,
|
2075 | mutatesSelf: true,
|
2076 | returns: null,
|
2077 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2078 | }
|
2079 | };
|
2080 | const callsArgReturnsNumber = {
|
2081 | value: {
|
2082 | callsArgs: [0],
|
2083 | mutatesSelf: false,
|
2084 | returns: null,
|
2085 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2086 | }
|
2087 | };
|
2088 | const UNKNOWN_LITERAL_STRING = {
|
2089 | deoptimizePath: () => { },
|
2090 | getLiteralValueAtPath: () => UnknownValue,
|
2091 | getReturnExpressionWhenCalledAtPath: path => {
|
2092 | if (path.length === 1) {
|
2093 | return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
|
2094 | }
|
2095 | return UNKNOWN_EXPRESSION;
|
2096 | },
|
2097 | hasEffectsWhenAccessedAtPath: path => path.length > 1,
|
2098 | hasEffectsWhenAssignedAtPath: path => path.length > 0,
|
2099 | hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
|
2100 | if (path.length === 1) {
|
2101 | return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
|
2102 | }
|
2103 | return true;
|
2104 | },
|
2105 | include: () => { },
|
2106 | includeCallArguments(context, args) {
|
2107 | for (const arg of args) {
|
2108 | arg.include(context, false);
|
2109 | }
|
2110 | },
|
2111 | included: true,
|
2112 | toString: () => '[[UNKNOWN STRING]]'
|
2113 | };
|
2114 | const returnsString = {
|
2115 | value: {
|
2116 | callsArgs: null,
|
2117 | mutatesSelf: false,
|
2118 | returns: null,
|
2119 | returnsPrimitive: UNKNOWN_LITERAL_STRING
|
2120 | }
|
2121 | };
|
2122 | class UnknownObjectExpression {
|
2123 | constructor() {
|
2124 | this.included = false;
|
2125 | }
|
2126 | deoptimizePath() { }
|
2127 | getLiteralValueAtPath() {
|
2128 | return UnknownValue;
|
2129 | }
|
2130 | getReturnExpressionWhenCalledAtPath(path) {
|
2131 | if (path.length === 1) {
|
2132 | return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
|
2133 | }
|
2134 | return UNKNOWN_EXPRESSION;
|
2135 | }
|
2136 | hasEffectsWhenAccessedAtPath(path) {
|
2137 | return path.length > 1;
|
2138 | }
|
2139 | hasEffectsWhenAssignedAtPath(path) {
|
2140 | return path.length > 1;
|
2141 | }
|
2142 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
2143 | if (path.length === 1) {
|
2144 | return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
|
2145 | }
|
2146 | return true;
|
2147 | }
|
2148 | include() {
|
2149 | this.included = true;
|
2150 | }
|
2151 | includeCallArguments(context, args) {
|
2152 | for (const arg of args) {
|
2153 | arg.include(context, false);
|
2154 | }
|
2155 | }
|
2156 | toString() {
|
2157 | return '[[UNKNOWN OBJECT]]';
|
2158 | }
|
2159 | }
|
2160 | const objectMembers = assembleMemberDescriptions({
|
2161 | hasOwnProperty: returnsBoolean,
|
2162 | isPrototypeOf: returnsBoolean,
|
2163 | propertyIsEnumerable: returnsBoolean,
|
2164 | toLocaleString: returnsString,
|
2165 | toString: returnsString,
|
2166 | valueOf: returnsUnknown
|
2167 | });
|
2168 | const arrayMembers = assembleMemberDescriptions({
|
2169 | concat: returnsArray,
|
2170 | copyWithin: mutatesSelfReturnsArray,
|
2171 | every: callsArgReturnsBoolean,
|
2172 | fill: mutatesSelfReturnsArray,
|
2173 | filter: callsArgReturnsArray,
|
2174 | find: callsArgReturnsUnknown,
|
2175 | findIndex: callsArgReturnsNumber,
|
2176 | forEach: callsArgReturnsUnknown,
|
2177 | includes: returnsBoolean,
|
2178 | indexOf: returnsNumber,
|
2179 | join: returnsString,
|
2180 | lastIndexOf: returnsNumber,
|
2181 | map: callsArgReturnsArray,
|
2182 | pop: mutatesSelfReturnsUnknown,
|
2183 | push: mutatesSelfReturnsNumber,
|
2184 | reduce: callsArgReturnsUnknown,
|
2185 | reduceRight: callsArgReturnsUnknown,
|
2186 | reverse: mutatesSelfReturnsArray,
|
2187 | shift: mutatesSelfReturnsUnknown,
|
2188 | slice: returnsArray,
|
2189 | some: callsArgReturnsBoolean,
|
2190 | sort: callsArgMutatesSelfReturnsArray,
|
2191 | splice: mutatesSelfReturnsArray,
|
2192 | unshift: mutatesSelfReturnsNumber
|
2193 | }, objectMembers);
|
2194 | const literalBooleanMembers = assembleMemberDescriptions({
|
2195 | valueOf: returnsBoolean
|
2196 | }, objectMembers);
|
2197 | const literalNumberMembers = assembleMemberDescriptions({
|
2198 | toExponential: returnsString,
|
2199 | toFixed: returnsString,
|
2200 | toLocaleString: returnsString,
|
2201 | toPrecision: returnsString,
|
2202 | valueOf: returnsNumber
|
2203 | }, objectMembers);
|
2204 | const literalStringMembers = assembleMemberDescriptions({
|
2205 | charAt: returnsString,
|
2206 | charCodeAt: returnsNumber,
|
2207 | codePointAt: returnsNumber,
|
2208 | concat: returnsString,
|
2209 | endsWith: returnsBoolean,
|
2210 | includes: returnsBoolean,
|
2211 | indexOf: returnsNumber,
|
2212 | lastIndexOf: returnsNumber,
|
2213 | localeCompare: returnsNumber,
|
2214 | match: returnsBoolean,
|
2215 | normalize: returnsString,
|
2216 | padEnd: returnsString,
|
2217 | padStart: returnsString,
|
2218 | repeat: returnsString,
|
2219 | replace: {
|
2220 | value: {
|
2221 | callsArgs: [1],
|
2222 | mutatesSelf: false,
|
2223 | returns: null,
|
2224 | returnsPrimitive: UNKNOWN_LITERAL_STRING
|
2225 | }
|
2226 | },
|
2227 | search: returnsNumber,
|
2228 | slice: returnsString,
|
2229 | split: returnsArray,
|
2230 | startsWith: returnsBoolean,
|
2231 | substr: returnsString,
|
2232 | substring: returnsString,
|
2233 | toLocaleLowerCase: returnsString,
|
2234 | toLocaleUpperCase: returnsString,
|
2235 | toLowerCase: returnsString,
|
2236 | toUpperCase: returnsString,
|
2237 | trim: returnsString,
|
2238 | valueOf: returnsString
|
2239 | }, objectMembers);
|
2240 | function getLiteralMembersForValue(value) {
|
2241 | switch (typeof value) {
|
2242 | case 'boolean':
|
2243 | return literalBooleanMembers;
|
2244 | case 'number':
|
2245 | return literalNumberMembers;
|
2246 | case 'string':
|
2247 | return literalStringMembers;
|
2248 | default:
|
2249 | return Object.create(null);
|
2250 | }
|
2251 | }
|
2252 | function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
|
2253 | if (typeof memberName !== 'string' ||
|
2254 | !members[memberName] ||
|
2255 | (members[memberName].mutatesSelf && parentIncluded))
|
2256 | return true;
|
2257 | if (!members[memberName].callsArgs)
|
2258 | return false;
|
2259 | for (const argIndex of members[memberName].callsArgs) {
|
2260 | if (callOptions.args[argIndex] &&
|
2261 | callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
|
2262 | args: NO_ARGS,
|
2263 | withNew: false
|
2264 | }, context))
|
2265 | return true;
|
2266 | }
|
2267 | return false;
|
2268 | }
|
2269 | function getMemberReturnExpressionWhenCalled(members, memberName) {
|
2270 | if (typeof memberName !== 'string' || !members[memberName])
|
2271 | return UNKNOWN_EXPRESSION;
|
2272 | return members[memberName].returnsPrimitive !== null
|
2273 | ? members[memberName].returnsPrimitive
|
2274 | : new members[memberName].returns();
|
2275 | }
|
2276 |
|
2277 | class Variable {
|
2278 | constructor(name) {
|
2279 | this.alwaysRendered = false;
|
2280 | this.included = false;
|
2281 | this.isId = false;
|
2282 | this.isReassigned = false;
|
2283 | this.renderBaseName = null;
|
2284 | this.renderName = null;
|
2285 | this.name = name;
|
2286 | }
|
2287 | |
2288 |
|
2289 |
|
2290 |
|
2291 | addReference(_identifier) { }
|
2292 | deoptimizePath(_path) { }
|
2293 | getBaseVariableName() {
|
2294 | return this.renderBaseName || this.renderName || this.name;
|
2295 | }
|
2296 | getLiteralValueAtPath(_path, _recursionTracker, _origin) {
|
2297 | return UnknownValue;
|
2298 | }
|
2299 | getName() {
|
2300 | const name = this.renderName || this.name;
|
2301 | return this.renderBaseName
|
2302 | ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
|
2303 | : name;
|
2304 | }
|
2305 | getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
|
2306 | return UNKNOWN_EXPRESSION;
|
2307 | }
|
2308 | hasEffectsWhenAccessedAtPath(path, _context) {
|
2309 | return path.length > 0;
|
2310 | }
|
2311 | hasEffectsWhenAssignedAtPath(_path, _context) {
|
2312 | return true;
|
2313 | }
|
2314 | hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
|
2315 | return true;
|
2316 | }
|
2317 | |
2318 |
|
2319 |
|
2320 |
|
2321 |
|
2322 |
|
2323 | include() {
|
2324 | this.included = true;
|
2325 | }
|
2326 | includeCallArguments(context, args) {
|
2327 | for (const arg of args) {
|
2328 | arg.include(context, false);
|
2329 | }
|
2330 | }
|
2331 | markCalledFromTryStatement() { }
|
2332 | setRenderNames(baseName, name) {
|
2333 | this.renderBaseName = baseName;
|
2334 | this.renderName = name;
|
2335 | }
|
2336 | }
|
2337 |
|
2338 | class ExternalVariable extends Variable {
|
2339 | constructor(module, name) {
|
2340 | super(name);
|
2341 | this.module = module;
|
2342 | this.isNamespace = name === '*';
|
2343 | this.referenced = false;
|
2344 | }
|
2345 | addReference(identifier) {
|
2346 | this.referenced = true;
|
2347 | if (this.name === 'default' || this.name === '*') {
|
2348 | this.module.suggestName(identifier.name);
|
2349 | }
|
2350 | }
|
2351 | include() {
|
2352 | if (!this.included) {
|
2353 | this.included = true;
|
2354 | this.module.used = true;
|
2355 | }
|
2356 | }
|
2357 | }
|
2358 |
|
2359 | const BLANK = Object.freeze(Object.create(null));
|
2360 | const EMPTY_OBJECT = Object.freeze({});
|
2361 | const EMPTY_ARRAY = Object.freeze([]);
|
2362 |
|
2363 | const reservedWords = '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'.split(' ');
|
2364 | const builtins = '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'.split(' ');
|
2365 | const blacklisted = new Set(reservedWords.concat(builtins));
|
2366 | const illegalCharacters = /[^$_a-zA-Z0-9]/g;
|
2367 | const startsWithDigit = (str) => /\d/.test(str[0]);
|
2368 | function isLegal(str) {
|
2369 | if (startsWithDigit(str) || blacklisted.has(str)) {
|
2370 | return false;
|
2371 | }
|
2372 | return !illegalCharacters.test(str);
|
2373 | }
|
2374 | function makeLegal(str) {
|
2375 | str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
|
2376 | if (startsWithDigit(str) || blacklisted.has(str))
|
2377 | str = `_${str}`;
|
2378 | return str || '_';
|
2379 | }
|
2380 |
|
2381 | class ExternalModule {
|
2382 | constructor(options, id, hasModuleSideEffects, meta) {
|
2383 | this.options = options;
|
2384 | this.id = id;
|
2385 | this.defaultVariableName = '';
|
2386 | this.dynamicImporters = [];
|
2387 | this.importers = [];
|
2388 | this.mostCommonSuggestion = 0;
|
2389 | this.namespaceVariableName = '';
|
2390 | this.reexported = false;
|
2391 | this.renderPath = undefined;
|
2392 | this.renormalizeRenderPath = false;
|
2393 | this.used = false;
|
2394 | this.variableName = '';
|
2395 | this.execIndex = Infinity;
|
2396 | this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
|
2397 | this.nameSuggestions = Object.create(null);
|
2398 | this.declarations = Object.create(null);
|
2399 | this.exportedVariables = new Map();
|
2400 | const module = this;
|
2401 | this.info = {
|
2402 | ast: null,
|
2403 | code: null,
|
2404 | dynamicallyImportedIds: EMPTY_ARRAY,
|
2405 | get dynamicImporters() {
|
2406 | return module.dynamicImporters.sort();
|
2407 | },
|
2408 | hasModuleSideEffects,
|
2409 | id,
|
2410 | implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
|
2411 | implicitlyLoadedBefore: EMPTY_ARRAY,
|
2412 | importedIds: EMPTY_ARRAY,
|
2413 | get importers() {
|
2414 | return module.importers.sort();
|
2415 | },
|
2416 | isEntry: false,
|
2417 | isExternal: true,
|
2418 | meta,
|
2419 | syntheticNamedExports: false
|
2420 | };
|
2421 | }
|
2422 | getVariableForExportName(name) {
|
2423 | let declaration = this.declarations[name];
|
2424 | if (declaration)
|
2425 | return declaration;
|
2426 | this.declarations[name] = declaration = new ExternalVariable(this, name);
|
2427 | this.exportedVariables.set(declaration, name);
|
2428 | return declaration;
|
2429 | }
|
2430 | setRenderPath(options, inputBase) {
|
2431 | this.renderPath =
|
2432 | typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
|
2433 | if (!this.renderPath) {
|
2434 | if (!isAbsolute(this.id)) {
|
2435 | this.renderPath = this.id;
|
2436 | }
|
2437 | else {
|
2438 | this.renderPath = normalize(sysPath.relative(inputBase, this.id));
|
2439 | this.renormalizeRenderPath = true;
|
2440 | }
|
2441 | }
|
2442 | return this.renderPath;
|
2443 | }
|
2444 | suggestName(name) {
|
2445 | if (!this.nameSuggestions[name])
|
2446 | this.nameSuggestions[name] = 0;
|
2447 | this.nameSuggestions[name] += 1;
|
2448 | if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
|
2449 | this.mostCommonSuggestion = this.nameSuggestions[name];
|
2450 | this.suggestedVariableName = name;
|
2451 | }
|
2452 | }
|
2453 | warnUnusedImports() {
|
2454 | const unused = Object.keys(this.declarations).filter(name => {
|
2455 | if (name === '*')
|
2456 | return false;
|
2457 | const declaration = this.declarations[name];
|
2458 | return !declaration.included && !this.reexported && !declaration.referenced;
|
2459 | });
|
2460 | if (unused.length === 0)
|
2461 | return;
|
2462 | const names = unused.length === 1
|
2463 | ? `'${unused[0]}' is`
|
2464 | : `${unused
|
2465 | .slice(0, -1)
|
2466 | .map(name => `'${name}'`)
|
2467 | .join(', ')} and '${unused.slice(-1)}' are`;
|
2468 | this.options.onwarn({
|
2469 | code: 'UNUSED_EXTERNAL_IMPORT',
|
2470 | message: `${names} imported from external module '${this.id}' but never used`,
|
2471 | names: unused,
|
2472 | source: this.id
|
2473 | });
|
2474 | }
|
2475 | }
|
2476 |
|
2477 | function markModuleAndImpureDependenciesAsExecuted(baseModule) {
|
2478 | baseModule.isExecuted = true;
|
2479 | const modules = [baseModule];
|
2480 | const visitedModules = new Set();
|
2481 | for (const module of modules) {
|
2482 | for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
|
2483 | if (!(dependency instanceof ExternalModule) &&
|
2484 | !dependency.isExecuted &&
|
2485 | (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
|
2486 | !visitedModules.has(dependency.id)) {
|
2487 | dependency.isExecuted = true;
|
2488 | visitedModules.add(dependency.id);
|
2489 | modules.push(dependency);
|
2490 | }
|
2491 | }
|
2492 | }
|
2493 | }
|
2494 |
|
2495 | const BROKEN_FLOW_NONE = 0;
|
2496 | const BROKEN_FLOW_BREAK_CONTINUE = 1;
|
2497 | const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
|
2498 | function createInclusionContext() {
|
2499 | return {
|
2500 | brokenFlow: BROKEN_FLOW_NONE,
|
2501 | includedCallArguments: new Set(),
|
2502 | includedLabels: new Set()
|
2503 | };
|
2504 | }
|
2505 | function createHasEffectsContext() {
|
2506 | return {
|
2507 | accessed: new PathTracker(),
|
2508 | assigned: new PathTracker(),
|
2509 | brokenFlow: BROKEN_FLOW_NONE,
|
2510 | called: new DiscriminatedPathTracker(),
|
2511 | ignore: {
|
2512 | breaks: false,
|
2513 | continues: false,
|
2514 | labels: new Set(),
|
2515 | returnAwaitYield: false
|
2516 | },
|
2517 | includedLabels: new Set(),
|
2518 | instantiated: new DiscriminatedPathTracker(),
|
2519 | replacedVariableInits: new Map()
|
2520 | };
|
2521 | }
|
2522 |
|
2523 |
|
2524 | const MAX_PATH_DEPTH = 7;
|
2525 | class LocalVariable extends Variable {
|
2526 | constructor(name, declarator, init, context) {
|
2527 | super(name);
|
2528 | this.additionalInitializers = null;
|
2529 | this.calledFromTryStatement = false;
|
2530 | this.expressionsToBeDeoptimized = [];
|
2531 | this.declarations = declarator ? [declarator] : [];
|
2532 | this.init = init;
|
2533 | this.deoptimizationTracker = context.deoptimizationTracker;
|
2534 | this.module = context.module;
|
2535 | }
|
2536 | addDeclaration(identifier, init) {
|
2537 | this.declarations.push(identifier);
|
2538 | if (this.additionalInitializers === null) {
|
2539 | this.additionalInitializers = this.init === null ? [] : [this.init];
|
2540 | this.init = UNKNOWN_EXPRESSION;
|
2541 | this.isReassigned = true;
|
2542 | }
|
2543 | if (init !== null) {
|
2544 | this.additionalInitializers.push(init);
|
2545 | }
|
2546 | }
|
2547 | consolidateInitializers() {
|
2548 | if (this.additionalInitializers !== null) {
|
2549 | for (const initializer of this.additionalInitializers) {
|
2550 | initializer.deoptimizePath(UNKNOWN_PATH);
|
2551 | }
|
2552 | this.additionalInitializers = null;
|
2553 | }
|
2554 | }
|
2555 | deoptimizePath(path) {
|
2556 | if (path.length > MAX_PATH_DEPTH || this.isReassigned)
|
2557 | return;
|
2558 | const trackedEntities = this.deoptimizationTracker.getEntities(path);
|
2559 | if (trackedEntities.has(this))
|
2560 | return;
|
2561 | trackedEntities.add(this);
|
2562 | if (path.length === 0) {
|
2563 | if (!this.isReassigned) {
|
2564 | this.isReassigned = true;
|
2565 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
|
2566 | this.expressionsToBeDeoptimized = [];
|
2567 | for (const expression of expressionsToBeDeoptimized) {
|
2568 | expression.deoptimizeCache();
|
2569 | }
|
2570 | if (this.init) {
|
2571 | this.init.deoptimizePath(UNKNOWN_PATH);
|
2572 | }
|
2573 | }
|
2574 | }
|
2575 | else if (this.init) {
|
2576 | this.init.deoptimizePath(path);
|
2577 | }
|
2578 | }
|
2579 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
2580 | if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
|
2581 | return UnknownValue;
|
2582 | }
|
2583 | const trackedEntities = recursionTracker.getEntities(path);
|
2584 | if (trackedEntities.has(this.init)) {
|
2585 | return UnknownValue;
|
2586 | }
|
2587 | this.expressionsToBeDeoptimized.push(origin);
|
2588 | trackedEntities.add(this.init);
|
2589 | const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
|
2590 | trackedEntities.delete(this.init);
|
2591 | return value;
|
2592 | }
|
2593 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
2594 | if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
|
2595 | return UNKNOWN_EXPRESSION;
|
2596 | }
|
2597 | const trackedEntities = recursionTracker.getEntities(path);
|
2598 | if (trackedEntities.has(this.init)) {
|
2599 | return UNKNOWN_EXPRESSION;
|
2600 | }
|
2601 | this.expressionsToBeDeoptimized.push(origin);
|
2602 | trackedEntities.add(this.init);
|
2603 | const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
2604 | trackedEntities.delete(this.init);
|
2605 | return value;
|
2606 | }
|
2607 | hasEffectsWhenAccessedAtPath(path, context) {
|
2608 | if (path.length === 0)
|
2609 | return false;
|
2610 | if (this.isReassigned || path.length > MAX_PATH_DEPTH)
|
2611 | return true;
|
2612 | const trackedExpressions = context.accessed.getEntities(path);
|
2613 | if (trackedExpressions.has(this))
|
2614 | return false;
|
2615 | trackedExpressions.add(this);
|
2616 | return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
|
2617 | }
|
2618 | hasEffectsWhenAssignedAtPath(path, context) {
|
2619 | if (this.included || path.length > MAX_PATH_DEPTH)
|
2620 | return true;
|
2621 | if (path.length === 0)
|
2622 | return false;
|
2623 | if (this.isReassigned)
|
2624 | return true;
|
2625 | const trackedExpressions = context.assigned.getEntities(path);
|
2626 | if (trackedExpressions.has(this))
|
2627 | return false;
|
2628 | trackedExpressions.add(this);
|
2629 | return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
|
2630 | }
|
2631 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
2632 | if (path.length > MAX_PATH_DEPTH || this.isReassigned)
|
2633 | return true;
|
2634 | const trackedExpressions = (callOptions.withNew
|
2635 | ? context.instantiated
|
2636 | : context.called).getEntities(path, callOptions);
|
2637 | if (trackedExpressions.has(this))
|
2638 | return false;
|
2639 | trackedExpressions.add(this);
|
2640 | return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
|
2641 | }
|
2642 | include() {
|
2643 | if (!this.included) {
|
2644 | this.included = true;
|
2645 | if (!this.module.isExecuted) {
|
2646 | markModuleAndImpureDependenciesAsExecuted(this.module);
|
2647 | }
|
2648 | for (const declaration of this.declarations) {
|
2649 |
|
2650 | if (!declaration.included)
|
2651 | declaration.include(createInclusionContext(), false);
|
2652 | let node = declaration.parent;
|
2653 | while (!node.included) {
|
2654 |
|
2655 |
|
2656 | node.included = true;
|
2657 | if (node.type === Program)
|
2658 | break;
|
2659 | node = node.parent;
|
2660 | }
|
2661 | }
|
2662 | }
|
2663 | }
|
2664 | includeCallArguments(context, args) {
|
2665 | if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
|
2666 | for (const arg of args) {
|
2667 | arg.include(context, false);
|
2668 | }
|
2669 | }
|
2670 | else if (this.init) {
|
2671 | context.includedCallArguments.add(this.init);
|
2672 | this.init.includeCallArguments(context, args);
|
2673 | context.includedCallArguments.delete(this.init);
|
2674 | }
|
2675 | }
|
2676 | markCalledFromTryStatement() {
|
2677 | this.calledFromTryStatement = true;
|
2678 | }
|
2679 | }
|
2680 |
|
2681 | class Scope {
|
2682 | constructor() {
|
2683 | this.children = [];
|
2684 | this.variables = new Map();
|
2685 | }
|
2686 | addDeclaration(identifier, context, init, _isHoisted) {
|
2687 | const name = identifier.name;
|
2688 | let variable = this.variables.get(name);
|
2689 | if (variable) {
|
2690 | variable.addDeclaration(identifier, init);
|
2691 | }
|
2692 | else {
|
2693 | variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
|
2694 | this.variables.set(name, variable);
|
2695 | }
|
2696 | return variable;
|
2697 | }
|
2698 | contains(name) {
|
2699 | return this.variables.has(name);
|
2700 | }
|
2701 | findVariable(_name) {
|
2702 | throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
|
2703 | }
|
2704 | }
|
2705 |
|
2706 | class ChildScope extends Scope {
|
2707 | constructor(parent) {
|
2708 | super();
|
2709 | this.accessedOutsideVariables = new Map();
|
2710 | this.parent = parent;
|
2711 | parent.children.push(this);
|
2712 | }
|
2713 | addAccessedDynamicImport(importExpression) {
|
2714 | (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
|
2715 | if (this.parent instanceof ChildScope) {
|
2716 | this.parent.addAccessedDynamicImport(importExpression);
|
2717 | }
|
2718 | }
|
2719 | addAccessedGlobals(globals, accessedGlobalsByScope) {
|
2720 | const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
|
2721 | for (const name of globals) {
|
2722 | accessedGlobals.add(name);
|
2723 | }
|
2724 | accessedGlobalsByScope.set(this, accessedGlobals);
|
2725 | if (this.parent instanceof ChildScope) {
|
2726 | this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
|
2727 | }
|
2728 | }
|
2729 | addNamespaceMemberAccess(name, variable) {
|
2730 | this.accessedOutsideVariables.set(name, variable);
|
2731 | this.parent.addNamespaceMemberAccess(name, variable);
|
2732 | }
|
2733 | addReturnExpression(expression) {
|
2734 | this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
|
2735 | }
|
2736 | addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
|
2737 | for (const variable of this.accessedOutsideVariables.values()) {
|
2738 | if (variable.included) {
|
2739 | usedNames.add(variable.getBaseVariableName());
|
2740 | if (format === 'system' && exportNamesByVariable.has(variable)) {
|
2741 | usedNames.add('exports');
|
2742 | }
|
2743 | }
|
2744 | }
|
2745 | const accessedGlobals = accessedGlobalsByScope.get(this);
|
2746 | if (accessedGlobals) {
|
2747 | for (const name of accessedGlobals) {
|
2748 | usedNames.add(name);
|
2749 | }
|
2750 | }
|
2751 | }
|
2752 | contains(name) {
|
2753 | return this.variables.has(name) || this.parent.contains(name);
|
2754 | }
|
2755 | deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
|
2756 | const usedNames = new Set();
|
2757 | this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
|
2758 | if (this.accessedDynamicImports) {
|
2759 | for (const importExpression of this.accessedDynamicImports) {
|
2760 | if (importExpression.inlineNamespace) {
|
2761 | usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
|
2762 | }
|
2763 | }
|
2764 | }
|
2765 | for (const [name, variable] of this.variables) {
|
2766 | if (variable.included || variable.alwaysRendered) {
|
2767 | variable.setRenderNames(null, getSafeName(name, usedNames));
|
2768 | }
|
2769 | }
|
2770 | for (const scope of this.children) {
|
2771 | scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
|
2772 | }
|
2773 | }
|
2774 | findLexicalBoundary() {
|
2775 | return this.parent.findLexicalBoundary();
|
2776 | }
|
2777 | findVariable(name) {
|
2778 | const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
|
2779 | if (knownVariable) {
|
2780 | return knownVariable;
|
2781 | }
|
2782 | const variable = this.parent.findVariable(name);
|
2783 | this.accessedOutsideVariables.set(name, variable);
|
2784 | return variable;
|
2785 | }
|
2786 | }
|
2787 |
|
2788 | function getLocator$1(source, options) {
|
2789 | if (options === void 0) { options = {}; }
|
2790 | var offsetLine = options.offsetLine || 0;
|
2791 | var offsetColumn = options.offsetColumn || 0;
|
2792 | var originalLines = source.split('\n');
|
2793 | var start = 0;
|
2794 | var lineRanges = originalLines.map(function (line, i) {
|
2795 | var end = start + line.length + 1;
|
2796 | var range = { start: start, end: end, line: i };
|
2797 | start = end;
|
2798 | return range;
|
2799 | });
|
2800 | var i = 0;
|
2801 | function rangeContains(range, index) {
|
2802 | return range.start <= index && index < range.end;
|
2803 | }
|
2804 | function getLocation(range, index) {
|
2805 | return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
|
2806 | }
|
2807 | function locate(search, startIndex) {
|
2808 | if (typeof search === 'string') {
|
2809 | search = source.indexOf(search, startIndex || 0);
|
2810 | }
|
2811 | var range = lineRanges[i];
|
2812 | var d = search >= range.end ? 1 : -1;
|
2813 | while (range) {
|
2814 | if (rangeContains(range, search))
|
2815 | return getLocation(range, search);
|
2816 | i += d;
|
2817 | range = lineRanges[i];
|
2818 | }
|
2819 | }
|
2820 | return locate;
|
2821 | }
|
2822 | function locate(source, search, options) {
|
2823 | if (typeof options === 'number') {
|
2824 | throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
|
2825 | }
|
2826 | return getLocator$1(source, options)(search, options && options.startIndex);
|
2827 | }
|
2828 |
|
2829 | const keys = {
|
2830 | Literal: [],
|
2831 | Program: ['body']
|
2832 | };
|
2833 | function getAndCreateKeys(esTreeNode) {
|
2834 | keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
|
2835 | return keys[esTreeNode.type];
|
2836 | }
|
2837 |
|
2838 | const INCLUDE_PARAMETERS = 'variables';
|
2839 | class NodeBase {
|
2840 | constructor(esTreeNode, parent, parentScope) {
|
2841 | this.included = false;
|
2842 | this.esTreeNode = esTreeNode;
|
2843 | this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
|
2844 | this.parent = parent;
|
2845 | this.context = parent.context;
|
2846 | this.createScope(parentScope);
|
2847 | this.parseNode(esTreeNode);
|
2848 | this.initialise();
|
2849 | this.context.magicString.addSourcemapLocation(this.start);
|
2850 | this.context.magicString.addSourcemapLocation(this.end);
|
2851 | }
|
2852 | |
2853 |
|
2854 |
|
2855 |
|
2856 | bind() {
|
2857 | for (const key of this.keys) {
|
2858 | const value = this[key];
|
2859 | if (value === null || key === 'annotations')
|
2860 | continue;
|
2861 | if (Array.isArray(value)) {
|
2862 | for (const child of value) {
|
2863 | if (child !== null)
|
2864 | child.bind();
|
2865 | }
|
2866 | }
|
2867 | else {
|
2868 | value.bind();
|
2869 | }
|
2870 | }
|
2871 | }
|
2872 | |
2873 |
|
2874 |
|
2875 | createScope(parentScope) {
|
2876 | this.scope = parentScope;
|
2877 | }
|
2878 | declare(_kind, _init) {
|
2879 | return [];
|
2880 | }
|
2881 | deoptimizePath(_path) { }
|
2882 | getLiteralValueAtPath(_path, _recursionTracker, _origin) {
|
2883 | return UnknownValue;
|
2884 | }
|
2885 | getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
|
2886 | return UNKNOWN_EXPRESSION;
|
2887 | }
|
2888 | hasEffects(context) {
|
2889 | for (const key of this.keys) {
|
2890 | const value = this[key];
|
2891 | if (value === null || key === 'annotations')
|
2892 | continue;
|
2893 | if (Array.isArray(value)) {
|
2894 | for (const child of value) {
|
2895 | if (child !== null && child.hasEffects(context))
|
2896 | return true;
|
2897 | }
|
2898 | }
|
2899 | else if (value.hasEffects(context))
|
2900 | return true;
|
2901 | }
|
2902 | return false;
|
2903 | }
|
2904 | hasEffectsWhenAccessedAtPath(path, _context) {
|
2905 | return path.length > 0;
|
2906 | }
|
2907 | hasEffectsWhenAssignedAtPath(_path, _context) {
|
2908 | return true;
|
2909 | }
|
2910 | hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
|
2911 | return true;
|
2912 | }
|
2913 | include(context, includeChildrenRecursively) {
|
2914 | this.included = true;
|
2915 | for (const key of this.keys) {
|
2916 | const value = this[key];
|
2917 | if (value === null || key === 'annotations')
|
2918 | continue;
|
2919 | if (Array.isArray(value)) {
|
2920 | for (const child of value) {
|
2921 | if (child !== null)
|
2922 | child.include(context, includeChildrenRecursively);
|
2923 | }
|
2924 | }
|
2925 | else {
|
2926 | value.include(context, includeChildrenRecursively);
|
2927 | }
|
2928 | }
|
2929 | }
|
2930 | includeCallArguments(context, args) {
|
2931 | for (const arg of args) {
|
2932 | arg.include(context, false);
|
2933 | }
|
2934 | }
|
2935 | includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
|
2936 | this.include(context, includeChildrenRecursively);
|
2937 | }
|
2938 | |
2939 |
|
2940 |
|
2941 | initialise() { }
|
2942 | insertSemicolon(code) {
|
2943 | if (code.original[this.end - 1] !== ';') {
|
2944 | code.appendLeft(this.end, ';');
|
2945 | }
|
2946 | }
|
2947 | parseNode(esTreeNode) {
|
2948 | for (const key of Object.keys(esTreeNode)) {
|
2949 |
|
2950 | if (this.hasOwnProperty(key))
|
2951 | continue;
|
2952 | const value = esTreeNode[key];
|
2953 | if (typeof value !== 'object' || value === null || key === 'annotations') {
|
2954 | this[key] = value;
|
2955 | }
|
2956 | else if (Array.isArray(value)) {
|
2957 | this[key] = [];
|
2958 | for (const child of value) {
|
2959 | this[key].push(child === null
|
2960 | ? null
|
2961 | : new (this.context.nodeConstructors[child.type] ||
|
2962 | this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
|
2963 | }
|
2964 | }
|
2965 | else {
|
2966 | this[key] = new (this.context.nodeConstructors[value.type] ||
|
2967 | this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
|
2968 | }
|
2969 | }
|
2970 | }
|
2971 | render(code, options) {
|
2972 | for (const key of this.keys) {
|
2973 | const value = this[key];
|
2974 | if (value === null || key === 'annotations')
|
2975 | continue;
|
2976 | if (Array.isArray(value)) {
|
2977 | for (const child of value) {
|
2978 | if (child !== null)
|
2979 | child.render(code, options);
|
2980 | }
|
2981 | }
|
2982 | else {
|
2983 | value.render(code, options);
|
2984 | }
|
2985 | }
|
2986 | }
|
2987 | shouldBeIncluded(context) {
|
2988 | return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
|
2989 | }
|
2990 | toString() {
|
2991 | return this.context.code.slice(this.start, this.end);
|
2992 | }
|
2993 | }
|
2994 |
|
2995 | class ClassNode extends NodeBase {
|
2996 | createScope(parentScope) {
|
2997 | this.scope = new ChildScope(parentScope);
|
2998 | }
|
2999 | hasEffectsWhenAccessedAtPath(path) {
|
3000 | if (path.length <= 1)
|
3001 | return false;
|
3002 | return path.length > 2 || path[0] !== 'prototype';
|
3003 | }
|
3004 | hasEffectsWhenAssignedAtPath(path) {
|
3005 | if (path.length <= 1)
|
3006 | return false;
|
3007 | return path.length > 2 || path[0] !== 'prototype';
|
3008 | }
|
3009 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
3010 | if (!callOptions.withNew)
|
3011 | return true;
|
3012 | return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
|
3013 | (this.superClass !== null &&
|
3014 | this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
|
3015 | }
|
3016 | initialise() {
|
3017 | if (this.id !== null) {
|
3018 | this.id.declare('class', this);
|
3019 | }
|
3020 | }
|
3021 | }
|
3022 |
|
3023 | class ClassDeclaration extends ClassNode {
|
3024 | initialise() {
|
3025 | super.initialise();
|
3026 | if (this.id !== null) {
|
3027 | this.id.variable.isId = true;
|
3028 | }
|
3029 | }
|
3030 | parseNode(esTreeNode) {
|
3031 | if (esTreeNode.id !== null) {
|
3032 | this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
|
3033 | }
|
3034 | super.parseNode(esTreeNode);
|
3035 | }
|
3036 | render(code, options) {
|
3037 | if (options.format === 'system' &&
|
3038 | this.id &&
|
3039 | options.exportNamesByVariable.has(this.id.variable)) {
|
3040 | code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
|
3041 | }
|
3042 | super.render(code, options);
|
3043 | }
|
3044 | }
|
3045 |
|
3046 | class ArgumentsVariable extends LocalVariable {
|
3047 | constructor(context) {
|
3048 | super('arguments', null, UNKNOWN_EXPRESSION, context);
|
3049 | }
|
3050 | hasEffectsWhenAccessedAtPath(path) {
|
3051 | return path.length > 1;
|
3052 | }
|
3053 | hasEffectsWhenAssignedAtPath() {
|
3054 | return true;
|
3055 | }
|
3056 | hasEffectsWhenCalledAtPath() {
|
3057 | return true;
|
3058 | }
|
3059 | }
|
3060 |
|
3061 | class ThisVariable extends LocalVariable {
|
3062 | constructor(context) {
|
3063 | super('this', null, null, context);
|
3064 | }
|
3065 | getLiteralValueAtPath() {
|
3066 | return UnknownValue;
|
3067 | }
|
3068 | hasEffectsWhenAccessedAtPath(path, context) {
|
3069 | return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
|
3070 | super.hasEffectsWhenAccessedAtPath(path, context));
|
3071 | }
|
3072 | hasEffectsWhenAssignedAtPath(path, context) {
|
3073 | return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
|
3074 | super.hasEffectsWhenAssignedAtPath(path, context));
|
3075 | }
|
3076 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
3077 | return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
|
3078 | super.hasEffectsWhenCalledAtPath(path, callOptions, context));
|
3079 | }
|
3080 | getInit(context) {
|
3081 | return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
|
3082 | }
|
3083 | }
|
3084 |
|
3085 | class SpreadElement extends NodeBase {
|
3086 | bind() {
|
3087 | super.bind();
|
3088 |
|
3089 |
|
3090 | this.argument.deoptimizePath([UnknownKey, UnknownKey]);
|
3091 | }
|
3092 | }
|
3093 |
|
3094 | class ParameterScope extends ChildScope {
|
3095 | constructor(parent, context) {
|
3096 | super(parent);
|
3097 | this.parameters = [];
|
3098 | this.hasRest = false;
|
3099 | this.context = context;
|
3100 | this.hoistedBodyVarScope = new ChildScope(this);
|
3101 | }
|
3102 | |
3103 |
|
3104 |
|
3105 |
|
3106 | addParameterDeclaration(identifier) {
|
3107 | const name = identifier.name;
|
3108 | let variable = this.hoistedBodyVarScope.variables.get(name);
|
3109 | if (variable) {
|
3110 | variable.addDeclaration(identifier, null);
|
3111 | }
|
3112 | else {
|
3113 | variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
|
3114 | }
|
3115 | this.variables.set(name, variable);
|
3116 | return variable;
|
3117 | }
|
3118 | addParameterVariables(parameters, hasRest) {
|
3119 | this.parameters = parameters;
|
3120 | for (const parameterList of parameters) {
|
3121 | for (const parameter of parameterList) {
|
3122 | parameter.alwaysRendered = true;
|
3123 | }
|
3124 | }
|
3125 | this.hasRest = hasRest;
|
3126 | }
|
3127 | includeCallArguments(context, args) {
|
3128 | let calledFromTryStatement = false;
|
3129 | let argIncluded = false;
|
3130 | const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
|
3131 | for (const checkedArg of args) {
|
3132 | if (checkedArg instanceof SpreadElement) {
|
3133 | for (const arg of args) {
|
3134 | arg.include(context, false);
|
3135 | }
|
3136 | break;
|
3137 | }
|
3138 | }
|
3139 | for (let index = args.length - 1; index >= 0; index--) {
|
3140 | const paramVars = this.parameters[index] || restParam;
|
3141 | const arg = args[index];
|
3142 | if (paramVars) {
|
3143 | calledFromTryStatement = false;
|
3144 | for (const variable of paramVars) {
|
3145 | if (variable.included) {
|
3146 | argIncluded = true;
|
3147 | }
|
3148 | if (variable.calledFromTryStatement) {
|
3149 | calledFromTryStatement = true;
|
3150 | }
|
3151 | }
|
3152 | }
|
3153 | if (!argIncluded && arg.shouldBeIncluded(context)) {
|
3154 | argIncluded = true;
|
3155 | }
|
3156 | if (argIncluded) {
|
3157 | arg.include(context, calledFromTryStatement);
|
3158 | }
|
3159 | }
|
3160 | }
|
3161 | }
|
3162 |
|
3163 | class ReturnValueScope extends ParameterScope {
|
3164 | constructor() {
|
3165 | super(...arguments);
|
3166 | this.returnExpression = null;
|
3167 | this.returnExpressions = [];
|
3168 | }
|
3169 | addReturnExpression(expression) {
|
3170 | this.returnExpressions.push(expression);
|
3171 | }
|
3172 | getReturnExpression() {
|
3173 | if (this.returnExpression === null)
|
3174 | this.updateReturnExpression();
|
3175 | return this.returnExpression;
|
3176 | }
|
3177 | updateReturnExpression() {
|
3178 | if (this.returnExpressions.length === 1) {
|
3179 | this.returnExpression = this.returnExpressions[0];
|
3180 | }
|
3181 | else {
|
3182 | this.returnExpression = UNKNOWN_EXPRESSION;
|
3183 | for (const expression of this.returnExpressions) {
|
3184 | expression.deoptimizePath(UNKNOWN_PATH);
|
3185 | }
|
3186 | }
|
3187 | }
|
3188 | }
|
3189 |
|
3190 | class FunctionScope extends ReturnValueScope {
|
3191 | constructor(parent, context) {
|
3192 | super(parent, context);
|
3193 | this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
|
3194 | this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
|
3195 | }
|
3196 | findLexicalBoundary() {
|
3197 | return this;
|
3198 | }
|
3199 | includeCallArguments(context, args) {
|
3200 | super.includeCallArguments(context, args);
|
3201 | if (this.argumentsVariable.included) {
|
3202 | for (const arg of args) {
|
3203 | if (!arg.included) {
|
3204 | arg.include(context, false);
|
3205 | }
|
3206 | }
|
3207 | }
|
3208 | }
|
3209 | }
|
3210 |
|
3211 | function isReference(node, parent) {
|
3212 | if (node.type === 'MemberExpression') {
|
3213 | return !node.computed && isReference(node.object, node);
|
3214 | }
|
3215 | if (node.type === 'Identifier') {
|
3216 | if (!parent)
|
3217 | return true;
|
3218 | switch (parent.type) {
|
3219 |
|
3220 | case 'MemberExpression': return parent.computed || node === parent.object;
|
3221 |
|
3222 | case 'MethodDefinition': return parent.computed;
|
3223 |
|
3224 | case 'FieldDefinition': return parent.computed || node === parent.value;
|
3225 |
|
3226 | case 'Property': return parent.computed || node === parent.value;
|
3227 |
|
3228 |
|
3229 | case 'ExportSpecifier':
|
3230 | case 'ImportSpecifier': return node === parent.local;
|
3231 |
|
3232 | case 'LabeledStatement':
|
3233 | case 'BreakStatement':
|
3234 | case 'ContinueStatement': return false;
|
3235 | default: return true;
|
3236 | }
|
3237 | }
|
3238 | return false;
|
3239 | }
|
3240 |
|
3241 | const ValueProperties = Symbol('Value Properties');
|
3242 | const PURE = { pure: true };
|
3243 | const IMPURE = { pure: false };
|
3244 |
|
3245 |
|
3246 | const O = {
|
3247 |
|
3248 | __proto__: null,
|
3249 | [ValueProperties]: IMPURE
|
3250 | };
|
3251 |
|
3252 | const PF = {
|
3253 |
|
3254 | __proto__: null,
|
3255 | [ValueProperties]: PURE
|
3256 | };
|
3257 |
|
3258 | const C = {
|
3259 |
|
3260 | __proto__: null,
|
3261 | [ValueProperties]: IMPURE,
|
3262 | prototype: O
|
3263 | };
|
3264 |
|
3265 | const PC = {
|
3266 |
|
3267 | __proto__: null,
|
3268 | [ValueProperties]: PURE,
|
3269 | prototype: O
|
3270 | };
|
3271 | const ARRAY_TYPE = {
|
3272 |
|
3273 | __proto__: null,
|
3274 | [ValueProperties]: PURE,
|
3275 | from: PF,
|
3276 | of: PF,
|
3277 | prototype: O
|
3278 | };
|
3279 | const INTL_MEMBER = {
|
3280 |
|
3281 | __proto__: null,
|
3282 | [ValueProperties]: PURE,
|
3283 | supportedLocalesOf: PC
|
3284 | };
|
3285 | const knownGlobals = {
|
3286 |
|
3287 | global: O,
|
3288 | globalThis: O,
|
3289 | self: O,
|
3290 | window: O,
|
3291 |
|
3292 |
|
3293 | __proto__: null,
|
3294 | [ValueProperties]: IMPURE,
|
3295 | Array: {
|
3296 |
|
3297 | __proto__: null,
|
3298 | [ValueProperties]: IMPURE,
|
3299 | from: O,
|
3300 | isArray: PF,
|
3301 | of: PF,
|
3302 | prototype: O
|
3303 | },
|
3304 | ArrayBuffer: {
|
3305 |
|
3306 | __proto__: null,
|
3307 | [ValueProperties]: PURE,
|
3308 | isView: PF,
|
3309 | prototype: O
|
3310 | },
|
3311 | Atomics: O,
|
3312 | BigInt: C,
|
3313 | BigInt64Array: C,
|
3314 | BigUint64Array: C,
|
3315 | Boolean: PC,
|
3316 |
|
3317 | constructor: C,
|
3318 | DataView: PC,
|
3319 | Date: {
|
3320 |
|
3321 | __proto__: null,
|
3322 | [ValueProperties]: PURE,
|
3323 | now: PF,
|
3324 | parse: PF,
|
3325 | prototype: O,
|
3326 | UTC: PF
|
3327 | },
|
3328 | decodeURI: PF,
|
3329 | decodeURIComponent: PF,
|
3330 | encodeURI: PF,
|
3331 | encodeURIComponent: PF,
|
3332 | Error: PC,
|
3333 | escape: PF,
|
3334 | eval: O,
|
3335 | EvalError: PC,
|
3336 | Float32Array: ARRAY_TYPE,
|
3337 | Float64Array: ARRAY_TYPE,
|
3338 | Function: C,
|
3339 |
|
3340 | hasOwnProperty: O,
|
3341 | Infinity: O,
|
3342 | Int16Array: ARRAY_TYPE,
|
3343 | Int32Array: ARRAY_TYPE,
|
3344 | Int8Array: ARRAY_TYPE,
|
3345 | isFinite: PF,
|
3346 | isNaN: PF,
|
3347 |
|
3348 | isPrototypeOf: O,
|
3349 | JSON: O,
|
3350 | Map: PC,
|
3351 | Math: {
|
3352 |
|
3353 | __proto__: null,
|
3354 | [ValueProperties]: IMPURE,
|
3355 | abs: PF,
|
3356 | acos: PF,
|
3357 | acosh: PF,
|
3358 | asin: PF,
|
3359 | asinh: PF,
|
3360 | atan: PF,
|
3361 | atan2: PF,
|
3362 | atanh: PF,
|
3363 | cbrt: PF,
|
3364 | ceil: PF,
|
3365 | clz32: PF,
|
3366 | cos: PF,
|
3367 | cosh: PF,
|
3368 | exp: PF,
|
3369 | expm1: PF,
|
3370 | floor: PF,
|
3371 | fround: PF,
|
3372 | hypot: PF,
|
3373 | imul: PF,
|
3374 | log: PF,
|
3375 | log10: PF,
|
3376 | log1p: PF,
|
3377 | log2: PF,
|
3378 | max: PF,
|
3379 | min: PF,
|
3380 | pow: PF,
|
3381 | random: PF,
|
3382 | round: PF,
|
3383 | sign: PF,
|
3384 | sin: PF,
|
3385 | sinh: PF,
|
3386 | sqrt: PF,
|
3387 | tan: PF,
|
3388 | tanh: PF,
|
3389 | trunc: PF
|
3390 | },
|
3391 | NaN: O,
|
3392 | Number: {
|
3393 |
|
3394 | __proto__: null,
|
3395 | [ValueProperties]: PURE,
|
3396 | isFinite: PF,
|
3397 | isInteger: PF,
|
3398 | isNaN: PF,
|
3399 | isSafeInteger: PF,
|
3400 | parseFloat: PF,
|
3401 | parseInt: PF,
|
3402 | prototype: O
|
3403 | },
|
3404 | Object: {
|
3405 |
|
3406 | __proto__: null,
|
3407 | [ValueProperties]: PURE,
|
3408 | create: PF,
|
3409 | getNotifier: PF,
|
3410 | getOwn: PF,
|
3411 | getOwnPropertyDescriptor: PF,
|
3412 | getOwnPropertyNames: PF,
|
3413 | getOwnPropertySymbols: PF,
|
3414 | getPrototypeOf: PF,
|
3415 | is: PF,
|
3416 | isExtensible: PF,
|
3417 | isFrozen: PF,
|
3418 | isSealed: PF,
|
3419 | keys: PF,
|
3420 | prototype: O
|
3421 | },
|
3422 | parseFloat: PF,
|
3423 | parseInt: PF,
|
3424 | Promise: {
|
3425 |
|
3426 | __proto__: null,
|
3427 | [ValueProperties]: IMPURE,
|
3428 | all: PF,
|
3429 | prototype: O,
|
3430 | race: PF,
|
3431 | resolve: PF
|
3432 | },
|
3433 |
|
3434 | propertyIsEnumerable: O,
|
3435 | Proxy: O,
|
3436 | RangeError: PC,
|
3437 | ReferenceError: PC,
|
3438 | Reflect: O,
|
3439 | RegExp: PC,
|
3440 | Set: PC,
|
3441 | SharedArrayBuffer: C,
|
3442 | String: {
|
3443 |
|
3444 | __proto__: null,
|
3445 | [ValueProperties]: PURE,
|
3446 | fromCharCode: PF,
|
3447 | fromCodePoint: PF,
|
3448 | prototype: O,
|
3449 | raw: PF
|
3450 | },
|
3451 | Symbol: {
|
3452 |
|
3453 | __proto__: null,
|
3454 | [ValueProperties]: PURE,
|
3455 | for: PF,
|
3456 | keyFor: PF,
|
3457 | prototype: O
|
3458 | },
|
3459 | SyntaxError: PC,
|
3460 |
|
3461 | toLocaleString: O,
|
3462 |
|
3463 | toString: O,
|
3464 | TypeError: PC,
|
3465 | Uint16Array: ARRAY_TYPE,
|
3466 | Uint32Array: ARRAY_TYPE,
|
3467 | Uint8Array: ARRAY_TYPE,
|
3468 | Uint8ClampedArray: ARRAY_TYPE,
|
3469 |
|
3470 |
|
3471 | unescape: PF,
|
3472 | URIError: PC,
|
3473 |
|
3474 | valueOf: O,
|
3475 | WeakMap: PC,
|
3476 | WeakSet: PC,
|
3477 |
|
3478 | clearInterval: C,
|
3479 | clearTimeout: C,
|
3480 | console: O,
|
3481 | Intl: {
|
3482 |
|
3483 | __proto__: null,
|
3484 | [ValueProperties]: IMPURE,
|
3485 | Collator: INTL_MEMBER,
|
3486 | DateTimeFormat: INTL_MEMBER,
|
3487 | ListFormat: INTL_MEMBER,
|
3488 | NumberFormat: INTL_MEMBER,
|
3489 | PluralRules: INTL_MEMBER,
|
3490 | RelativeTimeFormat: INTL_MEMBER
|
3491 | },
|
3492 | setInterval: C,
|
3493 | setTimeout: C,
|
3494 | TextDecoder: C,
|
3495 | TextEncoder: C,
|
3496 | URL: C,
|
3497 | URLSearchParams: C,
|
3498 |
|
3499 | AbortController: C,
|
3500 | AbortSignal: C,
|
3501 | addEventListener: O,
|
3502 | alert: O,
|
3503 | AnalyserNode: C,
|
3504 | Animation: C,
|
3505 | AnimationEvent: C,
|
3506 | applicationCache: O,
|
3507 | ApplicationCache: C,
|
3508 | ApplicationCacheErrorEvent: C,
|
3509 | atob: O,
|
3510 | Attr: C,
|
3511 | Audio: C,
|
3512 | AudioBuffer: C,
|
3513 | AudioBufferSourceNode: C,
|
3514 | AudioContext: C,
|
3515 | AudioDestinationNode: C,
|
3516 | AudioListener: C,
|
3517 | AudioNode: C,
|
3518 | AudioParam: C,
|
3519 | AudioProcessingEvent: C,
|
3520 | AudioScheduledSourceNode: C,
|
3521 | AudioWorkletNode: C,
|
3522 | BarProp: C,
|
3523 | BaseAudioContext: C,
|
3524 | BatteryManager: C,
|
3525 | BeforeUnloadEvent: C,
|
3526 | BiquadFilterNode: C,
|
3527 | Blob: C,
|
3528 | BlobEvent: C,
|
3529 | blur: O,
|
3530 | BroadcastChannel: C,
|
3531 | btoa: O,
|
3532 | ByteLengthQueuingStrategy: C,
|
3533 | Cache: C,
|
3534 | caches: O,
|
3535 | CacheStorage: C,
|
3536 | cancelAnimationFrame: O,
|
3537 | cancelIdleCallback: O,
|
3538 | CanvasCaptureMediaStreamTrack: C,
|
3539 | CanvasGradient: C,
|
3540 | CanvasPattern: C,
|
3541 | CanvasRenderingContext2D: C,
|
3542 | ChannelMergerNode: C,
|
3543 | ChannelSplitterNode: C,
|
3544 | CharacterData: C,
|
3545 | clientInformation: O,
|
3546 | ClipboardEvent: C,
|
3547 | close: O,
|
3548 | closed: O,
|
3549 | CloseEvent: C,
|
3550 | Comment: C,
|
3551 | CompositionEvent: C,
|
3552 | confirm: O,
|
3553 | ConstantSourceNode: C,
|
3554 | ConvolverNode: C,
|
3555 | CountQueuingStrategy: C,
|
3556 | createImageBitmap: O,
|
3557 | Credential: C,
|
3558 | CredentialsContainer: C,
|
3559 | crypto: O,
|
3560 | Crypto: C,
|
3561 | CryptoKey: C,
|
3562 | CSS: C,
|
3563 | CSSConditionRule: C,
|
3564 | CSSFontFaceRule: C,
|
3565 | CSSGroupingRule: C,
|
3566 | CSSImportRule: C,
|
3567 | CSSKeyframeRule: C,
|
3568 | CSSKeyframesRule: C,
|
3569 | CSSMediaRule: C,
|
3570 | CSSNamespaceRule: C,
|
3571 | CSSPageRule: C,
|
3572 | CSSRule: C,
|
3573 | CSSRuleList: C,
|
3574 | CSSStyleDeclaration: C,
|
3575 | CSSStyleRule: C,
|
3576 | CSSStyleSheet: C,
|
3577 | CSSSupportsRule: C,
|
3578 | CustomElementRegistry: C,
|
3579 | customElements: O,
|
3580 | CustomEvent: C,
|
3581 | DataTransfer: C,
|
3582 | DataTransferItem: C,
|
3583 | DataTransferItemList: C,
|
3584 | defaultstatus: O,
|
3585 | defaultStatus: O,
|
3586 | DelayNode: C,
|
3587 | DeviceMotionEvent: C,
|
3588 | DeviceOrientationEvent: C,
|
3589 | devicePixelRatio: O,
|
3590 | dispatchEvent: O,
|
3591 | document: O,
|
3592 | Document: C,
|
3593 | DocumentFragment: C,
|
3594 | DocumentType: C,
|
3595 | DOMError: C,
|
3596 | DOMException: C,
|
3597 | DOMImplementation: C,
|
3598 | DOMMatrix: C,
|
3599 | DOMMatrixReadOnly: C,
|
3600 | DOMParser: C,
|
3601 | DOMPoint: C,
|
3602 | DOMPointReadOnly: C,
|
3603 | DOMQuad: C,
|
3604 | DOMRect: C,
|
3605 | DOMRectReadOnly: C,
|
3606 | DOMStringList: C,
|
3607 | DOMStringMap: C,
|
3608 | DOMTokenList: C,
|
3609 | DragEvent: C,
|
3610 | DynamicsCompressorNode: C,
|
3611 | Element: C,
|
3612 | ErrorEvent: C,
|
3613 | Event: C,
|
3614 | EventSource: C,
|
3615 | EventTarget: C,
|
3616 | external: O,
|
3617 | fetch: O,
|
3618 | File: C,
|
3619 | FileList: C,
|
3620 | FileReader: C,
|
3621 | find: O,
|
3622 | focus: O,
|
3623 | FocusEvent: C,
|
3624 | FontFace: C,
|
3625 | FontFaceSetLoadEvent: C,
|
3626 | FormData: C,
|
3627 | frames: O,
|
3628 | GainNode: C,
|
3629 | Gamepad: C,
|
3630 | GamepadButton: C,
|
3631 | GamepadEvent: C,
|
3632 | getComputedStyle: O,
|
3633 | getSelection: O,
|
3634 | HashChangeEvent: C,
|
3635 | Headers: C,
|
3636 | history: O,
|
3637 | History: C,
|
3638 | HTMLAllCollection: C,
|
3639 | HTMLAnchorElement: C,
|
3640 | HTMLAreaElement: C,
|
3641 | HTMLAudioElement: C,
|
3642 | HTMLBaseElement: C,
|
3643 | HTMLBodyElement: C,
|
3644 | HTMLBRElement: C,
|
3645 | HTMLButtonElement: C,
|
3646 | HTMLCanvasElement: C,
|
3647 | HTMLCollection: C,
|
3648 | HTMLContentElement: C,
|
3649 | HTMLDataElement: C,
|
3650 | HTMLDataListElement: C,
|
3651 | HTMLDetailsElement: C,
|
3652 | HTMLDialogElement: C,
|
3653 | HTMLDirectoryElement: C,
|
3654 | HTMLDivElement: C,
|
3655 | HTMLDListElement: C,
|
3656 | HTMLDocument: C,
|
3657 | HTMLElement: C,
|
3658 | HTMLEmbedElement: C,
|
3659 | HTMLFieldSetElement: C,
|
3660 | HTMLFontElement: C,
|
3661 | HTMLFormControlsCollection: C,
|
3662 | HTMLFormElement: C,
|
3663 | HTMLFrameElement: C,
|
3664 | HTMLFrameSetElement: C,
|
3665 | HTMLHeadElement: C,
|
3666 | HTMLHeadingElement: C,
|
3667 | HTMLHRElement: C,
|
3668 | HTMLHtmlElement: C,
|
3669 | HTMLIFrameElement: C,
|
3670 | HTMLImageElement: C,
|
3671 | HTMLInputElement: C,
|
3672 | HTMLLabelElement: C,
|
3673 | HTMLLegendElement: C,
|
3674 | HTMLLIElement: C,
|
3675 | HTMLLinkElement: C,
|
3676 | HTMLMapElement: C,
|
3677 | HTMLMarqueeElement: C,
|
3678 | HTMLMediaElement: C,
|
3679 | HTMLMenuElement: C,
|
3680 | HTMLMetaElement: C,
|
3681 | HTMLMeterElement: C,
|
3682 | HTMLModElement: C,
|
3683 | HTMLObjectElement: C,
|
3684 | HTMLOListElement: C,
|
3685 | HTMLOptGroupElement: C,
|
3686 | HTMLOptionElement: C,
|
3687 | HTMLOptionsCollection: C,
|
3688 | HTMLOutputElement: C,
|
3689 | HTMLParagraphElement: C,
|
3690 | HTMLParamElement: C,
|
3691 | HTMLPictureElement: C,
|
3692 | HTMLPreElement: C,
|
3693 | HTMLProgressElement: C,
|
3694 | HTMLQuoteElement: C,
|
3695 | HTMLScriptElement: C,
|
3696 | HTMLSelectElement: C,
|
3697 | HTMLShadowElement: C,
|
3698 | HTMLSlotElement: C,
|
3699 | HTMLSourceElement: C,
|
3700 | HTMLSpanElement: C,
|
3701 | HTMLStyleElement: C,
|
3702 | HTMLTableCaptionElement: C,
|
3703 | HTMLTableCellElement: C,
|
3704 | HTMLTableColElement: C,
|
3705 | HTMLTableElement: C,
|
3706 | HTMLTableRowElement: C,
|
3707 | HTMLTableSectionElement: C,
|
3708 | HTMLTemplateElement: C,
|
3709 | HTMLTextAreaElement: C,
|
3710 | HTMLTimeElement: C,
|
3711 | HTMLTitleElement: C,
|
3712 | HTMLTrackElement: C,
|
3713 | HTMLUListElement: C,
|
3714 | HTMLUnknownElement: C,
|
3715 | HTMLVideoElement: C,
|
3716 | IDBCursor: C,
|
3717 | IDBCursorWithValue: C,
|
3718 | IDBDatabase: C,
|
3719 | IDBFactory: C,
|
3720 | IDBIndex: C,
|
3721 | IDBKeyRange: C,
|
3722 | IDBObjectStore: C,
|
3723 | IDBOpenDBRequest: C,
|
3724 | IDBRequest: C,
|
3725 | IDBTransaction: C,
|
3726 | IDBVersionChangeEvent: C,
|
3727 | IdleDeadline: C,
|
3728 | IIRFilterNode: C,
|
3729 | Image: C,
|
3730 | ImageBitmap: C,
|
3731 | ImageBitmapRenderingContext: C,
|
3732 | ImageCapture: C,
|
3733 | ImageData: C,
|
3734 | indexedDB: O,
|
3735 | innerHeight: O,
|
3736 | innerWidth: O,
|
3737 | InputEvent: C,
|
3738 | IntersectionObserver: C,
|
3739 | IntersectionObserverEntry: C,
|
3740 | isSecureContext: O,
|
3741 | KeyboardEvent: C,
|
3742 | KeyframeEffect: C,
|
3743 | length: O,
|
3744 | localStorage: O,
|
3745 | location: O,
|
3746 | Location: C,
|
3747 | locationbar: O,
|
3748 | matchMedia: O,
|
3749 | MediaDeviceInfo: C,
|
3750 | MediaDevices: C,
|
3751 | MediaElementAudioSourceNode: C,
|
3752 | MediaEncryptedEvent: C,
|
3753 | MediaError: C,
|
3754 | MediaKeyMessageEvent: C,
|
3755 | MediaKeySession: C,
|
3756 | MediaKeyStatusMap: C,
|
3757 | MediaKeySystemAccess: C,
|
3758 | MediaList: C,
|
3759 | MediaQueryList: C,
|
3760 | MediaQueryListEvent: C,
|
3761 | MediaRecorder: C,
|
3762 | MediaSettingsRange: C,
|
3763 | MediaSource: C,
|
3764 | MediaStream: C,
|
3765 | MediaStreamAudioDestinationNode: C,
|
3766 | MediaStreamAudioSourceNode: C,
|
3767 | MediaStreamEvent: C,
|
3768 | MediaStreamTrack: C,
|
3769 | MediaStreamTrackEvent: C,
|
3770 | menubar: O,
|
3771 | MessageChannel: C,
|
3772 | MessageEvent: C,
|
3773 | MessagePort: C,
|
3774 | MIDIAccess: C,
|
3775 | MIDIConnectionEvent: C,
|
3776 | MIDIInput: C,
|
3777 | MIDIInputMap: C,
|
3778 | MIDIMessageEvent: C,
|
3779 | MIDIOutput: C,
|
3780 | MIDIOutputMap: C,
|
3781 | MIDIPort: C,
|
3782 | MimeType: C,
|
3783 | MimeTypeArray: C,
|
3784 | MouseEvent: C,
|
3785 | moveBy: O,
|
3786 | moveTo: O,
|
3787 | MutationEvent: C,
|
3788 | MutationObserver: C,
|
3789 | MutationRecord: C,
|
3790 | name: O,
|
3791 | NamedNodeMap: C,
|
3792 | NavigationPreloadManager: C,
|
3793 | navigator: O,
|
3794 | Navigator: C,
|
3795 | NetworkInformation: C,
|
3796 | Node: C,
|
3797 | NodeFilter: O,
|
3798 | NodeIterator: C,
|
3799 | NodeList: C,
|
3800 | Notification: C,
|
3801 | OfflineAudioCompletionEvent: C,
|
3802 | OfflineAudioContext: C,
|
3803 | offscreenBuffering: O,
|
3804 | OffscreenCanvas: C,
|
3805 | open: O,
|
3806 | openDatabase: O,
|
3807 | Option: C,
|
3808 | origin: O,
|
3809 | OscillatorNode: C,
|
3810 | outerHeight: O,
|
3811 | outerWidth: O,
|
3812 | PageTransitionEvent: C,
|
3813 | pageXOffset: O,
|
3814 | pageYOffset: O,
|
3815 | PannerNode: C,
|
3816 | parent: O,
|
3817 | Path2D: C,
|
3818 | PaymentAddress: C,
|
3819 | PaymentRequest: C,
|
3820 | PaymentRequestUpdateEvent: C,
|
3821 | PaymentResponse: C,
|
3822 | performance: O,
|
3823 | Performance: C,
|
3824 | PerformanceEntry: C,
|
3825 | PerformanceLongTaskTiming: C,
|
3826 | PerformanceMark: C,
|
3827 | PerformanceMeasure: C,
|
3828 | PerformanceNavigation: C,
|
3829 | PerformanceNavigationTiming: C,
|
3830 | PerformanceObserver: C,
|
3831 | PerformanceObserverEntryList: C,
|
3832 | PerformancePaintTiming: C,
|
3833 | PerformanceResourceTiming: C,
|
3834 | PerformanceTiming: C,
|
3835 | PeriodicWave: C,
|
3836 | Permissions: C,
|
3837 | PermissionStatus: C,
|
3838 | personalbar: O,
|
3839 | PhotoCapabilities: C,
|
3840 | Plugin: C,
|
3841 | PluginArray: C,
|
3842 | PointerEvent: C,
|
3843 | PopStateEvent: C,
|
3844 | postMessage: O,
|
3845 | Presentation: C,
|
3846 | PresentationAvailability: C,
|
3847 | PresentationConnection: C,
|
3848 | PresentationConnectionAvailableEvent: C,
|
3849 | PresentationConnectionCloseEvent: C,
|
3850 | PresentationConnectionList: C,
|
3851 | PresentationReceiver: C,
|
3852 | PresentationRequest: C,
|
3853 | print: O,
|
3854 | ProcessingInstruction: C,
|
3855 | ProgressEvent: C,
|
3856 | PromiseRejectionEvent: C,
|
3857 | prompt: O,
|
3858 | PushManager: C,
|
3859 | PushSubscription: C,
|
3860 | PushSubscriptionOptions: C,
|
3861 | queueMicrotask: O,
|
3862 | RadioNodeList: C,
|
3863 | Range: C,
|
3864 | ReadableStream: C,
|
3865 | RemotePlayback: C,
|
3866 | removeEventListener: O,
|
3867 | Request: C,
|
3868 | requestAnimationFrame: O,
|
3869 | requestIdleCallback: O,
|
3870 | resizeBy: O,
|
3871 | ResizeObserver: C,
|
3872 | ResizeObserverEntry: C,
|
3873 | resizeTo: O,
|
3874 | Response: C,
|
3875 | RTCCertificate: C,
|
3876 | RTCDataChannel: C,
|
3877 | RTCDataChannelEvent: C,
|
3878 | RTCDtlsTransport: C,
|
3879 | RTCIceCandidate: C,
|
3880 | RTCIceTransport: C,
|
3881 | RTCPeerConnection: C,
|
3882 | RTCPeerConnectionIceEvent: C,
|
3883 | RTCRtpReceiver: C,
|
3884 | RTCRtpSender: C,
|
3885 | RTCSctpTransport: C,
|
3886 | RTCSessionDescription: C,
|
3887 | RTCStatsReport: C,
|
3888 | RTCTrackEvent: C,
|
3889 | screen: O,
|
3890 | Screen: C,
|
3891 | screenLeft: O,
|
3892 | ScreenOrientation: C,
|
3893 | screenTop: O,
|
3894 | screenX: O,
|
3895 | screenY: O,
|
3896 | ScriptProcessorNode: C,
|
3897 | scroll: O,
|
3898 | scrollbars: O,
|
3899 | scrollBy: O,
|
3900 | scrollTo: O,
|
3901 | scrollX: O,
|
3902 | scrollY: O,
|
3903 | SecurityPolicyViolationEvent: C,
|
3904 | Selection: C,
|
3905 | ServiceWorker: C,
|
3906 | ServiceWorkerContainer: C,
|
3907 | ServiceWorkerRegistration: C,
|
3908 | sessionStorage: O,
|
3909 | ShadowRoot: C,
|
3910 | SharedWorker: C,
|
3911 | SourceBuffer: C,
|
3912 | SourceBufferList: C,
|
3913 | speechSynthesis: O,
|
3914 | SpeechSynthesisEvent: C,
|
3915 | SpeechSynthesisUtterance: C,
|
3916 | StaticRange: C,
|
3917 | status: O,
|
3918 | statusbar: O,
|
3919 | StereoPannerNode: C,
|
3920 | stop: O,
|
3921 | Storage: C,
|
3922 | StorageEvent: C,
|
3923 | StorageManager: C,
|
3924 | styleMedia: O,
|
3925 | StyleSheet: C,
|
3926 | StyleSheetList: C,
|
3927 | SubtleCrypto: C,
|
3928 | SVGAElement: C,
|
3929 | SVGAngle: C,
|
3930 | SVGAnimatedAngle: C,
|
3931 | SVGAnimatedBoolean: C,
|
3932 | SVGAnimatedEnumeration: C,
|
3933 | SVGAnimatedInteger: C,
|
3934 | SVGAnimatedLength: C,
|
3935 | SVGAnimatedLengthList: C,
|
3936 | SVGAnimatedNumber: C,
|
3937 | SVGAnimatedNumberList: C,
|
3938 | SVGAnimatedPreserveAspectRatio: C,
|
3939 | SVGAnimatedRect: C,
|
3940 | SVGAnimatedString: C,
|
3941 | SVGAnimatedTransformList: C,
|
3942 | SVGAnimateElement: C,
|
3943 | SVGAnimateMotionElement: C,
|
3944 | SVGAnimateTransformElement: C,
|
3945 | SVGAnimationElement: C,
|
3946 | SVGCircleElement: C,
|
3947 | SVGClipPathElement: C,
|
3948 | SVGComponentTransferFunctionElement: C,
|
3949 | SVGDefsElement: C,
|
3950 | SVGDescElement: C,
|
3951 | SVGDiscardElement: C,
|
3952 | SVGElement: C,
|
3953 | SVGEllipseElement: C,
|
3954 | SVGFEBlendElement: C,
|
3955 | SVGFEColorMatrixElement: C,
|
3956 | SVGFEComponentTransferElement: C,
|
3957 | SVGFECompositeElement: C,
|
3958 | SVGFEConvolveMatrixElement: C,
|
3959 | SVGFEDiffuseLightingElement: C,
|
3960 | SVGFEDisplacementMapElement: C,
|
3961 | SVGFEDistantLightElement: C,
|
3962 | SVGFEDropShadowElement: C,
|
3963 | SVGFEFloodElement: C,
|
3964 | SVGFEFuncAElement: C,
|
3965 | SVGFEFuncBElement: C,
|
3966 | SVGFEFuncGElement: C,
|
3967 | SVGFEFuncRElement: C,
|
3968 | SVGFEGaussianBlurElement: C,
|
3969 | SVGFEImageElement: C,
|
3970 | SVGFEMergeElement: C,
|
3971 | SVGFEMergeNodeElement: C,
|
3972 | SVGFEMorphologyElement: C,
|
3973 | SVGFEOffsetElement: C,
|
3974 | SVGFEPointLightElement: C,
|
3975 | SVGFESpecularLightingElement: C,
|
3976 | SVGFESpotLightElement: C,
|
3977 | SVGFETileElement: C,
|
3978 | SVGFETurbulenceElement: C,
|
3979 | SVGFilterElement: C,
|
3980 | SVGForeignObjectElement: C,
|
3981 | SVGGElement: C,
|
3982 | SVGGeometryElement: C,
|
3983 | SVGGradientElement: C,
|
3984 | SVGGraphicsElement: C,
|
3985 | SVGImageElement: C,
|
3986 | SVGLength: C,
|
3987 | SVGLengthList: C,
|
3988 | SVGLinearGradientElement: C,
|
3989 | SVGLineElement: C,
|
3990 | SVGMarkerElement: C,
|
3991 | SVGMaskElement: C,
|
3992 | SVGMatrix: C,
|
3993 | SVGMetadataElement: C,
|
3994 | SVGMPathElement: C,
|
3995 | SVGNumber: C,
|
3996 | SVGNumberList: C,
|
3997 | SVGPathElement: C,
|
3998 | SVGPatternElement: C,
|
3999 | SVGPoint: C,
|
4000 | SVGPointList: C,
|
4001 | SVGPolygonElement: C,
|
4002 | SVGPolylineElement: C,
|
4003 | SVGPreserveAspectRatio: C,
|
4004 | SVGRadialGradientElement: C,
|
4005 | SVGRect: C,
|
4006 | SVGRectElement: C,
|
4007 | SVGScriptElement: C,
|
4008 | SVGSetElement: C,
|
4009 | SVGStopElement: C,
|
4010 | SVGStringList: C,
|
4011 | SVGStyleElement: C,
|
4012 | SVGSVGElement: C,
|
4013 | SVGSwitchElement: C,
|
4014 | SVGSymbolElement: C,
|
4015 | SVGTextContentElement: C,
|
4016 | SVGTextElement: C,
|
4017 | SVGTextPathElement: C,
|
4018 | SVGTextPositioningElement: C,
|
4019 | SVGTitleElement: C,
|
4020 | SVGTransform: C,
|
4021 | SVGTransformList: C,
|
4022 | SVGTSpanElement: C,
|
4023 | SVGUnitTypes: C,
|
4024 | SVGUseElement: C,
|
4025 | SVGViewElement: C,
|
4026 | TaskAttributionTiming: C,
|
4027 | Text: C,
|
4028 | TextEvent: C,
|
4029 | TextMetrics: C,
|
4030 | TextTrack: C,
|
4031 | TextTrackCue: C,
|
4032 | TextTrackCueList: C,
|
4033 | TextTrackList: C,
|
4034 | TimeRanges: C,
|
4035 | toolbar: O,
|
4036 | top: O,
|
4037 | Touch: C,
|
4038 | TouchEvent: C,
|
4039 | TouchList: C,
|
4040 | TrackEvent: C,
|
4041 | TransitionEvent: C,
|
4042 | TreeWalker: C,
|
4043 | UIEvent: C,
|
4044 | ValidityState: C,
|
4045 | visualViewport: O,
|
4046 | VisualViewport: C,
|
4047 | VTTCue: C,
|
4048 | WaveShaperNode: C,
|
4049 | WebAssembly: O,
|
4050 | WebGL2RenderingContext: C,
|
4051 | WebGLActiveInfo: C,
|
4052 | WebGLBuffer: C,
|
4053 | WebGLContextEvent: C,
|
4054 | WebGLFramebuffer: C,
|
4055 | WebGLProgram: C,
|
4056 | WebGLQuery: C,
|
4057 | WebGLRenderbuffer: C,
|
4058 | WebGLRenderingContext: C,
|
4059 | WebGLSampler: C,
|
4060 | WebGLShader: C,
|
4061 | WebGLShaderPrecisionFormat: C,
|
4062 | WebGLSync: C,
|
4063 | WebGLTexture: C,
|
4064 | WebGLTransformFeedback: C,
|
4065 | WebGLUniformLocation: C,
|
4066 | WebGLVertexArrayObject: C,
|
4067 | WebSocket: C,
|
4068 | WheelEvent: C,
|
4069 | Window: C,
|
4070 | Worker: C,
|
4071 | WritableStream: C,
|
4072 | XMLDocument: C,
|
4073 | XMLHttpRequest: C,
|
4074 | XMLHttpRequestEventTarget: C,
|
4075 | XMLHttpRequestUpload: C,
|
4076 | XMLSerializer: C,
|
4077 | XPathEvaluator: C,
|
4078 | XPathExpression: C,
|
4079 | XPathResult: C,
|
4080 | XSLTProcessor: C
|
4081 | };
|
4082 | for (const global of ['window', 'global', 'self', 'globalThis']) {
|
4083 | knownGlobals[global] = knownGlobals;
|
4084 | }
|
4085 | function getGlobalAtPath(path) {
|
4086 | let currentGlobal = knownGlobals;
|
4087 | for (const pathSegment of path) {
|
4088 | if (typeof pathSegment !== 'string') {
|
4089 | return null;
|
4090 | }
|
4091 | currentGlobal = currentGlobal[pathSegment];
|
4092 | if (!currentGlobal) {
|
4093 | return null;
|
4094 | }
|
4095 | }
|
4096 | return currentGlobal[ValueProperties];
|
4097 | }
|
4098 | function isPureGlobal(path) {
|
4099 | const globalAtPath = getGlobalAtPath(path);
|
4100 | return globalAtPath !== null && globalAtPath.pure;
|
4101 | }
|
4102 | function isGlobalMember(path) {
|
4103 | if (path.length === 1) {
|
4104 | return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
|
4105 | }
|
4106 | return getGlobalAtPath(path.slice(0, -1)) !== null;
|
4107 | }
|
4108 |
|
4109 | class GlobalVariable extends Variable {
|
4110 | constructor() {
|
4111 | super(...arguments);
|
4112 | this.isReassigned = true;
|
4113 | }
|
4114 | hasEffectsWhenAccessedAtPath(path) {
|
4115 | return !isGlobalMember([this.name, ...path]);
|
4116 | }
|
4117 | hasEffectsWhenCalledAtPath(path) {
|
4118 | return !isPureGlobal([this.name, ...path]);
|
4119 | }
|
4120 | }
|
4121 |
|
4122 | class Identifier$1 extends NodeBase {
|
4123 | constructor() {
|
4124 | super(...arguments);
|
4125 | this.variable = null;
|
4126 | this.bound = false;
|
4127 | }
|
4128 | addExportedVariables(variables, exportNamesByVariable) {
|
4129 | if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
|
4130 | variables.push(this.variable);
|
4131 | }
|
4132 | }
|
4133 | bind() {
|
4134 | if (this.bound)
|
4135 | return;
|
4136 | this.bound = true;
|
4137 | if (this.variable === null && isReference(this, this.parent)) {
|
4138 | this.variable = this.scope.findVariable(this.name);
|
4139 | this.variable.addReference(this);
|
4140 | }
|
4141 | if (this.variable !== null &&
|
4142 | this.variable instanceof LocalVariable &&
|
4143 | this.variable.additionalInitializers !== null) {
|
4144 | this.variable.consolidateInitializers();
|
4145 | }
|
4146 | }
|
4147 | declare(kind, init) {
|
4148 | let variable;
|
4149 | switch (kind) {
|
4150 | case 'var':
|
4151 | variable = this.scope.addDeclaration(this, this.context, init, true);
|
4152 | break;
|
4153 | case 'function':
|
4154 |
|
4155 | variable = this.scope.addDeclaration(this, this.context, init, false);
|
4156 | break;
|
4157 | case 'let':
|
4158 | case 'const':
|
4159 | case 'class':
|
4160 | variable = this.scope.addDeclaration(this, this.context, init, false);
|
4161 | break;
|
4162 | case 'parameter':
|
4163 | variable = this.scope.addParameterDeclaration(this);
|
4164 | break;
|
4165 |
|
4166 | default:
|
4167 |
|
4168 | throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
|
4169 | }
|
4170 | return [(this.variable = variable)];
|
4171 | }
|
4172 | deoptimizePath(path) {
|
4173 | if (!this.bound)
|
4174 | this.bind();
|
4175 | if (path.length === 0 && !this.scope.contains(this.name)) {
|
4176 | this.disallowImportReassignment();
|
4177 | }
|
4178 | this.variable.deoptimizePath(path);
|
4179 | }
|
4180 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
4181 | if (!this.bound)
|
4182 | this.bind();
|
4183 | return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
|
4184 | }
|
4185 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
4186 | if (!this.bound)
|
4187 | this.bind();
|
4188 | return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
4189 | }
|
4190 | hasEffects() {
|
4191 | return (this.context.options.treeshake.unknownGlobalSideEffects &&
|
4192 | this.variable instanceof GlobalVariable &&
|
4193 | this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
|
4194 | }
|
4195 | hasEffectsWhenAccessedAtPath(path, context) {
|
4196 | return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
|
4197 | }
|
4198 | hasEffectsWhenAssignedAtPath(path, context) {
|
4199 | return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
|
4200 | }
|
4201 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
4202 | return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
4203 | }
|
4204 | include() {
|
4205 | if (!this.included) {
|
4206 | this.included = true;
|
4207 | if (this.variable !== null) {
|
4208 | this.context.includeVariable(this.variable);
|
4209 | }
|
4210 | }
|
4211 | }
|
4212 | includeCallArguments(context, args) {
|
4213 | this.variable.includeCallArguments(context, args);
|
4214 | }
|
4215 | render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
|
4216 | if (this.variable) {
|
4217 | const name = this.variable.getName();
|
4218 | if (name !== this.name) {
|
4219 | code.overwrite(this.start, this.end, name, {
|
4220 | contentOnly: true,
|
4221 | storeName: true
|
4222 | });
|
4223 | if (isShorthandProperty) {
|
4224 | code.prependRight(this.start, `${this.name}: `);
|
4225 | }
|
4226 | }
|
4227 |
|
4228 | if (name === 'eval' &&
|
4229 | renderedParentType === CallExpression &&
|
4230 | isCalleeOfRenderedParent) {
|
4231 | code.appendRight(this.start, '0, ');
|
4232 | }
|
4233 | }
|
4234 | }
|
4235 | disallowImportReassignment() {
|
4236 | return this.context.error({
|
4237 | code: 'ILLEGAL_REASSIGNMENT',
|
4238 | message: `Illegal reassignment to import '${this.name}'`
|
4239 | }, this.start);
|
4240 | }
|
4241 | }
|
4242 |
|
4243 | class RestElement extends NodeBase {
|
4244 | constructor() {
|
4245 | super(...arguments);
|
4246 | this.declarationInit = null;
|
4247 | }
|
4248 | addExportedVariables(variables, exportNamesByVariable) {
|
4249 | this.argument.addExportedVariables(variables, exportNamesByVariable);
|
4250 | }
|
4251 | bind() {
|
4252 | super.bind();
|
4253 | if (this.declarationInit !== null) {
|
4254 | this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
|
4255 | }
|
4256 | }
|
4257 | declare(kind, init) {
|
4258 | this.declarationInit = init;
|
4259 | return this.argument.declare(kind, UNKNOWN_EXPRESSION);
|
4260 | }
|
4261 | deoptimizePath(path) {
|
4262 | path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
|
4263 | }
|
4264 | hasEffectsWhenAssignedAtPath(path, context) {
|
4265 | return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
|
4266 | }
|
4267 | }
|
4268 |
|
4269 | class FunctionNode extends NodeBase {
|
4270 | constructor() {
|
4271 | super(...arguments);
|
4272 | this.isPrototypeDeoptimized = false;
|
4273 | }
|
4274 | createScope(parentScope) {
|
4275 | this.scope = new FunctionScope(parentScope, this.context);
|
4276 | }
|
4277 | deoptimizePath(path) {
|
4278 | if (path.length === 1) {
|
4279 | if (path[0] === 'prototype') {
|
4280 | this.isPrototypeDeoptimized = true;
|
4281 | }
|
4282 | else if (path[0] === UnknownKey) {
|
4283 | this.isPrototypeDeoptimized = true;
|
4284 |
|
4285 |
|
4286 | this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
|
4287 | }
|
4288 | }
|
4289 | }
|
4290 | getReturnExpressionWhenCalledAtPath(path) {
|
4291 | return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
|
4292 | }
|
4293 | hasEffects() {
|
4294 | return this.id !== null && this.id.hasEffects();
|
4295 | }
|
4296 | hasEffectsWhenAccessedAtPath(path) {
|
4297 | if (path.length <= 1)
|
4298 | return false;
|
4299 | return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
|
4300 | }
|
4301 | hasEffectsWhenAssignedAtPath(path) {
|
4302 | if (path.length <= 1) {
|
4303 | return false;
|
4304 | }
|
4305 | return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
|
4306 | }
|
4307 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
4308 | if (path.length > 0)
|
4309 | return true;
|
4310 | for (const param of this.params) {
|
4311 | if (param.hasEffects(context))
|
4312 | return true;
|
4313 | }
|
4314 | const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
|
4315 | context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
|
4316 | const { brokenFlow, ignore } = context;
|
4317 | context.ignore = {
|
4318 | breaks: false,
|
4319 | continues: false,
|
4320 | labels: new Set(),
|
4321 | returnAwaitYield: true
|
4322 | };
|
4323 | if (this.body.hasEffects(context))
|
4324 | return true;
|
4325 | context.brokenFlow = brokenFlow;
|
4326 | if (thisInit) {
|
4327 | context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
|
4328 | }
|
4329 | else {
|
4330 | context.replacedVariableInits.delete(this.scope.thisVariable);
|
4331 | }
|
4332 | context.ignore = ignore;
|
4333 | return false;
|
4334 | }
|
4335 | include(context, includeChildrenRecursively) {
|
4336 | this.included = true;
|
4337 | if (this.id)
|
4338 | this.id.include();
|
4339 | const hasArguments = this.scope.argumentsVariable.included;
|
4340 | for (const param of this.params) {
|
4341 | if (!(param instanceof Identifier$1) || hasArguments) {
|
4342 | param.include(context, includeChildrenRecursively);
|
4343 | }
|
4344 | }
|
4345 | const { brokenFlow } = context;
|
4346 | context.brokenFlow = BROKEN_FLOW_NONE;
|
4347 | this.body.include(context, includeChildrenRecursively);
|
4348 | context.brokenFlow = brokenFlow;
|
4349 | }
|
4350 | includeCallArguments(context, args) {
|
4351 | this.scope.includeCallArguments(context, args);
|
4352 | }
|
4353 | initialise() {
|
4354 | if (this.id !== null) {
|
4355 | this.id.declare('function', this);
|
4356 | }
|
4357 | this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
|
4358 | this.body.addImplicitReturnExpressionToScope();
|
4359 | }
|
4360 | parseNode(esTreeNode) {
|
4361 | this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
|
4362 | super.parseNode(esTreeNode);
|
4363 | }
|
4364 | }
|
4365 | FunctionNode.prototype.preventChildBlockScope = true;
|
4366 |
|
4367 | class FunctionDeclaration extends FunctionNode {
|
4368 | initialise() {
|
4369 | super.initialise();
|
4370 | if (this.id !== null) {
|
4371 | this.id.variable.isId = true;
|
4372 | }
|
4373 | }
|
4374 | parseNode(esTreeNode) {
|
4375 | if (esTreeNode.id !== null) {
|
4376 | this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
|
4377 | .parent);
|
4378 | }
|
4379 | super.parseNode(esTreeNode);
|
4380 | }
|
4381 | }
|
4382 |
|
4383 |
|
4384 | function getDeclarationStart(code, start) {
|
4385 | return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
|
4386 | }
|
4387 | function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
|
4388 | const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
|
4389 | code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
|
4390 | const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
|
4391 | if (generatorStarPos === -1) {
|
4392 | return declarationEnd;
|
4393 | }
|
4394 | return declarationEnd + generatorStarPos + 1;
|
4395 | }
|
4396 | class ExportDefaultDeclaration extends NodeBase {
|
4397 | include(context, includeChildrenRecursively) {
|
4398 | super.include(context, includeChildrenRecursively);
|
4399 | if (includeChildrenRecursively) {
|
4400 | this.context.includeVariable(this.variable);
|
4401 | }
|
4402 | }
|
4403 | initialise() {
|
4404 | const declaration = this.declaration;
|
4405 | this.declarationName =
|
4406 | (declaration.id && declaration.id.name) || this.declaration.name;
|
4407 | this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
|
4408 | this.context.addExport(this);
|
4409 | }
|
4410 | render(code, options, nodeRenderOptions) {
|
4411 | const { start, end } = nodeRenderOptions;
|
4412 | const declarationStart = getDeclarationStart(code.original, this.start);
|
4413 | if (this.declaration instanceof FunctionDeclaration) {
|
4414 | this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
|
4415 | }
|
4416 | else if (this.declaration instanceof ClassDeclaration) {
|
4417 | this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
|
4418 | }
|
4419 | else if (this.variable.getOriginalVariable() !== this.variable) {
|
4420 |
|
4421 | treeshakeNode(this, code, start, end);
|
4422 | return;
|
4423 | }
|
4424 | else if (this.variable.included) {
|
4425 | this.renderVariableDeclaration(code, declarationStart, options);
|
4426 | }
|
4427 | else {
|
4428 | code.remove(this.start, declarationStart);
|
4429 | this.declaration.render(code, options, {
|
4430 | isCalleeOfRenderedParent: false,
|
4431 | renderedParentType: ExpressionStatement
|
4432 | });
|
4433 | if (code.original[this.end - 1] !== ';') {
|
4434 | code.appendLeft(this.end, ';');
|
4435 | }
|
4436 | return;
|
4437 | }
|
4438 | this.declaration.render(code, options);
|
4439 | }
|
4440 | renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
|
4441 | const name = this.variable.getName();
|
4442 |
|
4443 | code.remove(this.start, declarationStart);
|
4444 | if (needsId) {
|
4445 | code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
|
4446 | }
|
4447 | if (options.format === 'system' &&
|
4448 | this.declaration instanceof ClassDeclaration &&
|
4449 | options.exportNamesByVariable.has(this.variable)) {
|
4450 | code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
|
4451 | }
|
4452 | }
|
4453 | renderVariableDeclaration(code, declarationStart, options) {
|
4454 | const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59;
|
4455 | const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
|
4456 | if (systemExportNames) {
|
4457 | code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
|
4458 | code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
|
4459 | }
|
4460 | else {
|
4461 | code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
|
4462 | if (!hasTrailingSemicolon) {
|
4463 | code.appendLeft(this.end, ';');
|
4464 | }
|
4465 | }
|
4466 | }
|
4467 | }
|
4468 | ExportDefaultDeclaration.prototype.needsBoundaries = true;
|
4469 |
|
4470 | class UndefinedVariable extends Variable {
|
4471 | constructor() {
|
4472 | super('undefined');
|
4473 | }
|
4474 | getLiteralValueAtPath() {
|
4475 | return undefined;
|
4476 | }
|
4477 | }
|
4478 |
|
4479 | class ExportDefaultVariable extends LocalVariable {
|
4480 | constructor(name, exportDefaultDeclaration, context) {
|
4481 | super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
|
4482 | this.hasId = false;
|
4483 |
|
4484 | this.originalId = null;
|
4485 | this.originalVariableAndDeclarationModules = null;
|
4486 | const declaration = exportDefaultDeclaration.declaration;
|
4487 | if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
|
4488 | declaration.id) {
|
4489 | this.hasId = true;
|
4490 | this.originalId = declaration.id;
|
4491 | }
|
4492 | else if (declaration instanceof Identifier$1) {
|
4493 | this.originalId = declaration;
|
4494 | }
|
4495 | }
|
4496 | addReference(identifier) {
|
4497 | if (!this.hasId) {
|
4498 | this.name = identifier.name;
|
4499 | }
|
4500 | }
|
4501 | getAssignedVariableName() {
|
4502 | return (this.originalId && this.originalId.name) || null;
|
4503 | }
|
4504 | getBaseVariableName() {
|
4505 | const original = this.getOriginalVariable();
|
4506 | if (original === this) {
|
4507 | return super.getBaseVariableName();
|
4508 | }
|
4509 | else {
|
4510 | return original.getBaseVariableName();
|
4511 | }
|
4512 | }
|
4513 | getName() {
|
4514 | const original = this.getOriginalVariable();
|
4515 | if (original === this) {
|
4516 | return super.getName();
|
4517 | }
|
4518 | else {
|
4519 | return original.getName();
|
4520 | }
|
4521 | }
|
4522 | getOriginalVariable() {
|
4523 | return this.getOriginalVariableAndDeclarationModules().original;
|
4524 | }
|
4525 | getOriginalVariableAndDeclarationModules() {
|
4526 | if (this.originalVariableAndDeclarationModules === null) {
|
4527 | if (!this.originalId ||
|
4528 | (!this.hasId &&
|
4529 | (this.originalId.variable.isReassigned ||
|
4530 | this.originalId.variable instanceof UndefinedVariable))) {
|
4531 | this.originalVariableAndDeclarationModules = { modules: [], original: this };
|
4532 | }
|
4533 | else {
|
4534 | const assignedOriginal = this.originalId.variable;
|
4535 | if (assignedOriginal instanceof ExportDefaultVariable) {
|
4536 | const { modules, original } = assignedOriginal.getOriginalVariableAndDeclarationModules();
|
4537 | this.originalVariableAndDeclarationModules = {
|
4538 | modules: modules.concat(this.module),
|
4539 | original
|
4540 | };
|
4541 | }
|
4542 | else {
|
4543 | this.originalVariableAndDeclarationModules = {
|
4544 | modules: [this.module],
|
4545 | original: assignedOriginal
|
4546 | };
|
4547 | }
|
4548 | }
|
4549 | }
|
4550 | return this.originalVariableAndDeclarationModules;
|
4551 | }
|
4552 | }
|
4553 |
|
4554 | const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
|
4555 |
|
4556 | class ExportShimVariable extends Variable {
|
4557 | constructor(module) {
|
4558 | super(MISSING_EXPORT_SHIM_VARIABLE);
|
4559 | this.module = module;
|
4560 | }
|
4561 | }
|
4562 |
|
4563 | class NamespaceVariable extends Variable {
|
4564 | constructor(context, syntheticNamedExports) {
|
4565 | super(context.getModuleName());
|
4566 | this.memberVariables = null;
|
4567 | this.mergedNamespaces = [];
|
4568 | this.referencedEarly = false;
|
4569 | this.references = [];
|
4570 | this.context = context;
|
4571 | this.module = context.module;
|
4572 | this.syntheticNamedExports = syntheticNamedExports;
|
4573 | }
|
4574 | addReference(identifier) {
|
4575 | this.references.push(identifier);
|
4576 | this.name = identifier.name;
|
4577 | }
|
4578 |
|
4579 |
|
4580 |
|
4581 |
|
4582 | deoptimizePath() {
|
4583 | const memberVariables = this.getMemberVariables();
|
4584 | for (const key of Object.keys(memberVariables)) {
|
4585 | memberVariables[key].deoptimizePath(UNKNOWN_PATH);
|
4586 | }
|
4587 | }
|
4588 | getMemberVariables() {
|
4589 | if (this.memberVariables) {
|
4590 | return this.memberVariables;
|
4591 | }
|
4592 | const memberVariables = Object.create(null);
|
4593 | for (const name of this.context.getExports().concat(this.context.getReexports())) {
|
4594 | if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
|
4595 | memberVariables[name] = this.context.traceExport(name);
|
4596 | }
|
4597 | }
|
4598 | return (this.memberVariables = memberVariables);
|
4599 | }
|
4600 | include() {
|
4601 | this.included = true;
|
4602 | this.context.includeAllExports();
|
4603 | }
|
4604 | prepareNamespace(mergedNamespaces) {
|
4605 | this.mergedNamespaces = mergedNamespaces;
|
4606 | const moduleExecIndex = this.context.getModuleExecIndex();
|
4607 | for (const identifier of this.references) {
|
4608 | if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
|
4609 | this.referencedEarly = true;
|
4610 | break;
|
4611 | }
|
4612 | }
|
4613 | }
|
4614 | renderBlock(options) {
|
4615 | const _ = options.compact ? '' : ' ';
|
4616 | const n = options.compact ? '' : '\n';
|
4617 | const t = options.indent;
|
4618 | const memberVariables = this.getMemberVariables();
|
4619 | const members = Object.keys(memberVariables).map(name => {
|
4620 | const original = memberVariables[name];
|
4621 | if (this.referencedEarly || original.isReassigned) {
|
4622 | return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
|
4623 | }
|
4624 | const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
|
4625 | return `${t}${safeName}: ${original.getName()}`;
|
4626 | });
|
4627 | if (options.namespaceToStringTag) {
|
4628 | members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
|
4629 | }
|
4630 | const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
|
4631 | if (!needsObjectAssign)
|
4632 | members.unshift(`${t}__proto__:${_}null`);
|
4633 | let output = `{${n}${members.join(`,${n}`)}${n}}`;
|
4634 | if (needsObjectAssign) {
|
4635 | const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
|
4636 | if (this.mergedNamespaces.length > 0) {
|
4637 | assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
|
4638 | }
|
4639 | if (this.syntheticNamedExports) {
|
4640 | assignmentArgs.push(this.module.getSyntheticNamespace().getName());
|
4641 | }
|
4642 | if (members.length > 0) {
|
4643 | assignmentArgs.push(output);
|
4644 | }
|
4645 | output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
|
4646 | }
|
4647 | if (options.freeze) {
|
4648 | output = `/*#__PURE__*/Object.freeze(${output})`;
|
4649 | }
|
4650 | const name = this.getName();
|
4651 | output = `${options.varOrConst} ${name}${_}=${_}${output};`;
|
4652 | if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
|
4653 | output += `${n}${getSystemExportStatement([this], options)};`;
|
4654 | }
|
4655 | return output;
|
4656 | }
|
4657 | renderFirst() {
|
4658 | return this.referencedEarly;
|
4659 | }
|
4660 | }
|
4661 | NamespaceVariable.prototype.isNamespace = true;
|
4662 |
|
4663 | class SyntheticNamedExportVariable extends Variable {
|
4664 | constructor(context, name, syntheticNamespace) {
|
4665 | super(name);
|
4666 | this.context = context;
|
4667 | this.module = context.module;
|
4668 | this.syntheticNamespace = syntheticNamespace;
|
4669 | }
|
4670 | getBaseVariable() {
|
4671 | let baseVariable = this.syntheticNamespace;
|
4672 | if (baseVariable instanceof ExportDefaultVariable) {
|
4673 | baseVariable = baseVariable.getOriginalVariable();
|
4674 | }
|
4675 | if (baseVariable instanceof SyntheticNamedExportVariable) {
|
4676 | baseVariable = baseVariable.getBaseVariable();
|
4677 | }
|
4678 | return baseVariable;
|
4679 | }
|
4680 | getBaseVariableName() {
|
4681 | return this.syntheticNamespace.getBaseVariableName();
|
4682 | }
|
4683 | getName() {
|
4684 | const name = this.name;
|
4685 | return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
|
4686 | }
|
4687 | include() {
|
4688 | if (!this.included) {
|
4689 | this.included = true;
|
4690 | this.context.includeVariable(this.syntheticNamespace);
|
4691 | }
|
4692 | }
|
4693 | setRenderNames(baseName, name) {
|
4694 | super.setRenderNames(baseName, name);
|
4695 | }
|
4696 | }
|
4697 | const getPropertyAccess = (name) => {
|
4698 | return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
|
4699 | ? `.${name}`
|
4700 | : `[${JSON.stringify(name)}]`;
|
4701 | };
|
4702 |
|
4703 | const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
|
4704 | const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
|
4705 | const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
|
4706 | const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
|
4707 | const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
|
4708 | const defaultInteropHelpersByInteropType = {
|
4709 | auto: INTEROP_DEFAULT_VARIABLE,
|
4710 | default: null,
|
4711 | defaultOnly: null,
|
4712 | esModule: null,
|
4713 | false: null,
|
4714 | true: INTEROP_DEFAULT_LEGACY_VARIABLE
|
4715 | };
|
4716 | function isDefaultAProperty(interopType, externalLiveBindings) {
|
4717 | return (interopType === 'esModule' ||
|
4718 | (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
|
4719 | }
|
4720 | const namespaceInteropHelpersByInteropType = {
|
4721 | auto: INTEROP_NAMESPACE_VARIABLE,
|
4722 | default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
|
4723 | defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
|
4724 | esModule: null,
|
4725 | false: null,
|
4726 | true: INTEROP_NAMESPACE_VARIABLE
|
4727 | };
|
4728 | function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
|
4729 | return (isDefaultAProperty(interopType, externalLiveBindings) &&
|
4730 | defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
|
4731 | }
|
4732 | function getDefaultOnlyHelper() {
|
4733 | return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
|
4734 | }
|
4735 | function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
|
4736 | return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
|
4737 | ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
|
4738 | : '').join('');
|
4739 | }
|
4740 | const HELPER_GENERATORS = {
|
4741 | [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
|
4742 | `e${_}&&${_}e.__esModule${_}?${_}` +
|
4743 | `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
|
4744 | [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
|
4745 | `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
|
4746 | `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
|
4747 | [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
|
4748 | (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
|
4749 | ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
|
4750 | : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
|
4751 | createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
|
4752 | `}${n}${n}`,
|
4753 | [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
|
4754 | createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
|
4755 | `}${n}${n}`,
|
4756 | [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
|
4757 | `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
|
4758 | `}${n}${n}`
|
4759 | };
|
4760 | function getDefaultLiveBinding(_) {
|
4761 | return `e${_}:${_}{${_}'default':${_}e${_}}`;
|
4762 | }
|
4763 | function getDefaultStatic(_) {
|
4764 | return `e['default']${_}:${_}e`;
|
4765 | }
|
4766 | function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
|
4767 | return (`${i}var n${_}=${_}${namespaceToStringTag
|
4768 | ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
|
4769 | : 'Object.create(null)'};${n}` +
|
4770 | `${i}if${_}(e)${_}{${n}` +
|
4771 | `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
|
4772 | (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
|
4773 | `${i}${t}});${n}` +
|
4774 | `${i}}${n}` +
|
4775 | `${i}n['default']${_}=${_}e;${n}` +
|
4776 | `${i}return ${getFrozen('n', freeze)};${n}`);
|
4777 | }
|
4778 | function copyPropertyLiveBinding(_, n, t, i) {
|
4779 | return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
|
4780 | `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
|
4781 | `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
|
4782 | `${i}${t}${t}enumerable:${_}true,${n}` +
|
4783 | `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
|
4784 | `${i}${t}${t}${t}return e[k];${n}` +
|
4785 | `${i}${t}${t}}${n}` +
|
4786 | `${i}${t}});${n}` +
|
4787 | `${i}}${n}`);
|
4788 | }
|
4789 | function copyPropertyStatic(_, n, _t, i) {
|
4790 | return `${i}n[k]${_}=${_}e[k];${n}`;
|
4791 | }
|
4792 | function getFrozen(fragment, freeze) {
|
4793 | return freeze ? `Object.freeze(${fragment})` : fragment;
|
4794 | }
|
4795 | const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
|
4796 |
|
4797 | function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
|
4798 | const _ = compact ? '' : ' ';
|
4799 | const n = compact ? '' : '\n';
|
4800 | if (!namedExportsMode) {
|
4801 | return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
|
4802 | }
|
4803 | let exportBlock = '';
|
4804 |
|
4805 | for (const { name, reexports } of dependencies) {
|
4806 | if (reexports && namedExportsMode) {
|
4807 | for (const specifier of reexports) {
|
4808 | if (specifier.reexported === '*') {
|
4809 | if (exportBlock)
|
4810 | exportBlock += n;
|
4811 | if (specifier.needsLiveBinding) {
|
4812 | exportBlock +=
|
4813 | `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
|
4814 | `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
|
4815 | `${t}${t}enumerable:${_}true,${n}` +
|
4816 | `${t}${t}get:${_}function${_}()${_}{${n}` +
|
4817 | `${t}${t}${t}return ${name}[k];${n}` +
|
4818 | `${t}${t}}${n}${t}});${n}});`;
|
4819 | }
|
4820 | else {
|
4821 | exportBlock +=
|
4822 | `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
|
4823 | `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
|
4824 | }
|
4825 | }
|
4826 | }
|
4827 | }
|
4828 | }
|
4829 | for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
|
4830 | if (reexports && namedExportsMode) {
|
4831 | for (const specifier of reexports) {
|
4832 | if (specifier.reexported !== '*') {
|
4833 | const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
|
4834 | if (exportBlock)
|
4835 | exportBlock += n;
|
4836 | exportBlock +=
|
4837 | specifier.imported !== '*' && specifier.needsLiveBinding
|
4838 | ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
|
4839 | `${t}enumerable:${_}true,${n}` +
|
4840 | `${t}get:${_}function${_}()${_}{${n}` +
|
4841 | `${t}${t}return ${importName};${n}${t}}${n}});`
|
4842 | : `exports.${specifier.reexported}${_}=${_}${importName};`;
|
4843 | }
|
4844 | }
|
4845 | }
|
4846 | }
|
4847 | for (const chunkExport of exports) {
|
4848 | const lhs = `exports.${chunkExport.exported}`;
|
4849 | const rhs = chunkExport.local;
|
4850 | if (lhs !== rhs) {
|
4851 | if (exportBlock)
|
4852 | exportBlock += n;
|
4853 | exportBlock += `${lhs}${_}=${_}${rhs};`;
|
4854 | }
|
4855 | }
|
4856 | if (exportBlock) {
|
4857 | return `${n}${n}${exportBlock}`;
|
4858 | }
|
4859 | return '';
|
4860 | }
|
4861 | function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
|
4862 | if (exports.length > 0) {
|
4863 | return exports[0].local;
|
4864 | }
|
4865 | else {
|
4866 | for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
|
4867 | if (reexports) {
|
4868 | return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
|
4869 | }
|
4870 | }
|
4871 | }
|
4872 | }
|
4873 | function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
|
4874 | if (imported === 'default') {
|
4875 | if (!isChunk) {
|
4876 | const moduleInterop = String(interop(moduleId));
|
4877 | const variableName = defaultInteropHelpersByInteropType[moduleInterop]
|
4878 | ? defaultVariableName
|
4879 | : moduleVariableName;
|
4880 | return isDefaultAProperty(moduleInterop, externalLiveBindings)
|
4881 | ? `${variableName}['default']`
|
4882 | : variableName;
|
4883 | }
|
4884 | return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
|
4885 | }
|
4886 | if (imported === '*') {
|
4887 | return (isChunk
|
4888 | ? !depNamedExportsMode
|
4889 | : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
|
4890 | ? namespaceVariableName
|
4891 | : moduleVariableName;
|
4892 | }
|
4893 | return `${moduleVariableName}.${imported}`;
|
4894 | }
|
4895 | function getEsModuleExport(_) {
|
4896 | return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
|
4897 | }
|
4898 | function getNamespaceToStringExport(_) {
|
4899 | return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
|
4900 | }
|
4901 | function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
|
4902 | let namespaceMarkers = '';
|
4903 | if (hasNamedExports) {
|
4904 | if (addEsModule) {
|
4905 | namespaceMarkers += getEsModuleExport(_);
|
4906 | }
|
4907 | if (addNamespaceToStringTag) {
|
4908 | if (namespaceMarkers) {
|
4909 | namespaceMarkers += n;
|
4910 | }
|
4911 | namespaceMarkers += getNamespaceToStringExport(_);
|
4912 | }
|
4913 | }
|
4914 | return namespaceMarkers;
|
4915 | }
|
4916 |
|
4917 | function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
|
4918 | const neededInteropHelpers = new Set();
|
4919 | const interopStatements = [];
|
4920 | const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
|
4921 | neededInteropHelpers.add(helper);
|
4922 | interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
|
4923 | };
|
4924 | for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
|
4925 | if (isChunk) {
|
4926 | for (const { imported, reexported } of [
|
4927 | ...(imports || []),
|
4928 | ...(reexports || [])
|
4929 | ]) {
|
4930 | if (imported === '*' && reexported !== '*') {
|
4931 | if (!namedExportsMode) {
|
4932 | addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
|
4933 | }
|
4934 | break;
|
4935 | }
|
4936 | }
|
4937 | }
|
4938 | else {
|
4939 | const moduleInterop = String(interop(id));
|
4940 | let hasDefault = false;
|
4941 | let hasNamespace = false;
|
4942 | for (const { imported, reexported } of [
|
4943 | ...(imports || []),
|
4944 | ...(reexports || [])
|
4945 | ]) {
|
4946 | let helper;
|
4947 | let variableName;
|
4948 | if (imported === 'default') {
|
4949 | if (!hasDefault) {
|
4950 | hasDefault = true;
|
4951 | if (defaultVariableName !== namespaceVariableName) {
|
4952 | variableName = defaultVariableName;
|
4953 | helper = defaultInteropHelpersByInteropType[moduleInterop];
|
4954 | }
|
4955 | }
|
4956 | }
|
4957 | else if (imported === '*' && reexported !== '*') {
|
4958 | if (!hasNamespace) {
|
4959 | hasNamespace = true;
|
4960 | helper = namespaceInteropHelpersByInteropType[moduleInterop];
|
4961 | variableName = namespaceVariableName;
|
4962 | }
|
4963 | }
|
4964 | if (helper) {
|
4965 | addInteropStatement(variableName, helper, name);
|
4966 | }
|
4967 | }
|
4968 | }
|
4969 | }
|
4970 | return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
|
4971 | }
|
4972 |
|
4973 | const builtins$1 = {
|
4974 | assert: true,
|
4975 | buffer: true,
|
4976 | console: true,
|
4977 | constants: true,
|
4978 | domain: true,
|
4979 | events: true,
|
4980 | http: true,
|
4981 | https: true,
|
4982 | os: true,
|
4983 | path: true,
|
4984 | process: true,
|
4985 | punycode: true,
|
4986 | querystring: true,
|
4987 | stream: true,
|
4988 | string_decoder: true,
|
4989 | timers: true,
|
4990 | tty: true,
|
4991 | url: true,
|
4992 | util: true,
|
4993 | vm: true,
|
4994 | zlib: true
|
4995 | };
|
4996 | function warnOnBuiltins(warn, dependencies) {
|
4997 | const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
|
4998 | if (!externalBuiltins.length)
|
4999 | return;
|
5000 | const detail = externalBuiltins.length === 1
|
5001 | ? `module ('${externalBuiltins[0]}')`
|
5002 | : `modules (${externalBuiltins
|
5003 | .slice(0, -1)
|
5004 | .map(name => `'${name}'`)
|
5005 | .join(', ')} and '${externalBuiltins.slice(-1)}')`;
|
5006 | warn({
|
5007 | code: 'MISSING_NODE_BUILTINS',
|
5008 | message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills`,
|
5009 | modules: externalBuiltins
|
5010 | });
|
5011 | }
|
5012 |
|
5013 |
|
5014 |
|
5015 |
|
5016 | function removeExtensionFromRelativeAmdId(id) {
|
5017 | if (id[0] === '.' && id.endsWith('.js')) {
|
5018 | return id.slice(0, -3);
|
5019 | }
|
5020 | return id;
|
5021 | }
|
5022 | function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
|
5023 | warnOnBuiltins(warn, dependencies);
|
5024 | const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
|
5025 | const args = dependencies.map(m => m.name);
|
5026 | const n = compact ? '' : '\n';
|
5027 | const s = compact ? '' : ';';
|
5028 | const _ = compact ? '' : ' ';
|
5029 | if (namedExportsMode && hasExports) {
|
5030 | args.unshift(`exports`);
|
5031 | deps.unshift(`'exports'`);
|
5032 | }
|
5033 | if (accessedGlobals.has('require')) {
|
5034 | args.unshift('require');
|
5035 | deps.unshift(`'require'`);
|
5036 | }
|
5037 | if (accessedGlobals.has('module')) {
|
5038 | args.unshift('module');
|
5039 | deps.unshift(`'module'`);
|
5040 | }
|
5041 | const params = (amdId ? `'${amdId}',${_}` : ``) + (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
|
5042 | const useStrict = strict ? `${_}'use strict';` : '';
|
5043 | magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
|
5044 | const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
|
5045 | let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
|
5046 | if (namespaceMarkers) {
|
5047 | namespaceMarkers = n + n + namespaceMarkers;
|
5048 | }
|
5049 | magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
|
5050 | return magicString
|
5051 | .indent(t)
|
5052 | .prepend(`${amdDefine}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
|
5053 | .append(`${n}${n}});`);
|
5054 | }
|
5055 |
|
5056 | function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
|
5057 | const n = compact ? '' : '\n';
|
5058 | const s = compact ? '' : ';';
|
5059 | const _ = compact ? '' : ' ';
|
5060 | const useStrict = strict ? `'use strict';${n}${n}` : '';
|
5061 | let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
|
5062 | if (namespaceMarkers) {
|
5063 | namespaceMarkers += n + n;
|
5064 | }
|
5065 | const importBlock = getImportBlock(dependencies, compact, varOrConst, n, _);
|
5066 | const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
|
5067 | magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
|
5068 | const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
|
5069 | return magicString.append(`${exportBlock}${outro}`);
|
5070 | }
|
5071 | function getImportBlock(dependencies, compact, varOrConst, n, _) {
|
5072 | let importBlock = '';
|
5073 | let definingVariable = false;
|
5074 | for (const { id, name, reexports, imports } of dependencies) {
|
5075 | if (!reexports && !imports) {
|
5076 | if (importBlock) {
|
5077 | importBlock += !compact || definingVariable ? `;${n}` : ',';
|
5078 | }
|
5079 | definingVariable = false;
|
5080 | importBlock += `require('${id}')`;
|
5081 | }
|
5082 | else {
|
5083 | importBlock +=
|
5084 | compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
|
5085 | definingVariable = true;
|
5086 | importBlock += `${name}${_}=${_}require('${id}')`;
|
5087 | }
|
5088 | }
|
5089 | if (importBlock) {
|
5090 | return `${importBlock};${n}${n}`;
|
5091 | }
|
5092 | return '';
|
5093 | }
|
5094 |
|
5095 | function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
|
5096 | const _ = compact ? '' : ' ';
|
5097 | const n = compact ? '' : '\n';
|
5098 | const importBlock = getImportBlock$1(dependencies, _);
|
5099 | if (importBlock.length > 0)
|
5100 | intro += importBlock.join(n) + n + n;
|
5101 | if (intro)
|
5102 | magicString.prepend(intro);
|
5103 | const exportBlock = getExportBlock$1(exports, _, varOrConst);
|
5104 | if (exportBlock.length)
|
5105 | magicString.append(n + n + exportBlock.join(n).trim());
|
5106 | if (outro)
|
5107 | magicString.append(outro);
|
5108 | return magicString.trim();
|
5109 | }
|
5110 | function getImportBlock$1(dependencies, _) {
|
5111 | const importBlock = [];
|
5112 | for (const { id, reexports, imports, name } of dependencies) {
|
5113 | if (!reexports && !imports) {
|
5114 | importBlock.push(`import${_}'${id}';`);
|
5115 | continue;
|
5116 | }
|
5117 | if (imports) {
|
5118 | let defaultImport = null;
|
5119 | let starImport = null;
|
5120 | const importedNames = [];
|
5121 | for (const specifier of imports) {
|
5122 | if (specifier.imported === 'default') {
|
5123 | defaultImport = specifier;
|
5124 | }
|
5125 | else if (specifier.imported === '*') {
|
5126 | starImport = specifier;
|
5127 | }
|
5128 | else {
|
5129 | importedNames.push(specifier);
|
5130 | }
|
5131 | }
|
5132 | if (starImport) {
|
5133 | importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
|
5134 | }
|
5135 | if (defaultImport && importedNames.length === 0) {
|
5136 | importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
|
5137 | }
|
5138 | else if (importedNames.length > 0) {
|
5139 | importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
|
5140 | .map(specifier => {
|
5141 | if (specifier.imported === specifier.local) {
|
5142 | return specifier.imported;
|
5143 | }
|
5144 | else {
|
5145 | return `${specifier.imported} as ${specifier.local}`;
|
5146 | }
|
5147 | })
|
5148 | .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
|
5149 | }
|
5150 | }
|
5151 | if (reexports) {
|
5152 | let starExport = null;
|
5153 | const namespaceReexports = [];
|
5154 | const namedReexports = [];
|
5155 | for (const specifier of reexports) {
|
5156 | if (specifier.reexported === '*') {
|
5157 | starExport = specifier;
|
5158 | }
|
5159 | else if (specifier.imported === '*') {
|
5160 | namespaceReexports.push(specifier);
|
5161 | }
|
5162 | else {
|
5163 | namedReexports.push(specifier);
|
5164 | }
|
5165 | }
|
5166 | if (starExport) {
|
5167 | importBlock.push(`export${_}*${_}from${_}'${id}';`);
|
5168 | }
|
5169 | if (namespaceReexports.length > 0) {
|
5170 | if (!imports ||
|
5171 | !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
|
5172 | importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
|
5173 | }
|
5174 | for (const specifier of namespaceReexports) {
|
5175 | importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
|
5176 | }
|
5177 | }
|
5178 | if (namedReexports.length > 0) {
|
5179 | importBlock.push(`export${_}{${_}${namedReexports
|
5180 | .map(specifier => {
|
5181 | if (specifier.imported === specifier.reexported) {
|
5182 | return specifier.imported;
|
5183 | }
|
5184 | else {
|
5185 | return `${specifier.imported} as ${specifier.reexported}`;
|
5186 | }
|
5187 | })
|
5188 | .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
|
5189 | }
|
5190 | }
|
5191 | }
|
5192 | return importBlock;
|
5193 | }
|
5194 | function getExportBlock$1(exports, _, varOrConst) {
|
5195 | const exportBlock = [];
|
5196 | const exportDeclaration = [];
|
5197 | for (const specifier of exports) {
|
5198 | if (specifier.exported === 'default') {
|
5199 | exportBlock.push(`export default ${specifier.local};`);
|
5200 | }
|
5201 | else {
|
5202 | if (specifier.expression) {
|
5203 | exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
|
5204 | }
|
5205 | exportDeclaration.push(specifier.exported === specifier.local
|
5206 | ? specifier.local
|
5207 | : `${specifier.local} as ${specifier.exported}`);
|
5208 | }
|
5209 | }
|
5210 | if (exportDeclaration.length) {
|
5211 | exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
|
5212 | }
|
5213 | return exportBlock;
|
5214 | }
|
5215 |
|
5216 | function spaces(i) {
|
5217 | let result = '';
|
5218 | while (i--)
|
5219 | result += ' ';
|
5220 | return result;
|
5221 | }
|
5222 | function tabsToSpaces(str) {
|
5223 | return str.replace(/^\t+/, match => match.split('\t').join(' '));
|
5224 | }
|
5225 | function getCodeFrame(source, line, column) {
|
5226 | let lines = source.split('\n');
|
5227 | const frameStart = Math.max(0, line - 3);
|
5228 | let frameEnd = Math.min(line + 2, lines.length);
|
5229 | lines = lines.slice(frameStart, frameEnd);
|
5230 | while (!/\S/.test(lines[lines.length - 1])) {
|
5231 | lines.pop();
|
5232 | frameEnd -= 1;
|
5233 | }
|
5234 | const digits = String(frameEnd).length;
|
5235 | return lines
|
5236 | .map((str, i) => {
|
5237 | const isErrorLine = frameStart + i + 1 === line;
|
5238 | let lineNum = String(i + frameStart + 1);
|
5239 | while (lineNum.length < digits)
|
5240 | lineNum = ` ${lineNum}`;
|
5241 | if (isErrorLine) {
|
5242 | const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
|
5243 | return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
|
5244 | }
|
5245 | return `${lineNum}: ${tabsToSpaces(str)}`;
|
5246 | })
|
5247 | .join('\n');
|
5248 | }
|
5249 |
|
5250 | function error(base) {
|
5251 | if (!(base instanceof Error))
|
5252 | base = Object.assign(new Error(base.message), base);
|
5253 | throw base;
|
5254 | }
|
5255 | function augmentCodeLocation(props, pos, source, id) {
|
5256 | if (typeof pos === 'object') {
|
5257 | const { line, column } = pos;
|
5258 | props.loc = { file: id, line, column };
|
5259 | }
|
5260 | else {
|
5261 | props.pos = pos;
|
5262 | const { line, column } = locate(source, pos, { offsetLine: 1 });
|
5263 | props.loc = { file: id, line, column };
|
5264 | }
|
5265 | if (props.frame === undefined) {
|
5266 | const { line, column } = props.loc;
|
5267 | props.frame = getCodeFrame(source, line, column);
|
5268 | }
|
5269 | }
|
5270 | var Errors;
|
5271 | (function (Errors) {
|
5272 | Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
|
5273 | Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
|
5274 | Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
|
5275 | Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
|
5276 | Errors["BAD_LOADER"] = "BAD_LOADER";
|
5277 | Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
|
5278 | Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
|
5279 | Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
|
5280 | Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
|
5281 | Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
|
5282 | Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
|
5283 | Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
|
5284 | Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
|
5285 | Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
|
5286 | Errors["INVALID_OPTION"] = "INVALID_OPTION";
|
5287 | Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
|
5288 | Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
|
5289 | Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
|
5290 | Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
|
5291 | Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
|
5292 | Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
|
5293 | Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
|
5294 | Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
|
5295 | Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
|
5296 | Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
|
5297 | Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
|
5298 | Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
|
5299 | Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
|
5300 | Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
|
5301 | })(Errors || (Errors = {}));
|
5302 | function errAssetNotFinalisedForFileName(name) {
|
5303 | return {
|
5304 | code: Errors.ASSET_NOT_FINALISED,
|
5305 | message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
|
5306 | };
|
5307 | }
|
5308 | function errCannotEmitFromOptionsHook() {
|
5309 | return {
|
5310 | code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
|
5311 | message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
|
5312 | };
|
5313 | }
|
5314 | function errChunkNotGeneratedForFileName(name) {
|
5315 | return {
|
5316 | code: Errors.CHUNK_NOT_GENERATED,
|
5317 | message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
|
5318 | };
|
5319 | }
|
5320 | function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
|
5321 | return {
|
5322 | code: Errors.ASSET_NOT_FOUND,
|
5323 | message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
|
5324 | };
|
5325 | }
|
5326 | function errAssetSourceAlreadySet(name) {
|
5327 | return {
|
5328 | code: Errors.ASSET_SOURCE_ALREADY_SET,
|
5329 | message: `Unable to set the source for asset "${name}", source already set.`
|
5330 | };
|
5331 | }
|
5332 | function errNoAssetSourceSet(assetName) {
|
5333 | return {
|
5334 | code: Errors.ASSET_SOURCE_MISSING,
|
5335 | message: `Plugin error creating asset "${assetName}" - no asset source set.`
|
5336 | };
|
5337 | }
|
5338 | function errBadLoader(id) {
|
5339 | return {
|
5340 | code: Errors.BAD_LOADER,
|
5341 | message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
|
5342 | };
|
5343 | }
|
5344 | function errDeprecation(deprecation) {
|
5345 | return {
|
5346 | code: Errors.DEPRECATED_FEATURE,
|
5347 | ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
|
5348 | };
|
5349 | }
|
5350 | function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
|
5351 | return {
|
5352 | code: Errors.FILE_NOT_FOUND,
|
5353 | message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
|
5354 | };
|
5355 | }
|
5356 | function errFileNameConflict(fileName) {
|
5357 | return {
|
5358 | code: Errors.FILE_NAME_CONFLICT,
|
5359 | message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
|
5360 | };
|
5361 | }
|
5362 | function errInputHookInOutputPlugin(pluginName, hookName) {
|
5363 | return {
|
5364 | code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
|
5365 | 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.`
|
5366 | };
|
5367 | }
|
5368 | function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
|
5369 | return {
|
5370 | code: Errors.INVALID_CHUNK,
|
5371 | message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
|
5372 | };
|
5373 | }
|
5374 | function errInvalidExportOptionValue(optionValue) {
|
5375 | return {
|
5376 | code: Errors.INVALID_EXPORT_OPTION,
|
5377 | message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
|
5378 | url: `https://rollupjs.org/guide/en/#outputexports`
|
5379 | };
|
5380 | }
|
5381 | function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
|
5382 | return {
|
5383 | code: 'INVALID_EXPORT_OPTION',
|
5384 | message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
|
5385 | };
|
5386 | }
|
5387 | function errInternalIdCannotBeExternal(source, importer) {
|
5388 | return {
|
5389 | code: Errors.INVALID_EXTERNAL_ID,
|
5390 | message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
|
5391 | };
|
5392 | }
|
5393 | function errInvalidOption(option, explanation) {
|
5394 | return {
|
5395 | code: Errors.INVALID_OPTION,
|
5396 | message: `Invalid value for option "${option}" - ${explanation}.`
|
5397 | };
|
5398 | }
|
5399 | function errInvalidRollupPhaseForAddWatchFile() {
|
5400 | return {
|
5401 | code: Errors.INVALID_ROLLUP_PHASE,
|
5402 | message: `Cannot call addWatchFile after the build has finished.`
|
5403 | };
|
5404 | }
|
5405 | function errInvalidRollupPhaseForChunkEmission() {
|
5406 | return {
|
5407 | code: Errors.INVALID_ROLLUP_PHASE,
|
5408 | message: `Cannot emit chunks after module loading has finished.`
|
5409 | };
|
5410 | }
|
5411 | function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
|
5412 | return {
|
5413 | code: Errors.MISSING_IMPLICIT_DEPENDANT,
|
5414 | message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
|
5415 | };
|
5416 | }
|
5417 | function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
|
5418 | return {
|
5419 | code: Errors.MISSING_IMPLICIT_DEPENDANT,
|
5420 | message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
|
5421 | };
|
5422 | }
|
5423 | function errImplicitDependantIsNotIncluded(module) {
|
5424 | const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
|
5425 | return {
|
5426 | code: Errors.MISSING_IMPLICIT_DEPENDANT,
|
5427 | message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
|
5428 | ? implicitDependencies[0]
|
5429 | : `${implicitDependencies.slice(0, -1).join('", "')}" and "${implicitDependencies.slice(-1)[0]}`}" 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.`
|
5430 | };
|
5431 | }
|
5432 | function errMixedExport(facadeModuleId, name) {
|
5433 | return {
|
5434 | code: Errors.MIXED_EXPORTS,
|
5435 | id: facadeModuleId,
|
5436 | 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`,
|
5437 | url: `https://rollupjs.org/guide/en/#outputexports`
|
5438 | };
|
5439 | }
|
5440 | function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
|
5441 | return {
|
5442 | code: Errors.NAMESPACE_CONFLICT,
|
5443 | message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
|
5444 | name,
|
5445 | reexporter: reexportingModule.id,
|
5446 | sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
|
5447 | };
|
5448 | }
|
5449 | function errNoTransformMapOrAstWithoutCode(pluginName) {
|
5450 | return {
|
5451 | code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
|
5452 | message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
|
5453 | 'a "code". This will be ignored.'
|
5454 | };
|
5455 | }
|
5456 | function errPreferNamedExports(facadeModuleId) {
|
5457 | const file = relativeId(facadeModuleId);
|
5458 | return {
|
5459 | code: Errors.PREFER_NAMED_EXPORTS,
|
5460 | id: facadeModuleId,
|
5461 | 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.`,
|
5462 | url: `https://rollupjs.org/guide/en/#outputexports`
|
5463 | };
|
5464 | }
|
5465 | function errUnexpectedNamedImport(id, imported, isReexport) {
|
5466 | const importType = isReexport ? 'reexport' : 'import';
|
5467 | return {
|
5468 | code: Errors.UNEXPECTED_NAMED_IMPORT,
|
5469 | id,
|
5470 | 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.`,
|
5471 | url: 'https://rollupjs.org/guide/en/#outputinterop'
|
5472 | };
|
5473 | }
|
5474 | function errUnexpectedNamespaceReexport(id) {
|
5475 | return {
|
5476 | code: Errors.UNEXPECTED_NAMED_IMPORT,
|
5477 | id,
|
5478 | 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.`,
|
5479 | url: 'https://rollupjs.org/guide/en/#outputinterop'
|
5480 | };
|
5481 | }
|
5482 | function errEntryCannotBeExternal(unresolvedId) {
|
5483 | return {
|
5484 | code: Errors.UNRESOLVED_ENTRY,
|
5485 | message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
|
5486 | };
|
5487 | }
|
5488 | function errUnresolvedEntry(unresolvedId) {
|
5489 | return {
|
5490 | code: Errors.UNRESOLVED_ENTRY,
|
5491 | message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
|
5492 | };
|
5493 | }
|
5494 | function errUnresolvedImport(source, importer) {
|
5495 | return {
|
5496 | code: Errors.UNRESOLVED_IMPORT,
|
5497 | message: `Could not resolve '${source}' from ${relativeId(importer)}`
|
5498 | };
|
5499 | }
|
5500 | function errUnresolvedImportTreatedAsExternal(source, importer) {
|
5501 | return {
|
5502 | code: Errors.UNRESOLVED_IMPORT,
|
5503 | importer: relativeId(importer),
|
5504 | message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
|
5505 | source,
|
5506 | url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
|
5507 | };
|
5508 | }
|
5509 | function errExternalSyntheticExports(source, importer) {
|
5510 | return {
|
5511 | code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
|
5512 | importer: relativeId(importer),
|
5513 | message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
|
5514 | source
|
5515 | };
|
5516 | }
|
5517 | function errFailedValidation(message) {
|
5518 | return {
|
5519 | code: Errors.VALIDATION_ERROR,
|
5520 | message
|
5521 | };
|
5522 | }
|
5523 | function warnDeprecation(deprecation, activeDeprecation, options) {
|
5524 | warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
|
5525 | }
|
5526 | function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
|
5527 | if (activeDeprecation || strictDeprecations) {
|
5528 | const warning = errDeprecation(deprecation);
|
5529 | if (strictDeprecations) {
|
5530 | return error(warning);
|
5531 | }
|
5532 | warn(warning);
|
5533 | }
|
5534 | }
|
5535 |
|
5536 |
|
5537 |
|
5538 | const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
|
5539 | function property(prop) {
|
5540 | return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
|
5541 | }
|
5542 | function keypath(keypath) {
|
5543 | return keypath
|
5544 | .split('.')
|
5545 | .map(property)
|
5546 | .join('');
|
5547 | }
|
5548 |
|
5549 | function setupNamespace(name, root, globals, compact) {
|
5550 | const _ = compact ? '' : ' ';
|
5551 | const parts = name.split('.');
|
5552 | parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
|
5553 | parts.pop();
|
5554 | let acc = root;
|
5555 | return (parts
|
5556 | .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
|
5557 | .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
|
5558 | }
|
5559 | function assignToDeepVariable(deepName, root, globals, compact, assignment) {
|
5560 | const _ = compact ? '' : ' ';
|
5561 | const parts = deepName.split('.');
|
5562 | parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
|
5563 | const last = parts.pop();
|
5564 | let acc = root;
|
5565 | let deepAssignment = parts
|
5566 | .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
|
5567 | .concat(`${acc}${property(last)}`)
|
5568 | .join(`,${_}`)
|
5569 | .concat(`${_}=${_}${assignment}`);
|
5570 | if (parts.length > 0) {
|
5571 | deepAssignment = `(${deepAssignment})`;
|
5572 | }
|
5573 | return deepAssignment;
|
5574 | }
|
5575 |
|
5576 | function trimEmptyImports(dependencies) {
|
5577 | let i = dependencies.length;
|
5578 | while (i--) {
|
5579 | const { imports, reexports } = dependencies[i];
|
5580 | if (imports || reexports) {
|
5581 | return dependencies.slice(0, i + 1);
|
5582 | }
|
5583 | }
|
5584 | return [];
|
5585 | }
|
5586 |
|
5587 | const thisProp = (name) => `this${keypath(name)}`;
|
5588 | function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
|
5589 | const _ = compact ? '' : ' ';
|
5590 | const s = compact ? '' : ';';
|
5591 | const n = compact ? '' : '\n';
|
5592 | const isNamespaced = name && name.indexOf('.') !== -1;
|
5593 | const useVariableAssignment = !extend && !isNamespaced;
|
5594 | if (name && useVariableAssignment && !isLegal(name)) {
|
5595 | return error({
|
5596 | code: 'ILLEGAL_IDENTIFIER_AS_NAME',
|
5597 | message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
|
5598 | });
|
5599 | }
|
5600 | warnOnBuiltins(warn, dependencies);
|
5601 | const external = trimEmptyImports(dependencies);
|
5602 | const deps = external.map(dep => dep.globalName || 'null');
|
5603 | const args = external.map(m => m.name);
|
5604 | if (hasExports && !name) {
|
5605 | warn({
|
5606 | code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
|
5607 | message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
|
5608 | });
|
5609 | }
|
5610 | if (namedExportsMode && hasExports) {
|
5611 | if (extend) {
|
5612 | deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
|
5613 | args.unshift('exports');
|
5614 | }
|
5615 | else {
|
5616 | deps.unshift('{}');
|
5617 | args.unshift('exports');
|
5618 | }
|
5619 | }
|
5620 | const useStrict = strict ? `${t}'use strict';${n}` : '';
|
5621 | const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
|
5622 | magicString.prepend(`${intro}${interopBlock}`);
|
5623 | let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
|
5624 | if (hasExports) {
|
5625 | if (name && !(extend && namedExportsMode)) {
|
5626 | wrapperIntro =
|
5627 | (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
|
5628 | `${_}=${_}${wrapperIntro}`;
|
5629 | }
|
5630 | if (isNamespaced) {
|
5631 | wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
|
5632 | }
|
5633 | }
|
5634 | let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
|
5635 | if (hasExports && !extend && namedExportsMode) {
|
5636 | wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
|
5637 | }
|
5638 | const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
|
5639 | let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
|
5640 | if (namespaceMarkers) {
|
5641 | namespaceMarkers = n + n + namespaceMarkers;
|
5642 | }
|
5643 | magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
|
5644 | return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
|
5645 | }
|
5646 |
|
5647 | function getStarExcludes({ dependencies, exports }) {
|
5648 | const starExcludes = new Set(exports.map(expt => expt.exported));
|
5649 | if (!starExcludes.has('default'))
|
5650 | starExcludes.add('default');
|
5651 |
|
5652 | for (const { reexports } of dependencies) {
|
5653 | if (reexports) {
|
5654 | for (const reexport of reexports) {
|
5655 | if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
|
5656 | starExcludes.add(reexport.reexported);
|
5657 | }
|
5658 | }
|
5659 | }
|
5660 | return starExcludes;
|
5661 | }
|
5662 | const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
|
5663 | ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
|
5664 | .map(prop => `${prop}:${_}1`)
|
5665 | .join(`,${_}`)}${_}};`
|
5666 | : '';
|
5667 | const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
|
5668 | function getExportsBlock(exports, _, t, n) {
|
5669 | if (exports.length === 0) {
|
5670 | return '';
|
5671 | }
|
5672 | if (exports.length === 1) {
|
5673 | return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
|
5674 | }
|
5675 | return (`${t}${t}${t}exports({${n}` +
|
5676 | exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
|
5677 | `${n}${t}${t}${t}});${n}${n}`);
|
5678 | }
|
5679 | const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
|
5680 | .filter(expt => expt.hoisted || expt.uninitialized)
|
5681 | .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
|
5682 | const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
|
5683 | .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
|
5684 | .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
|
5685 | const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
|
5686 | .filter(expt => expt.expression)
|
5687 | .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
|
5688 | function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
|
5689 | const n = options.compact ? '' : '\n';
|
5690 | const _ = options.compact ? '' : ' ';
|
5691 | const dependencyIds = dependencies.map(m => `'${m.id}'`);
|
5692 | const importBindings = [];
|
5693 | let starExcludes;
|
5694 | const setters = [];
|
5695 | for (const { imports, reexports } of dependencies) {
|
5696 | const setter = [];
|
5697 | if (imports) {
|
5698 | for (const specifier of imports) {
|
5699 | importBindings.push(specifier.local);
|
5700 | if (specifier.imported === '*') {
|
5701 | setter.push(`${specifier.local}${_}=${_}module;`);
|
5702 | }
|
5703 | else {
|
5704 | setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
|
5705 | }
|
5706 | }
|
5707 | }
|
5708 | if (reexports) {
|
5709 | let createdSetter = false;
|
5710 |
|
5711 | if (reexports.length > 1 ||
|
5712 | (reexports.length === 1 &&
|
5713 | (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
|
5714 |
|
5715 | for (const specifier of reexports) {
|
5716 | if (specifier.reexported !== '*')
|
5717 | continue;
|
5718 |
|
5719 | if (!starExcludes) {
|
5720 | starExcludes = getStarExcludes({ dependencies, exports });
|
5721 | }
|
5722 | if (!createdSetter) {
|
5723 | setter.push(`${varOrConst} _setter${_}=${_}{};`);
|
5724 | createdSetter = true;
|
5725 | }
|
5726 | setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
|
5727 | setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
|
5728 | setter.push('}');
|
5729 | }
|
5730 |
|
5731 | for (const specifier of reexports) {
|
5732 | if (specifier.imported !== '*' || specifier.reexported === '*')
|
5733 | continue;
|
5734 | setter.push(`exports('${specifier.reexported}',${_}module);`);
|
5735 | }
|
5736 |
|
5737 | for (const specifier of reexports) {
|
5738 | if (specifier.reexported === '*' || specifier.imported === '*')
|
5739 | continue;
|
5740 | if (!createdSetter) {
|
5741 | setter.push(`${varOrConst} _setter${_}=${_}{};`);
|
5742 | createdSetter = true;
|
5743 | }
|
5744 | setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
|
5745 | }
|
5746 | if (createdSetter) {
|
5747 | setter.push('exports(_setter);');
|
5748 | }
|
5749 | }
|
5750 | else {
|
5751 |
|
5752 | for (const specifier of reexports) {
|
5753 | setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
|
5754 | }
|
5755 | }
|
5756 | }
|
5757 | setters.push(setter.join(`${n}${t}${t}${t}`));
|
5758 | }
|
5759 | const registeredName = options.name ? `'${options.name}',${_}` : '';
|
5760 | const wrapperParams = accessedGlobals.has('module')
|
5761 | ? `exports,${_}module`
|
5762 | : hasExports
|
5763 | ? 'exports'
|
5764 | : '';
|
5765 | let wrapperStart = `System.register(${registeredName}[` +
|
5766 | dependencyIds.join(`,${_}`) +
|
5767 | `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
|
5768 | getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
|
5769 | getImportBindingsBlock(importBindings, _, t, n) +
|
5770 | `${n}${t}return${_}{${setters.length
|
5771 | ? `${n}${t}${t}setters:${_}[${setters
|
5772 | .map(s => s
|
5773 | ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
|
5774 | : options.systemNullSetters
|
5775 | ? `null`
|
5776 | : `function${_}()${_}{}`)
|
5777 | .join(`,${_}`)}],`
|
5778 | : ''}${n}`;
|
5779 | wrapperStart +=
|
5780 | `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
|
5781 | getHoistedExportsBlock(exports, _, t, n);
|
5782 | const wrapperEnd = `${n}${n}` +
|
5783 | getSyntheticExportsBlock(exports, _, t, n) +
|
5784 | getMissingExportsBlock(exports, _, t, n) +
|
5785 | `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
|
5786 | if (intro)
|
5787 | magicString.prepend(intro);
|
5788 | if (outro)
|
5789 | magicString.append(outro);
|
5790 | return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
|
5791 | }
|
5792 |
|
5793 | function globalProp(name, globalVar) {
|
5794 | if (!name)
|
5795 | return 'null';
|
5796 | return `${globalVar}${keypath(name)}`;
|
5797 | }
|
5798 | function safeAccess(name, globalVar, _) {
|
5799 | const parts = name.split('.');
|
5800 | let acc = globalVar;
|
5801 | return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
|
5802 | }
|
5803 | function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
|
5804 | const _ = compact ? '' : ' ';
|
5805 | const n = compact ? '' : '\n';
|
5806 | const s = compact ? '' : ';';
|
5807 | const factoryVar = compact ? 'f' : 'factory';
|
5808 | const globalVar = compact ? 'g' : 'global';
|
5809 | if (hasExports && !name) {
|
5810 | return error({
|
5811 | code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
|
5812 | message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
|
5813 | });
|
5814 | }
|
5815 | warnOnBuiltins(warn, dependencies);
|
5816 | const amdDeps = dependencies.map(m => `'${m.id}'`);
|
5817 | const cjsDeps = dependencies.map(m => `require('${m.id}')`);
|
5818 | const trimmedImports = trimEmptyImports(dependencies);
|
5819 | const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
|
5820 | const factoryArgs = trimmedImports.map(m => m.name);
|
5821 | if (namedExportsMode && (hasExports || noConflict)) {
|
5822 | amdDeps.unshift(`'exports'`);
|
5823 | cjsDeps.unshift(`exports`);
|
5824 | globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
|
5825 | factoryArgs.unshift('exports');
|
5826 | }
|
5827 | const amdParams = (amdId ? `'${amdId}',${_}` : ``) + (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
|
5828 | const define = amdDefine;
|
5829 | const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
|
5830 | const useStrict = strict ? `${_}'use strict';${n}` : ``;
|
5831 | let iifeExport;
|
5832 | if (noConflict) {
|
5833 | const noConflictExportsVar = compact ? 'e' : 'exports';
|
5834 | let factory;
|
5835 | if (!namedExportsMode && hasExports) {
|
5836 | factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
|
5837 | }
|
5838 | else {
|
5839 | const module = globalDeps.shift();
|
5840 | factory =
|
5841 | `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
|
5842 | `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
|
5843 | }
|
5844 | iifeExport =
|
5845 | `(function${_}()${_}{${n}` +
|
5846 | `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
|
5847 | `${t}${t}${factory}${n}` +
|
5848 | `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
|
5849 | `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
|
5850 | `${t}}())`;
|
5851 | }
|
5852 | else {
|
5853 | iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
|
5854 | if (!namedExportsMode && hasExports) {
|
5855 | iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
|
5856 | }
|
5857 | }
|
5858 | const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
|
5859 | const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
|
5860 | const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
|
5861 | const iifeStart = iifeNeedsGlobal
|
5862 | ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
|
5863 | : '';
|
5864 | const iifeEnd = iifeNeedsGlobal ? ')' : '';
|
5865 | const cjsIntro = iifeNeedsGlobal
|
5866 | ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
|
5867 | `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
|
5868 | : '';
|
5869 |
|
5870 | const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
|
5871 | cjsIntro +
|
5872 | `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
|
5873 | `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
|
5874 | `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
|
5875 | const wrapperOutro = n + n + '})));';
|
5876 | magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
|
5877 | const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
|
5878 | let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
|
5879 | if (namespaceMarkers) {
|
5880 | namespaceMarkers = n + n + namespaceMarkers;
|
5881 | }
|
5882 | magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
|
5883 | return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
|
5884 | }
|
5885 |
|
5886 | var finalisers = { system, amd, cjs, es, iife, umd };
|
5887 |
|
5888 | const extractors = {
|
5889 | ArrayPattern(names, param) {
|
5890 | for (const element of param.elements) {
|
5891 | if (element)
|
5892 | extractors[element.type](names, element);
|
5893 | }
|
5894 | },
|
5895 | AssignmentPattern(names, param) {
|
5896 | extractors[param.left.type](names, param.left);
|
5897 | },
|
5898 | Identifier(names, param) {
|
5899 | names.push(param.name);
|
5900 | },
|
5901 | MemberExpression() { },
|
5902 | ObjectPattern(names, param) {
|
5903 | for (const prop of param.properties) {
|
5904 | if (prop.type === 'RestElement') {
|
5905 | extractors.RestElement(names, prop);
|
5906 | }
|
5907 | else {
|
5908 | extractors[prop.value.type](names, prop.value);
|
5909 | }
|
5910 | }
|
5911 | },
|
5912 | RestElement(names, param) {
|
5913 | extractors[param.argument.type](names, param.argument);
|
5914 | }
|
5915 | };
|
5916 | const extractAssignedNames = function extractAssignedNames(param) {
|
5917 | const names = [];
|
5918 | extractors[param.type](names, param);
|
5919 | return names;
|
5920 | };
|
5921 |
|
5922 | class ExportAllDeclaration extends NodeBase {
|
5923 | hasEffects() {
|
5924 | return false;
|
5925 | }
|
5926 | initialise() {
|
5927 | this.context.addExport(this);
|
5928 | }
|
5929 | render(code, _options, nodeRenderOptions) {
|
5930 | code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
|
5931 | }
|
5932 | }
|
5933 | ExportAllDeclaration.prototype.needsBoundaries = true;
|
5934 |
|
5935 | class ArrayExpression extends NodeBase {
|
5936 | bind() {
|
5937 | super.bind();
|
5938 | for (const element of this.elements) {
|
5939 | if (element !== null)
|
5940 | element.deoptimizePath(UNKNOWN_PATH);
|
5941 | }
|
5942 | }
|
5943 | getReturnExpressionWhenCalledAtPath(path) {
|
5944 | if (path.length !== 1)
|
5945 | return UNKNOWN_EXPRESSION;
|
5946 | return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
|
5947 | }
|
5948 | hasEffectsWhenAccessedAtPath(path) {
|
5949 | return path.length > 1;
|
5950 | }
|
5951 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
5952 | if (path.length === 1) {
|
5953 | return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
|
5954 | }
|
5955 | return true;
|
5956 | }
|
5957 | }
|
5958 |
|
5959 | class ArrayPattern extends NodeBase {
|
5960 | addExportedVariables(variables, exportNamesByVariable) {
|
5961 | for (const element of this.elements) {
|
5962 | if (element !== null) {
|
5963 | element.addExportedVariables(variables, exportNamesByVariable);
|
5964 | }
|
5965 | }
|
5966 | }
|
5967 | declare(kind) {
|
5968 | const variables = [];
|
5969 | for (const element of this.elements) {
|
5970 | if (element !== null) {
|
5971 | variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
|
5972 | }
|
5973 | }
|
5974 | return variables;
|
5975 | }
|
5976 | deoptimizePath(path) {
|
5977 | if (path.length === 0) {
|
5978 | for (const element of this.elements) {
|
5979 | if (element !== null) {
|
5980 | element.deoptimizePath(path);
|
5981 | }
|
5982 | }
|
5983 | }
|
5984 | }
|
5985 | hasEffectsWhenAssignedAtPath(path, context) {
|
5986 | if (path.length > 0)
|
5987 | return true;
|
5988 | for (const element of this.elements) {
|
5989 | if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
|
5990 | return true;
|
5991 | }
|
5992 | return false;
|
5993 | }
|
5994 | }
|
5995 |
|
5996 | class BlockScope extends ChildScope {
|
5997 | addDeclaration(identifier, context, init, isHoisted) {
|
5998 | if (isHoisted) {
|
5999 | return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
|
6000 | }
|
6001 | else {
|
6002 | return super.addDeclaration(identifier, context, init, false);
|
6003 | }
|
6004 | }
|
6005 | }
|
6006 |
|
6007 | class ExpressionStatement$1 extends NodeBase {
|
6008 | initialise() {
|
6009 | if (this.directive &&
|
6010 | this.directive !== 'use strict' &&
|
6011 | this.parent.type === Program) {
|
6012 | this.context.warn(
|
6013 |
|
6014 | {
|
6015 | code: 'MODULE_LEVEL_DIRECTIVE',
|
6016 | message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
|
6017 | }, this.start);
|
6018 | }
|
6019 | }
|
6020 | render(code, options) {
|
6021 | super.render(code, options);
|
6022 | if (this.included)
|
6023 | this.insertSemicolon(code);
|
6024 | }
|
6025 | shouldBeIncluded(context) {
|
6026 | if (this.directive && this.directive !== 'use strict')
|
6027 | return this.parent.type !== Program;
|
6028 | return super.shouldBeIncluded(context);
|
6029 | }
|
6030 | }
|
6031 |
|
6032 | class BlockStatement$1 extends NodeBase {
|
6033 | constructor() {
|
6034 | super(...arguments);
|
6035 | this.directlyIncluded = false;
|
6036 | }
|
6037 | addImplicitReturnExpressionToScope() {
|
6038 | const lastStatement = this.body[this.body.length - 1];
|
6039 | if (!lastStatement || lastStatement.type !== ReturnStatement) {
|
6040 | this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
|
6041 | }
|
6042 | }
|
6043 | createScope(parentScope) {
|
6044 | this.scope = this.parent.preventChildBlockScope
|
6045 | ? parentScope
|
6046 | : new BlockScope(parentScope);
|
6047 | }
|
6048 | hasEffects(context) {
|
6049 | if (this.deoptimizeBody)
|
6050 | return true;
|
6051 | for (const node of this.body) {
|
6052 | if (node.hasEffects(context))
|
6053 | return true;
|
6054 | if (context.brokenFlow)
|
6055 | break;
|
6056 | }
|
6057 | return false;
|
6058 | }
|
6059 | include(context, includeChildrenRecursively) {
|
6060 | if (!this.deoptimizeBody || !this.directlyIncluded) {
|
6061 | this.included = true;
|
6062 | this.directlyIncluded = true;
|
6063 | if (this.deoptimizeBody)
|
6064 | includeChildrenRecursively = true;
|
6065 | for (const node of this.body) {
|
6066 | if (includeChildrenRecursively || node.shouldBeIncluded(context))
|
6067 | node.include(context, includeChildrenRecursively);
|
6068 | }
|
6069 | }
|
6070 | }
|
6071 | initialise() {
|
6072 | const firstBodyStatement = this.body[0];
|
6073 | this.deoptimizeBody =
|
6074 | firstBodyStatement instanceof ExpressionStatement$1 &&
|
6075 | firstBodyStatement.directive === 'use asm';
|
6076 | }
|
6077 | render(code, options) {
|
6078 | if (this.body.length) {
|
6079 | renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
|
6080 | }
|
6081 | else {
|
6082 | super.render(code, options);
|
6083 | }
|
6084 | }
|
6085 | }
|
6086 |
|
6087 | class ArrowFunctionExpression$1 extends NodeBase {
|
6088 | createScope(parentScope) {
|
6089 | this.scope = new ReturnValueScope(parentScope, this.context);
|
6090 | }
|
6091 | deoptimizePath(path) {
|
6092 |
|
6093 |
|
6094 | if (path.length === 1 && path[0] === UnknownKey) {
|
6095 | this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
|
6096 | }
|
6097 | }
|
6098 | getReturnExpressionWhenCalledAtPath(path) {
|
6099 | return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
|
6100 | }
|
6101 | hasEffects() {
|
6102 | return false;
|
6103 | }
|
6104 | hasEffectsWhenAccessedAtPath(path) {
|
6105 | return path.length > 1;
|
6106 | }
|
6107 | hasEffectsWhenAssignedAtPath(path) {
|
6108 | return path.length > 1;
|
6109 | }
|
6110 | hasEffectsWhenCalledAtPath(path, _callOptions, context) {
|
6111 | if (path.length > 0)
|
6112 | return true;
|
6113 | for (const param of this.params) {
|
6114 | if (param.hasEffects(context))
|
6115 | return true;
|
6116 | }
|
6117 | const { ignore, brokenFlow } = context;
|
6118 | context.ignore = {
|
6119 | breaks: false,
|
6120 | continues: false,
|
6121 | labels: new Set(),
|
6122 | returnAwaitYield: true
|
6123 | };
|
6124 | if (this.body.hasEffects(context))
|
6125 | return true;
|
6126 | context.ignore = ignore;
|
6127 | context.brokenFlow = brokenFlow;
|
6128 | return false;
|
6129 | }
|
6130 | include(context, includeChildrenRecursively) {
|
6131 | this.included = true;
|
6132 | for (const param of this.params) {
|
6133 | if (!(param instanceof Identifier$1)) {
|
6134 | param.include(context, includeChildrenRecursively);
|
6135 | }
|
6136 | }
|
6137 | const { brokenFlow } = context;
|
6138 | context.brokenFlow = BROKEN_FLOW_NONE;
|
6139 | this.body.include(context, includeChildrenRecursively);
|
6140 | context.brokenFlow = brokenFlow;
|
6141 | }
|
6142 | includeCallArguments(context, args) {
|
6143 | this.scope.includeCallArguments(context, args);
|
6144 | }
|
6145 | initialise() {
|
6146 | this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
|
6147 | if (this.body instanceof BlockStatement$1) {
|
6148 | this.body.addImplicitReturnExpressionToScope();
|
6149 | }
|
6150 | else {
|
6151 | this.scope.addReturnExpression(this.body);
|
6152 | }
|
6153 | }
|
6154 | parseNode(esTreeNode) {
|
6155 | if (esTreeNode.body.type === BlockStatement) {
|
6156 | this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
|
6157 | }
|
6158 | super.parseNode(esTreeNode);
|
6159 | }
|
6160 | }
|
6161 | ArrowFunctionExpression$1.prototype.preventChildBlockScope = true;
|
6162 |
|
6163 | class AssignmentExpression extends NodeBase {
|
6164 | constructor() {
|
6165 | super(...arguments);
|
6166 | this.deoptimized = false;
|
6167 | }
|
6168 | hasEffects(context) {
|
6169 | if (!this.deoptimized)
|
6170 | this.applyDeoptimizations();
|
6171 | return (this.right.hasEffects(context) ||
|
6172 | this.left.hasEffects(context) ||
|
6173 | this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
|
6174 | }
|
6175 | hasEffectsWhenAccessedAtPath(path, context) {
|
6176 | return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
|
6177 | }
|
6178 | include(context, includeChildrenRecursively) {
|
6179 | if (!this.deoptimized)
|
6180 | this.applyDeoptimizations();
|
6181 | this.included = true;
|
6182 | this.left.include(context, includeChildrenRecursively);
|
6183 | this.right.include(context, includeChildrenRecursively);
|
6184 | }
|
6185 | render(code, options) {
|
6186 | this.left.render(code, options);
|
6187 | this.right.render(code, options);
|
6188 | if (options.format === 'system') {
|
6189 | const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
|
6190 | if (this.left.type === 'Identifier' && exportNames) {
|
6191 | const _ = options.compact ? '' : ' ';
|
6192 | const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
|
6193 | const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
|
6194 | code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
|
6195 | ? `exports('${exportNames[0]}',${_}`
|
6196 | : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
|
6197 | code.appendLeft(this.right.end, ')');
|
6198 | }
|
6199 | else {
|
6200 | const systemPatternExports = [];
|
6201 | this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
|
6202 | if (systemPatternExports.length > 0) {
|
6203 | code.prependRight(this.start, getSystemExportFunctionLeft(systemPatternExports, true, options));
|
6204 | code.appendLeft(this.end, ')');
|
6205 | }
|
6206 | }
|
6207 | }
|
6208 | }
|
6209 | applyDeoptimizations() {
|
6210 | this.deoptimized = true;
|
6211 | this.left.deoptimizePath(EMPTY_PATH);
|
6212 | this.right.deoptimizePath(UNKNOWN_PATH);
|
6213 | }
|
6214 | }
|
6215 |
|
6216 | class AssignmentPattern extends NodeBase {
|
6217 | addExportedVariables(variables, exportNamesByVariable) {
|
6218 | this.left.addExportedVariables(variables, exportNamesByVariable);
|
6219 | }
|
6220 | bind() {
|
6221 | super.bind();
|
6222 | this.left.deoptimizePath(EMPTY_PATH);
|
6223 | this.right.deoptimizePath(UNKNOWN_PATH);
|
6224 | }
|
6225 | declare(kind, init) {
|
6226 | return this.left.declare(kind, init);
|
6227 | }
|
6228 | deoptimizePath(path) {
|
6229 | path.length === 0 && this.left.deoptimizePath(path);
|
6230 | }
|
6231 | hasEffectsWhenAssignedAtPath(path, context) {
|
6232 | return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
|
6233 | }
|
6234 | render(code, options, { isShorthandProperty } = BLANK) {
|
6235 | this.left.render(code, options, { isShorthandProperty });
|
6236 | this.right.render(code, options);
|
6237 | }
|
6238 | }
|
6239 |
|
6240 | class AwaitExpression extends NodeBase {
|
6241 | hasEffects(context) {
|
6242 | return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
|
6243 | }
|
6244 | include(context, includeChildrenRecursively) {
|
6245 | if (!this.included) {
|
6246 | this.included = true;
|
6247 | checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
|
6248 | let parent = this.parent;
|
6249 | do {
|
6250 | if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression$1)
|
6251 | break checkTopLevelAwait;
|
6252 | } while ((parent = parent.parent));
|
6253 | this.context.usesTopLevelAwait = true;
|
6254 | }
|
6255 | }
|
6256 | this.argument.include(context, includeChildrenRecursively);
|
6257 | }
|
6258 | }
|
6259 |
|
6260 | const binaryOperators = {
|
6261 | '!=': (left, right) => left != right,
|
6262 | '!==': (left, right) => left !== right,
|
6263 | '%': (left, right) => left % right,
|
6264 | '&': (left, right) => left & right,
|
6265 | '*': (left, right) => left * right,
|
6266 |
|
6267 | '**': (left, right) => left ** right,
|
6268 | '+': (left, right) => left + right,
|
6269 | '-': (left, right) => left - right,
|
6270 | '/': (left, right) => left / right,
|
6271 | '<': (left, right) => left < right,
|
6272 | '<<': (left, right) => left << right,
|
6273 | '<=': (left, right) => left <= right,
|
6274 | '==': (left, right) => left == right,
|
6275 | '===': (left, right) => left === right,
|
6276 | '>': (left, right) => left > right,
|
6277 | '>=': (left, right) => left >= right,
|
6278 | '>>': (left, right) => left >> right,
|
6279 | '>>>': (left, right) => left >>> right,
|
6280 | '^': (left, right) => left ^ right,
|
6281 | in: () => UnknownValue,
|
6282 | instanceof: () => UnknownValue,
|
6283 | '|': (left, right) => left | right
|
6284 | };
|
6285 | class BinaryExpression extends NodeBase {
|
6286 | deoptimizeCache() { }
|
6287 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
6288 | if (path.length > 0)
|
6289 | return UnknownValue;
|
6290 | const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
6291 | if (leftValue === UnknownValue)
|
6292 | return UnknownValue;
|
6293 | const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
6294 | if (rightValue === UnknownValue)
|
6295 | return UnknownValue;
|
6296 | const operatorFn = binaryOperators[this.operator];
|
6297 | if (!operatorFn)
|
6298 | return UnknownValue;
|
6299 | return operatorFn(leftValue, rightValue);
|
6300 | }
|
6301 | hasEffects(context) {
|
6302 |
|
6303 | if (this.operator === '+' &&
|
6304 | this.parent instanceof ExpressionStatement$1 &&
|
6305 | this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
|
6306 | return true;
|
6307 | return super.hasEffects(context);
|
6308 | }
|
6309 | hasEffectsWhenAccessedAtPath(path) {
|
6310 | return path.length > 1;
|
6311 | }
|
6312 | }
|
6313 |
|
6314 | class BreakStatement extends NodeBase {
|
6315 | hasEffects(context) {
|
6316 | if (this.label) {
|
6317 | if (!context.ignore.labels.has(this.label.name))
|
6318 | return true;
|
6319 | context.includedLabels.add(this.label.name);
|
6320 | context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
|
6321 | }
|
6322 | else {
|
6323 | if (!context.ignore.breaks)
|
6324 | return true;
|
6325 | context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
|
6326 | }
|
6327 | return false;
|
6328 | }
|
6329 | include(context) {
|
6330 | this.included = true;
|
6331 | if (this.label) {
|
6332 | this.label.include();
|
6333 | context.includedLabels.add(this.label.name);
|
6334 | }
|
6335 | context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
|
6336 | }
|
6337 | }
|
6338 |
|
6339 | class Literal extends NodeBase {
|
6340 | getLiteralValueAtPath(path) {
|
6341 | if (path.length > 0 ||
|
6342 |
|
6343 | (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
|
6344 | typeof this.value === 'bigint' ||
|
6345 |
|
6346 | this.context.code.charCodeAt(this.start) === 47) {
|
6347 | return UnknownValue;
|
6348 | }
|
6349 | return this.value;
|
6350 | }
|
6351 | getReturnExpressionWhenCalledAtPath(path) {
|
6352 | if (path.length !== 1)
|
6353 | return UNKNOWN_EXPRESSION;
|
6354 | return getMemberReturnExpressionWhenCalled(this.members, path[0]);
|
6355 | }
|
6356 | hasEffectsWhenAccessedAtPath(path) {
|
6357 | if (this.value === null) {
|
6358 | return path.length > 0;
|
6359 | }
|
6360 | return path.length > 1;
|
6361 | }
|
6362 | hasEffectsWhenAssignedAtPath(path) {
|
6363 | return path.length > 0;
|
6364 | }
|
6365 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6366 | if (path.length === 1) {
|
6367 | return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
|
6368 | }
|
6369 | return true;
|
6370 | }
|
6371 | initialise() {
|
6372 | this.members = getLiteralMembersForValue(this.value);
|
6373 | }
|
6374 | parseNode(esTreeNode) {
|
6375 | this.value = esTreeNode.value;
|
6376 | this.regex = esTreeNode.regex;
|
6377 | super.parseNode(esTreeNode);
|
6378 | }
|
6379 | render(code) {
|
6380 | if (typeof this.value === 'string') {
|
6381 | code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
|
6382 | }
|
6383 | }
|
6384 | }
|
6385 |
|
6386 | function getResolvablePropertyKey(memberExpression) {
|
6387 | return memberExpression.computed
|
6388 | ? getResolvableComputedPropertyKey(memberExpression.property)
|
6389 | : memberExpression.property.name;
|
6390 | }
|
6391 | function getResolvableComputedPropertyKey(propertyKey) {
|
6392 | if (propertyKey instanceof Literal) {
|
6393 | return String(propertyKey.value);
|
6394 | }
|
6395 | return null;
|
6396 | }
|
6397 | function getPathIfNotComputed(memberExpression) {
|
6398 | const nextPathKey = memberExpression.propertyKey;
|
6399 | const object = memberExpression.object;
|
6400 | if (typeof nextPathKey === 'string') {
|
6401 | if (object instanceof Identifier$1) {
|
6402 | return [
|
6403 | { key: object.name, pos: object.start },
|
6404 | { key: nextPathKey, pos: memberExpression.property.start }
|
6405 | ];
|
6406 | }
|
6407 | if (object instanceof MemberExpression) {
|
6408 | const parentPath = getPathIfNotComputed(object);
|
6409 | return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
|
6410 | }
|
6411 | }
|
6412 | return null;
|
6413 | }
|
6414 | function getStringFromPath(path) {
|
6415 | let pathString = path[0].key;
|
6416 | for (let index = 1; index < path.length; index++) {
|
6417 | pathString += '.' + path[index].key;
|
6418 | }
|
6419 | return pathString;
|
6420 | }
|
6421 | class MemberExpression extends NodeBase {
|
6422 | constructor() {
|
6423 | super(...arguments);
|
6424 | this.variable = null;
|
6425 | this.bound = false;
|
6426 | this.expressionsToBeDeoptimized = [];
|
6427 | this.replacement = null;
|
6428 | this.wasPathDeoptimizedWhileOptimized = false;
|
6429 | }
|
6430 | addExportedVariables() { }
|
6431 | bind() {
|
6432 | if (this.bound)
|
6433 | return;
|
6434 | this.bound = true;
|
6435 | const path = getPathIfNotComputed(this);
|
6436 | const baseVariable = path && this.scope.findVariable(path[0].key);
|
6437 | if (baseVariable && baseVariable.isNamespace) {
|
6438 | const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
|
6439 | if (!resolvedVariable) {
|
6440 | super.bind();
|
6441 | }
|
6442 | else if (typeof resolvedVariable === 'string') {
|
6443 | this.replacement = resolvedVariable;
|
6444 | }
|
6445 | else {
|
6446 | if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
|
6447 | resolvedVariable.module.suggestName(path[0].key);
|
6448 | }
|
6449 | this.variable = resolvedVariable;
|
6450 | this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
|
6451 | }
|
6452 | }
|
6453 | else {
|
6454 | super.bind();
|
6455 |
|
6456 | this.getPropertyKey();
|
6457 | }
|
6458 | }
|
6459 | deoptimizeCache() {
|
6460 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
|
6461 | this.expressionsToBeDeoptimized = [];
|
6462 | this.propertyKey = UnknownKey;
|
6463 | if (this.wasPathDeoptimizedWhileOptimized) {
|
6464 | this.object.deoptimizePath(UNKNOWN_PATH);
|
6465 | }
|
6466 | for (const expression of expressionsToBeDeoptimized) {
|
6467 | expression.deoptimizeCache();
|
6468 | }
|
6469 | }
|
6470 | deoptimizePath(path) {
|
6471 | if (!this.bound)
|
6472 | this.bind();
|
6473 | if (path.length === 0)
|
6474 | this.disallowNamespaceReassignment();
|
6475 | if (this.variable) {
|
6476 | this.variable.deoptimizePath(path);
|
6477 | }
|
6478 | else {
|
6479 | const propertyKey = this.getPropertyKey();
|
6480 | if (propertyKey === UnknownKey) {
|
6481 | this.object.deoptimizePath(UNKNOWN_PATH);
|
6482 | }
|
6483 | else {
|
6484 | this.wasPathDeoptimizedWhileOptimized = true;
|
6485 | this.object.deoptimizePath([propertyKey, ...path]);
|
6486 | }
|
6487 | }
|
6488 | }
|
6489 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
6490 | if (!this.bound)
|
6491 | this.bind();
|
6492 | if (this.variable !== null) {
|
6493 | return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
|
6494 | }
|
6495 | this.expressionsToBeDeoptimized.push(origin);
|
6496 | return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
|
6497 | }
|
6498 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
6499 | if (!this.bound)
|
6500 | this.bind();
|
6501 | if (this.variable !== null) {
|
6502 | return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
6503 | }
|
6504 | this.expressionsToBeDeoptimized.push(origin);
|
6505 | return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
|
6506 | }
|
6507 | hasEffects(context) {
|
6508 | return (this.property.hasEffects(context) ||
|
6509 | this.object.hasEffects(context) ||
|
6510 | (this.context.options.treeshake.propertyReadSideEffects &&
|
6511 | this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
|
6512 | }
|
6513 | hasEffectsWhenAccessedAtPath(path, context) {
|
6514 | if (path.length === 0)
|
6515 | return false;
|
6516 | if (this.variable !== null) {
|
6517 | return this.variable.hasEffectsWhenAccessedAtPath(path, context);
|
6518 | }
|
6519 | return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
|
6520 | }
|
6521 | hasEffectsWhenAssignedAtPath(path, context) {
|
6522 | if (this.variable !== null) {
|
6523 | return this.variable.hasEffectsWhenAssignedAtPath(path, context);
|
6524 | }
|
6525 | return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
|
6526 | }
|
6527 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6528 | if (this.variable !== null) {
|
6529 | return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
6530 | }
|
6531 | return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
|
6532 | }
|
6533 | include(context, includeChildrenRecursively) {
|
6534 | if (!this.included) {
|
6535 | this.included = true;
|
6536 | if (this.variable !== null) {
|
6537 | this.context.includeVariable(this.variable);
|
6538 | }
|
6539 | }
|
6540 | this.object.include(context, includeChildrenRecursively);
|
6541 | this.property.include(context, includeChildrenRecursively);
|
6542 | }
|
6543 | includeCallArguments(context, args) {
|
6544 | if (this.variable) {
|
6545 | this.variable.includeCallArguments(context, args);
|
6546 | }
|
6547 | else {
|
6548 | super.includeCallArguments(context, args);
|
6549 | }
|
6550 | }
|
6551 | initialise() {
|
6552 | this.propertyKey = getResolvablePropertyKey(this);
|
6553 | }
|
6554 | render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
|
6555 | const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
|
6556 | if (this.variable || this.replacement) {
|
6557 | let replacement = this.variable ? this.variable.getName() : this.replacement;
|
6558 | if (isCalleeOfDifferentParent)
|
6559 | replacement = '0, ' + replacement;
|
6560 | code.overwrite(this.start, this.end, replacement, {
|
6561 | contentOnly: true,
|
6562 | storeName: true
|
6563 | });
|
6564 | }
|
6565 | else {
|
6566 | if (isCalleeOfDifferentParent) {
|
6567 | code.appendRight(this.start, '0, ');
|
6568 | }
|
6569 | super.render(code, options);
|
6570 | }
|
6571 | }
|
6572 | disallowNamespaceReassignment() {
|
6573 | if (this.object instanceof Identifier$1) {
|
6574 | const variable = this.scope.findVariable(this.object.name);
|
6575 | if (variable.isNamespace) {
|
6576 | if (this.variable) {
|
6577 | this.context.includeVariable(this.variable);
|
6578 | }
|
6579 | this.context.warn({
|
6580 | code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
|
6581 | message: `Illegal reassignment to import '${this.object.name}'`
|
6582 | }, this.start);
|
6583 | }
|
6584 | }
|
6585 | }
|
6586 | getPropertyKey() {
|
6587 | if (this.propertyKey === null) {
|
6588 | this.propertyKey = UnknownKey;
|
6589 | const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
|
6590 | return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
|
6591 | }
|
6592 | return this.propertyKey;
|
6593 | }
|
6594 | resolveNamespaceVariables(baseVariable, path) {
|
6595 | if (path.length === 0)
|
6596 | return baseVariable;
|
6597 | if (!baseVariable.isNamespace)
|
6598 | return null;
|
6599 | const exportName = path[0].key;
|
6600 | const variable = baseVariable instanceof ExternalVariable
|
6601 | ? baseVariable.module.getVariableForExportName(exportName)
|
6602 | : baseVariable.context.traceExport(exportName);
|
6603 | if (!variable) {
|
6604 | const fileName = baseVariable instanceof ExternalVariable
|
6605 | ? baseVariable.module.id
|
6606 | : baseVariable.context.fileName;
|
6607 | this.context.warn({
|
6608 | code: 'MISSING_EXPORT',
|
6609 | exporter: relativeId(fileName),
|
6610 | importer: relativeId(this.context.fileName),
|
6611 | message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
|
6612 | missing: exportName,
|
6613 | url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
|
6614 | }, path[0].pos);
|
6615 | return 'undefined';
|
6616 | }
|
6617 | return this.resolveNamespaceVariables(variable, path.slice(1));
|
6618 | }
|
6619 | }
|
6620 |
|
6621 | class CallExpression$1 extends NodeBase {
|
6622 | constructor() {
|
6623 | super(...arguments);
|
6624 | this.expressionsToBeDeoptimized = [];
|
6625 | this.returnExpression = null;
|
6626 | this.wasPathDeoptmizedWhileOptimized = false;
|
6627 | }
|
6628 | bind() {
|
6629 | super.bind();
|
6630 | if (this.callee instanceof Identifier$1) {
|
6631 | const variable = this.scope.findVariable(this.callee.name);
|
6632 | if (variable.isNamespace) {
|
6633 | this.context.warn({
|
6634 | code: 'CANNOT_CALL_NAMESPACE',
|
6635 | message: `Cannot call a namespace ('${this.callee.name}')`
|
6636 | }, this.start);
|
6637 | }
|
6638 | if (this.callee.name === 'eval') {
|
6639 | this.context.warn({
|
6640 | code: 'EVAL',
|
6641 | message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
|
6642 | url: 'https://rollupjs.org/guide/en/#avoiding-eval'
|
6643 | }, this.start);
|
6644 | }
|
6645 | }
|
6646 |
|
6647 | this.getReturnExpression(SHARED_RECURSION_TRACKER);
|
6648 |
|
6649 | if (this.callee instanceof MemberExpression && !this.callee.variable) {
|
6650 | this.callee.object.deoptimizePath(UNKNOWN_PATH);
|
6651 | }
|
6652 | for (const argument of this.arguments) {
|
6653 |
|
6654 | argument.deoptimizePath(UNKNOWN_PATH);
|
6655 | }
|
6656 | }
|
6657 | deoptimizeCache() {
|
6658 | if (this.returnExpression !== UNKNOWN_EXPRESSION) {
|
6659 | this.returnExpression = null;
|
6660 | const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
|
6661 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
|
6662 | if (returnExpression !== UNKNOWN_EXPRESSION) {
|
6663 |
|
6664 |
|
6665 | this.expressionsToBeDeoptimized = [];
|
6666 | if (this.wasPathDeoptmizedWhileOptimized) {
|
6667 | returnExpression.deoptimizePath(UNKNOWN_PATH);
|
6668 | this.wasPathDeoptmizedWhileOptimized = false;
|
6669 | }
|
6670 | }
|
6671 | for (const expression of expressionsToBeDeoptimized) {
|
6672 | expression.deoptimizeCache();
|
6673 | }
|
6674 | }
|
6675 | }
|
6676 | deoptimizePath(path) {
|
6677 | if (path.length === 0)
|
6678 | return;
|
6679 | const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
|
6680 | if (trackedEntities.has(this))
|
6681 | return;
|
6682 | trackedEntities.add(this);
|
6683 | const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
|
6684 | if (returnExpression !== UNKNOWN_EXPRESSION) {
|
6685 | this.wasPathDeoptmizedWhileOptimized = true;
|
6686 | returnExpression.deoptimizePath(path);
|
6687 | }
|
6688 | }
|
6689 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
6690 | const returnExpression = this.getReturnExpression(recursionTracker);
|
6691 | if (returnExpression === UNKNOWN_EXPRESSION) {
|
6692 | return UnknownValue;
|
6693 | }
|
6694 | const trackedEntities = recursionTracker.getEntities(path);
|
6695 | if (trackedEntities.has(returnExpression)) {
|
6696 | return UnknownValue;
|
6697 | }
|
6698 | this.expressionsToBeDeoptimized.push(origin);
|
6699 | trackedEntities.add(returnExpression);
|
6700 | const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
|
6701 | trackedEntities.delete(returnExpression);
|
6702 | return value;
|
6703 | }
|
6704 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
6705 | const returnExpression = this.getReturnExpression(recursionTracker);
|
6706 | if (this.returnExpression === UNKNOWN_EXPRESSION) {
|
6707 | return UNKNOWN_EXPRESSION;
|
6708 | }
|
6709 | const trackedEntities = recursionTracker.getEntities(path);
|
6710 | if (trackedEntities.has(returnExpression)) {
|
6711 | return UNKNOWN_EXPRESSION;
|
6712 | }
|
6713 | this.expressionsToBeDeoptimized.push(origin);
|
6714 | trackedEntities.add(returnExpression);
|
6715 | const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
6716 | trackedEntities.delete(returnExpression);
|
6717 | return value;
|
6718 | }
|
6719 | hasEffects(context) {
|
6720 | for (const argument of this.arguments) {
|
6721 | if (argument.hasEffects(context))
|
6722 | return true;
|
6723 | }
|
6724 | if (this.context.options.treeshake.annotations &&
|
6725 | this.annotatedPure)
|
6726 | return false;
|
6727 | return (this.callee.hasEffects(context) ||
|
6728 | this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
|
6729 | }
|
6730 | hasEffectsWhenAccessedAtPath(path, context) {
|
6731 | if (path.length === 0)
|
6732 | return false;
|
6733 | const trackedExpressions = context.accessed.getEntities(path);
|
6734 | if (trackedExpressions.has(this))
|
6735 | return false;
|
6736 | trackedExpressions.add(this);
|
6737 | return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
|
6738 | }
|
6739 | hasEffectsWhenAssignedAtPath(path, context) {
|
6740 | if (path.length === 0)
|
6741 | return true;
|
6742 | const trackedExpressions = context.assigned.getEntities(path);
|
6743 | if (trackedExpressions.has(this))
|
6744 | return false;
|
6745 | trackedExpressions.add(this);
|
6746 | return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
|
6747 | }
|
6748 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6749 | const trackedExpressions = (callOptions.withNew
|
6750 | ? context.instantiated
|
6751 | : context.called).getEntities(path, callOptions);
|
6752 | if (trackedExpressions.has(this))
|
6753 | return false;
|
6754 | trackedExpressions.add(this);
|
6755 | return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
6756 | }
|
6757 | include(context, includeChildrenRecursively) {
|
6758 | if (includeChildrenRecursively) {
|
6759 | super.include(context, includeChildrenRecursively);
|
6760 | if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
|
6761 | this.callee instanceof Identifier$1 &&
|
6762 | this.callee.variable) {
|
6763 | this.callee.variable.markCalledFromTryStatement();
|
6764 | }
|
6765 | }
|
6766 | else {
|
6767 | this.included = true;
|
6768 | this.callee.include(context, false);
|
6769 | }
|
6770 | this.callee.includeCallArguments(context, this.arguments);
|
6771 | if (!this.returnExpression.included) {
|
6772 | this.returnExpression.include(context, false);
|
6773 | }
|
6774 | }
|
6775 | initialise() {
|
6776 | this.callOptions = {
|
6777 | args: this.arguments,
|
6778 | withNew: false
|
6779 | };
|
6780 | }
|
6781 | render(code, options, { renderedParentType } = BLANK) {
|
6782 | this.callee.render(code, options);
|
6783 | if (this.arguments.length > 0) {
|
6784 | if (this.arguments[this.arguments.length - 1].included) {
|
6785 | for (const arg of this.arguments) {
|
6786 | arg.render(code, options);
|
6787 | }
|
6788 | }
|
6789 | else {
|
6790 | let lastIncludedIndex = this.arguments.length - 2;
|
6791 | while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
|
6792 | lastIncludedIndex--;
|
6793 | }
|
6794 | if (lastIncludedIndex >= 0) {
|
6795 | for (let index = 0; index <= lastIncludedIndex; index++) {
|
6796 | this.arguments[index].render(code, options);
|
6797 | }
|
6798 | code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
|
6799 | }
|
6800 | else {
|
6801 | code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
|
6802 | }
|
6803 | }
|
6804 | }
|
6805 | if (renderedParentType === ExpressionStatement &&
|
6806 | this.callee.type === FunctionExpression) {
|
6807 | code.appendRight(this.start, '(');
|
6808 | code.prependLeft(this.end, ')');
|
6809 | }
|
6810 | }
|
6811 | getReturnExpression(recursionTracker) {
|
6812 | if (this.returnExpression === null) {
|
6813 | this.returnExpression = UNKNOWN_EXPRESSION;
|
6814 | return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
|
6815 | }
|
6816 | return this.returnExpression;
|
6817 | }
|
6818 | }
|
6819 |
|
6820 | class CatchScope extends ParameterScope {
|
6821 | addDeclaration(identifier, context, init, isHoisted) {
|
6822 | if (isHoisted) {
|
6823 | return this.parent.addDeclaration(identifier, context, init, isHoisted);
|
6824 | }
|
6825 | else {
|
6826 | return super.addDeclaration(identifier, context, init, false);
|
6827 | }
|
6828 | }
|
6829 | }
|
6830 |
|
6831 | class CatchClause extends NodeBase {
|
6832 | createScope(parentScope) {
|
6833 | this.scope = new CatchScope(parentScope, this.context);
|
6834 | }
|
6835 | initialise() {
|
6836 | if (this.param) {
|
6837 | this.param.declare('parameter', UNKNOWN_EXPRESSION);
|
6838 | }
|
6839 | }
|
6840 | parseNode(esTreeNode) {
|
6841 | this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
|
6842 | super.parseNode(esTreeNode);
|
6843 | }
|
6844 | }
|
6845 | CatchClause.prototype.preventChildBlockScope = true;
|
6846 |
|
6847 | class ChainExpression extends NodeBase {
|
6848 | }
|
6849 |
|
6850 | class ClassBodyScope extends ChildScope {
|
6851 | findLexicalBoundary() {
|
6852 | return this;
|
6853 | }
|
6854 | }
|
6855 |
|
6856 | class MethodDefinition extends NodeBase {
|
6857 | hasEffects(context) {
|
6858 | return this.key.hasEffects(context);
|
6859 | }
|
6860 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6861 | return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
|
6862 | }
|
6863 | }
|
6864 |
|
6865 | class ClassBody extends NodeBase {
|
6866 | createScope(parentScope) {
|
6867 | this.scope = new ClassBodyScope(parentScope);
|
6868 | }
|
6869 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6870 | if (path.length > 0)
|
6871 | return true;
|
6872 | return (this.classConstructor !== null &&
|
6873 | this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
|
6874 | }
|
6875 | initialise() {
|
6876 | for (const method of this.body) {
|
6877 | if (method instanceof MethodDefinition && method.kind === 'constructor') {
|
6878 | this.classConstructor = method;
|
6879 | return;
|
6880 | }
|
6881 | }
|
6882 | this.classConstructor = null;
|
6883 | }
|
6884 | }
|
6885 |
|
6886 | class ClassExpression extends ClassNode {
|
6887 | }
|
6888 |
|
6889 | class MultiExpression {
|
6890 | constructor(expressions) {
|
6891 | this.included = false;
|
6892 | this.expressions = expressions;
|
6893 | }
|
6894 | deoptimizePath(path) {
|
6895 | for (const expression of this.expressions) {
|
6896 | expression.deoptimizePath(path);
|
6897 | }
|
6898 | }
|
6899 | getLiteralValueAtPath() {
|
6900 | return UnknownValue;
|
6901 | }
|
6902 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
6903 | return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
|
6904 | }
|
6905 | hasEffectsWhenAccessedAtPath(path, context) {
|
6906 | for (const expression of this.expressions) {
|
6907 | if (expression.hasEffectsWhenAccessedAtPath(path, context))
|
6908 | return true;
|
6909 | }
|
6910 | return false;
|
6911 | }
|
6912 | hasEffectsWhenAssignedAtPath(path, context) {
|
6913 | for (const expression of this.expressions) {
|
6914 | if (expression.hasEffectsWhenAssignedAtPath(path, context))
|
6915 | return true;
|
6916 | }
|
6917 | return false;
|
6918 | }
|
6919 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
6920 | for (const expression of this.expressions) {
|
6921 | if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
|
6922 | return true;
|
6923 | }
|
6924 | return false;
|
6925 | }
|
6926 | include(context, includeChildrenRecursively) {
|
6927 |
|
6928 |
|
6929 | for (const expression of this.expressions) {
|
6930 | if (!expression.included) {
|
6931 | expression.include(context, includeChildrenRecursively);
|
6932 | }
|
6933 | }
|
6934 | }
|
6935 | includeCallArguments() { }
|
6936 | }
|
6937 |
|
6938 | class ConditionalExpression extends NodeBase {
|
6939 | constructor() {
|
6940 | super(...arguments);
|
6941 | this.expressionsToBeDeoptimized = [];
|
6942 | this.isBranchResolutionAnalysed = false;
|
6943 | this.usedBranch = null;
|
6944 | this.wasPathDeoptimizedWhileOptimized = false;
|
6945 | }
|
6946 | bind() {
|
6947 | super.bind();
|
6948 |
|
6949 | this.getUsedBranch();
|
6950 | }
|
6951 | deoptimizeCache() {
|
6952 | if (this.usedBranch !== null) {
|
6953 | const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
|
6954 | this.usedBranch = null;
|
6955 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
|
6956 | this.expressionsToBeDeoptimized = [];
|
6957 | if (this.wasPathDeoptimizedWhileOptimized) {
|
6958 | unusedBranch.deoptimizePath(UNKNOWN_PATH);
|
6959 | }
|
6960 | for (const expression of expressionsToBeDeoptimized) {
|
6961 | expression.deoptimizeCache();
|
6962 | }
|
6963 | }
|
6964 | }
|
6965 | deoptimizePath(path) {
|
6966 | if (path.length > 0) {
|
6967 | const usedBranch = this.getUsedBranch();
|
6968 | if (usedBranch === null) {
|
6969 | this.consequent.deoptimizePath(path);
|
6970 | this.alternate.deoptimizePath(path);
|
6971 | }
|
6972 | else {
|
6973 | this.wasPathDeoptimizedWhileOptimized = true;
|
6974 | usedBranch.deoptimizePath(path);
|
6975 | }
|
6976 | }
|
6977 | }
|
6978 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
6979 | const usedBranch = this.getUsedBranch();
|
6980 | if (usedBranch === null)
|
6981 | return UnknownValue;
|
6982 | this.expressionsToBeDeoptimized.push(origin);
|
6983 | return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
|
6984 | }
|
6985 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
6986 | const usedBranch = this.getUsedBranch();
|
6987 | if (usedBranch === null)
|
6988 | return new MultiExpression([
|
6989 | this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
|
6990 | this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
|
6991 | ]);
|
6992 | this.expressionsToBeDeoptimized.push(origin);
|
6993 | return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
6994 | }
|
6995 | hasEffects(context) {
|
6996 | if (this.test.hasEffects(context))
|
6997 | return true;
|
6998 | if (this.usedBranch === null) {
|
6999 | return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
|
7000 | }
|
7001 | return this.usedBranch.hasEffects(context);
|
7002 | }
|
7003 | hasEffectsWhenAccessedAtPath(path, context) {
|
7004 | if (path.length === 0)
|
7005 | return false;
|
7006 | if (this.usedBranch === null) {
|
7007 | return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
|
7008 | this.alternate.hasEffectsWhenAccessedAtPath(path, context));
|
7009 | }
|
7010 | return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
|
7011 | }
|
7012 | hasEffectsWhenAssignedAtPath(path, context) {
|
7013 | if (path.length === 0)
|
7014 | return true;
|
7015 | if (this.usedBranch === null) {
|
7016 | return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
|
7017 | this.alternate.hasEffectsWhenAssignedAtPath(path, context));
|
7018 | }
|
7019 | return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
|
7020 | }
|
7021 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
7022 | if (this.usedBranch === null) {
|
7023 | return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
|
7024 | this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
|
7025 | }
|
7026 | return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
7027 | }
|
7028 | include(context, includeChildrenRecursively) {
|
7029 | this.included = true;
|
7030 | if (includeChildrenRecursively ||
|
7031 | this.test.shouldBeIncluded(context) ||
|
7032 | this.usedBranch === null) {
|
7033 | this.test.include(context, includeChildrenRecursively);
|
7034 | this.consequent.include(context, includeChildrenRecursively);
|
7035 | this.alternate.include(context, includeChildrenRecursively);
|
7036 | }
|
7037 | else {
|
7038 | this.usedBranch.include(context, includeChildrenRecursively);
|
7039 | }
|
7040 | }
|
7041 | includeCallArguments(context, args) {
|
7042 | if (this.usedBranch === null) {
|
7043 | this.consequent.includeCallArguments(context, args);
|
7044 | this.alternate.includeCallArguments(context, args);
|
7045 | }
|
7046 | else {
|
7047 | this.usedBranch.includeCallArguments(context, args);
|
7048 | }
|
7049 | }
|
7050 | render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
|
7051 | if (!this.test.included) {
|
7052 | const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
|
7053 | const inclusionStart = (this.consequent.included
|
7054 | ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
|
7055 | : colonPos) + 1;
|
7056 | if (preventASI) {
|
7057 | removeLineBreaks(code, inclusionStart, this.usedBranch.start);
|
7058 | }
|
7059 | code.remove(this.start, inclusionStart);
|
7060 | if (this.consequent.included) {
|
7061 | code.remove(colonPos, this.end);
|
7062 | }
|
7063 | removeAnnotations(this, code);
|
7064 | this.usedBranch.render(code, options, {
|
7065 | isCalleeOfRenderedParent: renderedParentType
|
7066 | ? isCalleeOfRenderedParent
|
7067 | : this.parent.callee === this,
|
7068 | preventASI: true,
|
7069 | renderedParentType: renderedParentType || this.parent.type
|
7070 | });
|
7071 | }
|
7072 | else {
|
7073 | super.render(code, options);
|
7074 | }
|
7075 | }
|
7076 | getUsedBranch() {
|
7077 | if (this.isBranchResolutionAnalysed) {
|
7078 | return this.usedBranch;
|
7079 | }
|
7080 | this.isBranchResolutionAnalysed = true;
|
7081 | const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
|
7082 | return testValue === UnknownValue
|
7083 | ? null
|
7084 | : (this.usedBranch = testValue ? this.consequent : this.alternate);
|
7085 | }
|
7086 | }
|
7087 |
|
7088 | class ContinueStatement extends NodeBase {
|
7089 | hasEffects(context) {
|
7090 | if (this.label) {
|
7091 | if (!context.ignore.labels.has(this.label.name))
|
7092 | return true;
|
7093 | context.includedLabels.add(this.label.name);
|
7094 | context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
|
7095 | }
|
7096 | else {
|
7097 | if (!context.ignore.continues)
|
7098 | return true;
|
7099 | context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
|
7100 | }
|
7101 | return false;
|
7102 | }
|
7103 | include(context) {
|
7104 | this.included = true;
|
7105 | if (this.label) {
|
7106 | this.label.include();
|
7107 | context.includedLabels.add(this.label.name);
|
7108 | }
|
7109 | context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
|
7110 | }
|
7111 | }
|
7112 |
|
7113 | class DoWhileStatement extends NodeBase {
|
7114 | hasEffects(context) {
|
7115 | if (this.test.hasEffects(context))
|
7116 | return true;
|
7117 | const { brokenFlow, ignore: { breaks, continues } } = context;
|
7118 | context.ignore.breaks = true;
|
7119 | context.ignore.continues = true;
|
7120 | if (this.body.hasEffects(context))
|
7121 | return true;
|
7122 | context.ignore.breaks = breaks;
|
7123 | context.ignore.continues = continues;
|
7124 | context.brokenFlow = brokenFlow;
|
7125 | return false;
|
7126 | }
|
7127 | include(context, includeChildrenRecursively) {
|
7128 | this.included = true;
|
7129 | this.test.include(context, includeChildrenRecursively);
|
7130 | const { brokenFlow } = context;
|
7131 | this.body.include(context, includeChildrenRecursively);
|
7132 | context.brokenFlow = brokenFlow;
|
7133 | }
|
7134 | }
|
7135 |
|
7136 | class EmptyStatement extends NodeBase {
|
7137 | hasEffects() {
|
7138 | return false;
|
7139 | }
|
7140 | }
|
7141 |
|
7142 | class ExportNamedDeclaration extends NodeBase {
|
7143 | bind() {
|
7144 |
|
7145 | if (this.declaration !== null)
|
7146 | this.declaration.bind();
|
7147 | }
|
7148 | hasEffects(context) {
|
7149 | return this.declaration !== null && this.declaration.hasEffects(context);
|
7150 | }
|
7151 | initialise() {
|
7152 | this.context.addExport(this);
|
7153 | }
|
7154 | render(code, options, nodeRenderOptions) {
|
7155 | const { start, end } = nodeRenderOptions;
|
7156 | if (this.declaration === null) {
|
7157 | code.remove(start, end);
|
7158 | }
|
7159 | else {
|
7160 | code.remove(this.start, this.declaration.start);
|
7161 | this.declaration.render(code, options, { start, end });
|
7162 | }
|
7163 | }
|
7164 | }
|
7165 | ExportNamedDeclaration.prototype.needsBoundaries = true;
|
7166 |
|
7167 | class ExportSpecifier extends NodeBase {
|
7168 | }
|
7169 |
|
7170 | class FieldDefinition extends NodeBase {
|
7171 | hasEffects(context) {
|
7172 | return (this.key.hasEffects(context) ||
|
7173 | (this.static && this.value !== null && this.value.hasEffects(context)));
|
7174 | }
|
7175 | }
|
7176 |
|
7177 | class ForInStatement extends NodeBase {
|
7178 | bind() {
|
7179 | this.left.bind();
|
7180 | this.left.deoptimizePath(EMPTY_PATH);
|
7181 | this.right.bind();
|
7182 | this.body.bind();
|
7183 | }
|
7184 | createScope(parentScope) {
|
7185 | this.scope = new BlockScope(parentScope);
|
7186 | }
|
7187 | hasEffects(context) {
|
7188 | if ((this.left &&
|
7189 | (this.left.hasEffects(context) ||
|
7190 | this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
|
7191 | (this.right && this.right.hasEffects(context)))
|
7192 | return true;
|
7193 | const { brokenFlow, ignore: { breaks, continues } } = context;
|
7194 | context.ignore.breaks = true;
|
7195 | context.ignore.continues = true;
|
7196 | if (this.body.hasEffects(context))
|
7197 | return true;
|
7198 | context.ignore.breaks = breaks;
|
7199 | context.ignore.continues = continues;
|
7200 | context.brokenFlow = brokenFlow;
|
7201 | return false;
|
7202 | }
|
7203 | include(context, includeChildrenRecursively) {
|
7204 | this.included = true;
|
7205 | this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
|
7206 | this.left.deoptimizePath(EMPTY_PATH);
|
7207 | this.right.include(context, includeChildrenRecursively);
|
7208 | const { brokenFlow } = context;
|
7209 | this.body.include(context, includeChildrenRecursively);
|
7210 | context.brokenFlow = brokenFlow;
|
7211 | }
|
7212 | render(code, options) {
|
7213 | this.left.render(code, options, NO_SEMICOLON);
|
7214 | this.right.render(code, options, NO_SEMICOLON);
|
7215 |
|
7216 | if (code.original.charCodeAt(this.right.start - 1) === 110 ) {
|
7217 | code.prependLeft(this.right.start, ' ');
|
7218 | }
|
7219 | this.body.render(code, options);
|
7220 | }
|
7221 | }
|
7222 |
|
7223 | class ForOfStatement extends NodeBase {
|
7224 | bind() {
|
7225 | this.left.bind();
|
7226 | this.left.deoptimizePath(EMPTY_PATH);
|
7227 | this.right.bind();
|
7228 | this.body.bind();
|
7229 | }
|
7230 | createScope(parentScope) {
|
7231 | this.scope = new BlockScope(parentScope);
|
7232 | }
|
7233 | hasEffects() {
|
7234 |
|
7235 | return true;
|
7236 | }
|
7237 | include(context, includeChildrenRecursively) {
|
7238 | this.included = true;
|
7239 | this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
|
7240 | this.left.deoptimizePath(EMPTY_PATH);
|
7241 | this.right.include(context, includeChildrenRecursively);
|
7242 | const { brokenFlow } = context;
|
7243 | this.body.include(context, includeChildrenRecursively);
|
7244 | context.brokenFlow = brokenFlow;
|
7245 | }
|
7246 | render(code, options) {
|
7247 | this.left.render(code, options, NO_SEMICOLON);
|
7248 | this.right.render(code, options, NO_SEMICOLON);
|
7249 |
|
7250 | if (code.original.charCodeAt(this.right.start - 1) === 102 ) {
|
7251 | code.prependLeft(this.right.start, ' ');
|
7252 | }
|
7253 | this.body.render(code, options);
|
7254 | }
|
7255 | }
|
7256 |
|
7257 | class ForStatement extends NodeBase {
|
7258 | createScope(parentScope) {
|
7259 | this.scope = new BlockScope(parentScope);
|
7260 | }
|
7261 | hasEffects(context) {
|
7262 | if ((this.init && this.init.hasEffects(context)) ||
|
7263 | (this.test && this.test.hasEffects(context)) ||
|
7264 | (this.update && this.update.hasEffects(context)))
|
7265 | return true;
|
7266 | const { brokenFlow, ignore: { breaks, continues } } = context;
|
7267 | context.ignore.breaks = true;
|
7268 | context.ignore.continues = true;
|
7269 | if (this.body.hasEffects(context))
|
7270 | return true;
|
7271 | context.ignore.breaks = breaks;
|
7272 | context.ignore.continues = continues;
|
7273 | context.brokenFlow = brokenFlow;
|
7274 | return false;
|
7275 | }
|
7276 | include(context, includeChildrenRecursively) {
|
7277 | this.included = true;
|
7278 | if (this.init)
|
7279 | this.init.include(context, includeChildrenRecursively);
|
7280 | if (this.test)
|
7281 | this.test.include(context, includeChildrenRecursively);
|
7282 | const { brokenFlow } = context;
|
7283 | if (this.update)
|
7284 | this.update.include(context, includeChildrenRecursively);
|
7285 | this.body.include(context, includeChildrenRecursively);
|
7286 | context.brokenFlow = brokenFlow;
|
7287 | }
|
7288 | render(code, options) {
|
7289 | if (this.init)
|
7290 | this.init.render(code, options, NO_SEMICOLON);
|
7291 | if (this.test)
|
7292 | this.test.render(code, options, NO_SEMICOLON);
|
7293 | if (this.update)
|
7294 | this.update.render(code, options, NO_SEMICOLON);
|
7295 | this.body.render(code, options);
|
7296 | }
|
7297 | }
|
7298 |
|
7299 | class FunctionExpression$1 extends FunctionNode {
|
7300 | }
|
7301 |
|
7302 | class TrackingScope extends BlockScope {
|
7303 | constructor() {
|
7304 | super(...arguments);
|
7305 | this.hoistedDeclarations = [];
|
7306 | }
|
7307 | addDeclaration(identifier, context, init, isHoisted) {
|
7308 | this.hoistedDeclarations.push(identifier);
|
7309 | return this.parent.addDeclaration(identifier, context, init, isHoisted);
|
7310 | }
|
7311 | }
|
7312 |
|
7313 | const unset = Symbol('unset');
|
7314 | class IfStatement extends NodeBase {
|
7315 | constructor() {
|
7316 | super(...arguments);
|
7317 | this.testValue = unset;
|
7318 | }
|
7319 | deoptimizeCache() {
|
7320 | this.testValue = UnknownValue;
|
7321 | }
|
7322 | hasEffects(context) {
|
7323 | if (this.test.hasEffects(context)) {
|
7324 | return true;
|
7325 | }
|
7326 | const testValue = this.getTestValue();
|
7327 | if (testValue === UnknownValue) {
|
7328 | const { brokenFlow } = context;
|
7329 | if (this.consequent.hasEffects(context))
|
7330 | return true;
|
7331 | const consequentBrokenFlow = context.brokenFlow;
|
7332 | context.brokenFlow = brokenFlow;
|
7333 | if (this.alternate === null)
|
7334 | return false;
|
7335 | if (this.alternate.hasEffects(context))
|
7336 | return true;
|
7337 | context.brokenFlow =
|
7338 | context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
|
7339 | return false;
|
7340 | }
|
7341 | return testValue
|
7342 | ? this.consequent.hasEffects(context)
|
7343 | : this.alternate !== null && this.alternate.hasEffects(context);
|
7344 | }
|
7345 | include(context, includeChildrenRecursively) {
|
7346 | this.included = true;
|
7347 | if (includeChildrenRecursively) {
|
7348 | this.includeRecursively(includeChildrenRecursively, context);
|
7349 | }
|
7350 | else {
|
7351 | const testValue = this.getTestValue();
|
7352 | if (testValue === UnknownValue) {
|
7353 | this.includeUnknownTest(context);
|
7354 | }
|
7355 | else {
|
7356 | this.includeKnownTest(context, testValue);
|
7357 | }
|
7358 | }
|
7359 | }
|
7360 | parseNode(esTreeNode) {
|
7361 | this.consequentScope = new TrackingScope(this.scope);
|
7362 | this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
|
7363 | this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
|
7364 | if (esTreeNode.alternate) {
|
7365 | this.alternateScope = new TrackingScope(this.scope);
|
7366 | this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
|
7367 | this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
|
7368 | }
|
7369 | super.parseNode(esTreeNode);
|
7370 | }
|
7371 | render(code, options) {
|
7372 |
|
7373 | const testValue = this.getTestValue();
|
7374 | const hoistedDeclarations = [];
|
7375 | const includesIfElse = this.test.included;
|
7376 | const noTreeshake = !this.context.options.treeshake;
|
7377 | if (includesIfElse) {
|
7378 | this.test.render(code, options);
|
7379 | }
|
7380 | else {
|
7381 | removeAnnotations(this, code);
|
7382 | code.remove(this.start, this.consequent.start);
|
7383 | }
|
7384 | if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
|
7385 | this.consequent.render(code, options);
|
7386 | }
|
7387 | else {
|
7388 | code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
|
7389 | hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
|
7390 | }
|
7391 | if (this.alternate) {
|
7392 | if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
|
7393 | if (includesIfElse) {
|
7394 | if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
|
7395 | code.prependLeft(this.alternate.start, ' ');
|
7396 | }
|
7397 | }
|
7398 | else {
|
7399 | code.remove(this.consequent.end, this.alternate.start);
|
7400 | }
|
7401 | this.alternate.render(code, options);
|
7402 | }
|
7403 | else {
|
7404 | if (includesIfElse && this.shouldKeepAlternateBranch()) {
|
7405 | code.overwrite(this.alternate.start, this.end, ';');
|
7406 | }
|
7407 | else {
|
7408 | code.remove(this.consequent.end, this.end);
|
7409 | }
|
7410 | hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
|
7411 | }
|
7412 | }
|
7413 | this.renderHoistedDeclarations(hoistedDeclarations, code);
|
7414 | }
|
7415 | getTestValue() {
|
7416 | if (this.testValue === unset) {
|
7417 | return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
|
7418 | }
|
7419 | return this.testValue;
|
7420 | }
|
7421 | includeKnownTest(context, testValue) {
|
7422 | if (this.test.shouldBeIncluded(context)) {
|
7423 | this.test.include(context, false);
|
7424 | }
|
7425 | if (testValue && this.consequent.shouldBeIncluded(context)) {
|
7426 | this.consequent.include(context, false);
|
7427 | }
|
7428 | if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
|
7429 | this.alternate.include(context, false);
|
7430 | }
|
7431 | }
|
7432 | includeRecursively(includeChildrenRecursively, context) {
|
7433 | this.test.include(context, includeChildrenRecursively);
|
7434 | this.consequent.include(context, includeChildrenRecursively);
|
7435 | if (this.alternate !== null) {
|
7436 | this.alternate.include(context, includeChildrenRecursively);
|
7437 | }
|
7438 | }
|
7439 | includeUnknownTest(context) {
|
7440 | this.test.include(context, false);
|
7441 | const { brokenFlow } = context;
|
7442 | let consequentBrokenFlow = BROKEN_FLOW_NONE;
|
7443 | if (this.consequent.shouldBeIncluded(context)) {
|
7444 | this.consequent.include(context, false);
|
7445 | consequentBrokenFlow = context.brokenFlow;
|
7446 | context.brokenFlow = brokenFlow;
|
7447 | }
|
7448 | if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
|
7449 | this.alternate.include(context, false);
|
7450 | context.brokenFlow =
|
7451 | context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
|
7452 | }
|
7453 | }
|
7454 | renderHoistedDeclarations(hoistedDeclarations, code) {
|
7455 | const hoistedVars = [
|
7456 | ...new Set(hoistedDeclarations.map(identifier => {
|
7457 | const variable = identifier.variable;
|
7458 | return variable.included ? variable.getName() : '';
|
7459 | }))
|
7460 | ]
|
7461 | .filter(Boolean)
|
7462 | .join(', ');
|
7463 | if (hoistedVars) {
|
7464 | const parentType = this.parent.type;
|
7465 | const needsBraces = parentType !== Program && parentType !== BlockStatement;
|
7466 | code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
|
7467 | if (needsBraces) {
|
7468 | code.appendLeft(this.end, ` }`);
|
7469 | }
|
7470 | }
|
7471 | }
|
7472 | shouldKeepAlternateBranch() {
|
7473 | let currentParent = this.parent;
|
7474 | do {
|
7475 | if (currentParent instanceof IfStatement && currentParent.alternate) {
|
7476 | return true;
|
7477 | }
|
7478 | if (currentParent instanceof BlockStatement$1) {
|
7479 | return false;
|
7480 | }
|
7481 | currentParent = currentParent.parent;
|
7482 | } while (currentParent);
|
7483 | return false;
|
7484 | }
|
7485 | }
|
7486 |
|
7487 | class ImportDeclaration extends NodeBase {
|
7488 | bind() { }
|
7489 | hasEffects() {
|
7490 | return false;
|
7491 | }
|
7492 | initialise() {
|
7493 | this.context.addImport(this);
|
7494 | }
|
7495 | render(code, _options, nodeRenderOptions) {
|
7496 | code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
|
7497 | }
|
7498 | }
|
7499 | ImportDeclaration.prototype.needsBoundaries = true;
|
7500 |
|
7501 | class ImportDefaultSpecifier$1 extends NodeBase {
|
7502 | }
|
7503 |
|
7504 | class ImportExpression extends NodeBase {
|
7505 | constructor() {
|
7506 | super(...arguments);
|
7507 | this.inlineNamespace = null;
|
7508 | this.mechanism = null;
|
7509 | this.resolution = null;
|
7510 | }
|
7511 | hasEffects() {
|
7512 | return true;
|
7513 | }
|
7514 | include(context, includeChildrenRecursively) {
|
7515 | if (!this.included) {
|
7516 | this.included = true;
|
7517 | this.context.includeDynamicImport(this);
|
7518 | this.scope.addAccessedDynamicImport(this);
|
7519 | }
|
7520 | this.source.include(context, includeChildrenRecursively);
|
7521 | }
|
7522 | initialise() {
|
7523 | this.context.addDynamicImport(this);
|
7524 | }
|
7525 | render(code, options) {
|
7526 | if (this.inlineNamespace) {
|
7527 | const _ = options.compact ? '' : ' ';
|
7528 | const s = options.compact ? '' : ';';
|
7529 | code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
|
7530 | return;
|
7531 | }
|
7532 | if (this.mechanism) {
|
7533 | code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
|
7534 | code.overwrite(this.end - 1, this.end, this.mechanism.right);
|
7535 | }
|
7536 | this.source.render(code, options);
|
7537 | }
|
7538 | renderFinalResolution(code, resolution, namespaceExportName, options) {
|
7539 | code.overwrite(this.source.start, this.source.end, resolution);
|
7540 | if (namespaceExportName) {
|
7541 | const _ = options.compact ? '' : ' ';
|
7542 | const s = options.compact ? '' : ';';
|
7543 | code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
|
7544 | }
|
7545 | }
|
7546 | setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
|
7547 | this.resolution = resolution;
|
7548 | const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
|
7549 | let helper;
|
7550 | ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
|
7551 | if (helper) {
|
7552 | accessedGlobals.push(helper);
|
7553 | }
|
7554 | if (accessedGlobals.length > 0) {
|
7555 | this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
|
7556 | }
|
7557 | }
|
7558 | setInternalResolution(inlineNamespace) {
|
7559 | this.inlineNamespace = inlineNamespace;
|
7560 | }
|
7561 | getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
|
7562 | const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
|
7563 | {
|
7564 | customResolution: typeof this.resolution === 'string' ? this.resolution : null,
|
7565 | format: options.format,
|
7566 | moduleId: this.context.module.id,
|
7567 | targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
|
7568 | }
|
7569 | ]);
|
7570 | if (mechanism) {
|
7571 | return { helper: null, mechanism };
|
7572 | }
|
7573 | switch (options.format) {
|
7574 | case 'cjs': {
|
7575 | const _ = options.compact ? '' : ' ';
|
7576 | const s = options.compact ? '' : ';';
|
7577 | const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
|
7578 | const helper = this.getInteropHelper(resolution, exportMode, options.interop);
|
7579 | return {
|
7580 | helper,
|
7581 | mechanism: helper
|
7582 | ? {
|
7583 | left: `${leftStart} /*#__PURE__*/${helper}(require(`,
|
7584 | right: `))${s}${_}})`
|
7585 | }
|
7586 | : {
|
7587 | left: `${leftStart} require(`,
|
7588 | right: `)${s}${_}})`
|
7589 | }
|
7590 | };
|
7591 | }
|
7592 | case 'amd': {
|
7593 | const _ = options.compact ? '' : ' ';
|
7594 | const resolve = options.compact ? 'c' : 'resolve';
|
7595 | const reject = options.compact ? 'e' : 'reject';
|
7596 | const helper = this.getInteropHelper(resolution, exportMode, options.interop);
|
7597 | const resolveNamespace = helper
|
7598 | ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
|
7599 | : resolve;
|
7600 | return {
|
7601 | helper,
|
7602 | mechanism: {
|
7603 | left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
|
7604 | right: `],${_}${resolveNamespace},${_}${reject})${_}})`
|
7605 | }
|
7606 | };
|
7607 | }
|
7608 | case 'system':
|
7609 | return {
|
7610 | helper: null,
|
7611 | mechanism: {
|
7612 | left: 'module.import(',
|
7613 | right: ')'
|
7614 | }
|
7615 | };
|
7616 | case 'es':
|
7617 | if (options.dynamicImportFunction) {
|
7618 | return {
|
7619 | helper: null,
|
7620 | mechanism: {
|
7621 | left: `${options.dynamicImportFunction}(`,
|
7622 | right: ')'
|
7623 | }
|
7624 | };
|
7625 | }
|
7626 | }
|
7627 | return { helper: null, mechanism: null };
|
7628 | }
|
7629 | getInteropHelper(resolution, exportMode, interop) {
|
7630 | return exportMode === 'external'
|
7631 | ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
|
7632 | : exportMode === 'default'
|
7633 | ? getDefaultOnlyHelper()
|
7634 | : null;
|
7635 | }
|
7636 | }
|
7637 | const accessedImportGlobals = {
|
7638 | amd: ['require'],
|
7639 | cjs: ['require'],
|
7640 | system: ['module']
|
7641 | };
|
7642 |
|
7643 | class ImportNamespaceSpecifier$1 extends NodeBase {
|
7644 | }
|
7645 |
|
7646 | class ImportSpecifier extends NodeBase {
|
7647 | }
|
7648 |
|
7649 | class LabeledStatement extends NodeBase {
|
7650 | hasEffects(context) {
|
7651 | const brokenFlow = context.brokenFlow;
|
7652 | context.ignore.labels.add(this.label.name);
|
7653 | if (this.body.hasEffects(context))
|
7654 | return true;
|
7655 | context.ignore.labels.delete(this.label.name);
|
7656 | if (context.includedLabels.has(this.label.name)) {
|
7657 | context.includedLabels.delete(this.label.name);
|
7658 | context.brokenFlow = brokenFlow;
|
7659 | }
|
7660 | return false;
|
7661 | }
|
7662 | include(context, includeChildrenRecursively) {
|
7663 | this.included = true;
|
7664 | const brokenFlow = context.brokenFlow;
|
7665 | this.body.include(context, includeChildrenRecursively);
|
7666 | if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
|
7667 | this.label.include();
|
7668 | context.includedLabels.delete(this.label.name);
|
7669 | context.brokenFlow = brokenFlow;
|
7670 | }
|
7671 | }
|
7672 | render(code, options) {
|
7673 | if (this.label.included) {
|
7674 | this.label.render(code, options);
|
7675 | }
|
7676 | else {
|
7677 | code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
|
7678 | }
|
7679 | this.body.render(code, options);
|
7680 | }
|
7681 | }
|
7682 |
|
7683 | class LogicalExpression extends NodeBase {
|
7684 | constructor() {
|
7685 | super(...arguments);
|
7686 |
|
7687 | this.expressionsToBeDeoptimized = [];
|
7688 | this.isBranchResolutionAnalysed = false;
|
7689 | this.unusedBranch = null;
|
7690 | this.usedBranch = null;
|
7691 | this.wasPathDeoptimizedWhileOptimized = false;
|
7692 | }
|
7693 | bind() {
|
7694 | super.bind();
|
7695 |
|
7696 | this.getUsedBranch();
|
7697 | }
|
7698 | deoptimizeCache() {
|
7699 | if (this.usedBranch !== null) {
|
7700 | this.usedBranch = null;
|
7701 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
|
7702 | this.expressionsToBeDeoptimized = [];
|
7703 | if (this.wasPathDeoptimizedWhileOptimized) {
|
7704 | this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
|
7705 | }
|
7706 | for (const expression of expressionsToBeDeoptimized) {
|
7707 | expression.deoptimizeCache();
|
7708 | }
|
7709 | }
|
7710 | }
|
7711 | deoptimizePath(path) {
|
7712 | const usedBranch = this.getUsedBranch();
|
7713 | if (usedBranch === null) {
|
7714 | this.left.deoptimizePath(path);
|
7715 | this.right.deoptimizePath(path);
|
7716 | }
|
7717 | else {
|
7718 | this.wasPathDeoptimizedWhileOptimized = true;
|
7719 | usedBranch.deoptimizePath(path);
|
7720 | }
|
7721 | }
|
7722 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
7723 | const usedBranch = this.getUsedBranch();
|
7724 | if (usedBranch === null)
|
7725 | return UnknownValue;
|
7726 | this.expressionsToBeDeoptimized.push(origin);
|
7727 | return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
|
7728 | }
|
7729 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
7730 | const usedBranch = this.getUsedBranch();
|
7731 | if (usedBranch === null)
|
7732 | return new MultiExpression([
|
7733 | this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
|
7734 | this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
|
7735 | ]);
|
7736 | this.expressionsToBeDeoptimized.push(origin);
|
7737 | return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
7738 | }
|
7739 | hasEffects(context) {
|
7740 | if (this.left.hasEffects(context)) {
|
7741 | return true;
|
7742 | }
|
7743 | if (this.usedBranch !== this.left) {
|
7744 | return this.right.hasEffects(context);
|
7745 | }
|
7746 | return false;
|
7747 | }
|
7748 | hasEffectsWhenAccessedAtPath(path, context) {
|
7749 | if (path.length === 0)
|
7750 | return false;
|
7751 | if (this.usedBranch === null) {
|
7752 | return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
|
7753 | this.right.hasEffectsWhenAccessedAtPath(path, context));
|
7754 | }
|
7755 | return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
|
7756 | }
|
7757 | hasEffectsWhenAssignedAtPath(path, context) {
|
7758 | if (path.length === 0)
|
7759 | return true;
|
7760 | if (this.usedBranch === null) {
|
7761 | return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
|
7762 | this.right.hasEffectsWhenAssignedAtPath(path, context));
|
7763 | }
|
7764 | return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
|
7765 | }
|
7766 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
7767 | if (this.usedBranch === null) {
|
7768 | return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
|
7769 | this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
|
7770 | }
|
7771 | return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
7772 | }
|
7773 | include(context, includeChildrenRecursively) {
|
7774 | this.included = true;
|
7775 | if (includeChildrenRecursively ||
|
7776 | (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
|
7777 | this.usedBranch === null) {
|
7778 | this.left.include(context, includeChildrenRecursively);
|
7779 | this.right.include(context, includeChildrenRecursively);
|
7780 | }
|
7781 | else {
|
7782 | this.usedBranch.include(context, includeChildrenRecursively);
|
7783 | }
|
7784 | }
|
7785 | render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
|
7786 | if (!this.left.included || !this.right.included) {
|
7787 | const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
|
7788 | if (this.right.included) {
|
7789 | code.remove(this.start, operatorPos + 2);
|
7790 | if (preventASI) {
|
7791 | removeLineBreaks(code, operatorPos + 2, this.right.start);
|
7792 | }
|
7793 | }
|
7794 | else {
|
7795 | code.remove(operatorPos, this.end);
|
7796 | }
|
7797 | removeAnnotations(this, code);
|
7798 | this.usedBranch.render(code, options, {
|
7799 | isCalleeOfRenderedParent: renderedParentType
|
7800 | ? isCalleeOfRenderedParent
|
7801 | : this.parent.callee === this,
|
7802 | preventASI,
|
7803 | renderedParentType: renderedParentType || this.parent.type
|
7804 | });
|
7805 | }
|
7806 | else {
|
7807 | this.left.render(code, options, { preventASI });
|
7808 | this.right.render(code, options);
|
7809 | }
|
7810 | }
|
7811 | getUsedBranch() {
|
7812 | if (!this.isBranchResolutionAnalysed) {
|
7813 | this.isBranchResolutionAnalysed = true;
|
7814 | const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
|
7815 | if (leftValue === UnknownValue) {
|
7816 | return null;
|
7817 | }
|
7818 | else {
|
7819 | if ((this.operator === '||' && leftValue) ||
|
7820 | (this.operator === '&&' && !leftValue) ||
|
7821 | (this.operator === '??' && leftValue != null)) {
|
7822 | this.usedBranch = this.left;
|
7823 | this.unusedBranch = this.right;
|
7824 | }
|
7825 | else {
|
7826 | this.usedBranch = this.right;
|
7827 | this.unusedBranch = this.left;
|
7828 | }
|
7829 | }
|
7830 | }
|
7831 | return this.usedBranch;
|
7832 | }
|
7833 | }
|
7834 |
|
7835 | const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
|
7836 | const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
|
7837 | const FILE_PREFIX = 'ROLLUP_FILE_URL_';
|
7838 | class MetaProperty extends NodeBase {
|
7839 | addAccessedGlobals(format, accessedGlobalsByScope) {
|
7840 | const metaProperty = this.metaProperty;
|
7841 | const accessedGlobals = (metaProperty &&
|
7842 | (metaProperty.startsWith(FILE_PREFIX) ||
|
7843 | metaProperty.startsWith(ASSET_PREFIX) ||
|
7844 | metaProperty.startsWith(CHUNK_PREFIX))
|
7845 | ? accessedFileUrlGlobals
|
7846 | : accessedMetaUrlGlobals)[format];
|
7847 | if (accessedGlobals.length > 0) {
|
7848 | this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
|
7849 | }
|
7850 | }
|
7851 | getReferencedFileName(outputPluginDriver) {
|
7852 | const metaProperty = this.metaProperty;
|
7853 | if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
|
7854 | return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
|
7855 | }
|
7856 | return null;
|
7857 | }
|
7858 | hasEffects() {
|
7859 | return false;
|
7860 | }
|
7861 | hasEffectsWhenAccessedAtPath(path) {
|
7862 | return path.length > 1;
|
7863 | }
|
7864 | include() {
|
7865 | if (!this.included) {
|
7866 | this.included = true;
|
7867 | if (this.meta.name === 'import') {
|
7868 | this.context.addImportMeta(this);
|
7869 | const parent = this.parent;
|
7870 | this.metaProperty =
|
7871 | parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
|
7872 | ? parent.propertyKey
|
7873 | : null;
|
7874 | }
|
7875 | }
|
7876 | }
|
7877 | renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
|
7878 | var _a;
|
7879 | const parent = this.parent;
|
7880 | const metaProperty = this.metaProperty;
|
7881 | if (metaProperty &&
|
7882 | (metaProperty.startsWith(FILE_PREFIX) ||
|
7883 | metaProperty.startsWith(ASSET_PREFIX) ||
|
7884 | metaProperty.startsWith(CHUNK_PREFIX))) {
|
7885 | let referenceId = null;
|
7886 | let assetReferenceId = null;
|
7887 | let chunkReferenceId = null;
|
7888 | let fileName;
|
7889 | if (metaProperty.startsWith(FILE_PREFIX)) {
|
7890 | referenceId = metaProperty.substr(FILE_PREFIX.length);
|
7891 | fileName = outputPluginDriver.getFileName(referenceId);
|
7892 | }
|
7893 | else if (metaProperty.startsWith(ASSET_PREFIX)) {
|
7894 | warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
|
7895 | assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
|
7896 | fileName = outputPluginDriver.getFileName(assetReferenceId);
|
7897 | }
|
7898 | else {
|
7899 | warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
|
7900 | chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
|
7901 | fileName = outputPluginDriver.getFileName(chunkReferenceId);
|
7902 | }
|
7903 | const relativePath = normalize(sysPath.relative(sysPath.dirname(chunkId), fileName));
|
7904 | let replacement;
|
7905 | if (assetReferenceId !== null) {
|
7906 | replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
|
7907 | {
|
7908 | assetFileName: fileName,
|
7909 | chunkId,
|
7910 | format,
|
7911 | moduleId: this.context.module.id,
|
7912 | relativeAssetPath: relativePath
|
7913 | }
|
7914 | ]);
|
7915 | }
|
7916 | if (!replacement) {
|
7917 | replacement =
|
7918 | outputPluginDriver.hookFirstSync('resolveFileUrl', [
|
7919 | {
|
7920 | assetReferenceId,
|
7921 | chunkId,
|
7922 | chunkReferenceId,
|
7923 | fileName,
|
7924 | format,
|
7925 | moduleId: this.context.module.id,
|
7926 | referenceId: referenceId || assetReferenceId || chunkReferenceId,
|
7927 | relativePath
|
7928 | }
|
7929 | ]) || relativeUrlMechanisms[format](relativePath);
|
7930 | }
|
7931 | code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
|
7932 | return;
|
7933 | }
|
7934 | const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
|
7935 | metaProperty,
|
7936 | {
|
7937 | chunkId,
|
7938 | format,
|
7939 | moduleId: this.context.module.id
|
7940 | }
|
7941 | ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
|
7942 | if (typeof replacement === 'string') {
|
7943 | if (parent instanceof MemberExpression) {
|
7944 | code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
|
7945 | }
|
7946 | else {
|
7947 | code.overwrite(this.start, this.end, replacement, { contentOnly: true });
|
7948 | }
|
7949 | }
|
7950 | }
|
7951 | }
|
7952 | const accessedMetaUrlGlobals = {
|
7953 | amd: ['document', 'module', 'URL'],
|
7954 | cjs: ['document', 'require', 'URL'],
|
7955 | es: [],
|
7956 | iife: ['document', 'URL'],
|
7957 | system: ['module'],
|
7958 | umd: ['document', 'require', 'URL']
|
7959 | };
|
7960 | const accessedFileUrlGlobals = {
|
7961 | amd: ['document', 'require', 'URL'],
|
7962 | cjs: ['document', 'require', 'URL'],
|
7963 | es: [],
|
7964 | iife: ['document', 'URL'],
|
7965 | system: ['module', 'URL'],
|
7966 | umd: ['document', 'require', 'URL']
|
7967 | };
|
7968 | const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
|
7969 | const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
|
7970 | const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
|
7971 | const urlMechanism = getUrl(chunkId);
|
7972 | return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
|
7973 | };
|
7974 | const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
|
7975 | const relativeUrlMechanisms = {
|
7976 | amd: relativePath => {
|
7977 | if (relativePath[0] !== '.')
|
7978 | relativePath = './' + relativePath;
|
7979 | return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
|
7980 | },
|
7981 | cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
|
7982 | es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
|
7983 | iife: relativePath => getRelativeUrlFromDocument(relativePath),
|
7984 | system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
|
7985 | umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
|
7986 | };
|
7987 | const importMetaMechanisms = {
|
7988 | amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
|
7989 | cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
|
7990 | iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
|
7991 | system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
|
7992 | umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
|
7993 | };
|
7994 |
|
7995 | class NewExpression extends NodeBase {
|
7996 | bind() {
|
7997 | super.bind();
|
7998 | for (const argument of this.arguments) {
|
7999 |
|
8000 | argument.deoptimizePath(UNKNOWN_PATH);
|
8001 | }
|
8002 | }
|
8003 | hasEffects(context) {
|
8004 | for (const argument of this.arguments) {
|
8005 | if (argument.hasEffects(context))
|
8006 | return true;
|
8007 | }
|
8008 | if (this.context.options.treeshake.annotations &&
|
8009 | this.annotatedPure)
|
8010 | return false;
|
8011 | return (this.callee.hasEffects(context) ||
|
8012 | this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
|
8013 | }
|
8014 | hasEffectsWhenAccessedAtPath(path) {
|
8015 | return path.length > 1;
|
8016 | }
|
8017 | initialise() {
|
8018 | this.callOptions = {
|
8019 | args: this.arguments,
|
8020 | withNew: true
|
8021 | };
|
8022 | }
|
8023 | }
|
8024 |
|
8025 | class ObjectExpression extends NodeBase {
|
8026 | constructor() {
|
8027 | super(...arguments);
|
8028 | this.deoptimizedPaths = new Set();
|
8029 |
|
8030 | this.expressionsToBeDeoptimized = new Map();
|
8031 | this.hasUnknownDeoptimizedProperty = false;
|
8032 | this.propertyMap = null;
|
8033 | this.unmatchablePropertiesRead = [];
|
8034 | this.unmatchablePropertiesWrite = [];
|
8035 | }
|
8036 | bind() {
|
8037 | super.bind();
|
8038 |
|
8039 | this.getPropertyMap();
|
8040 | }
|
8041 |
|
8042 | deoptimizeCache() {
|
8043 | if (!this.hasUnknownDeoptimizedProperty)
|
8044 | this.deoptimizeAllProperties();
|
8045 | }
|
8046 | deoptimizePath(path) {
|
8047 | if (this.hasUnknownDeoptimizedProperty)
|
8048 | return;
|
8049 | const propertyMap = this.getPropertyMap();
|
8050 | const key = path[0];
|
8051 | if (path.length === 1) {
|
8052 | if (typeof key !== 'string') {
|
8053 | this.deoptimizeAllProperties();
|
8054 | return;
|
8055 | }
|
8056 | if (!this.deoptimizedPaths.has(key)) {
|
8057 | this.deoptimizedPaths.add(key);
|
8058 |
|
8059 |
|
8060 | const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
|
8061 | if (expressionsToBeDeoptimized) {
|
8062 | for (const expression of expressionsToBeDeoptimized) {
|
8063 | expression.deoptimizeCache();
|
8064 | }
|
8065 | }
|
8066 | }
|
8067 | }
|
8068 | const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
|
8069 | for (const property of typeof key === 'string'
|
8070 | ? propertyMap[key]
|
8071 | ? propertyMap[key].propertiesRead
|
8072 | : []
|
8073 | : this.properties) {
|
8074 | property.deoptimizePath(subPath);
|
8075 | }
|
8076 | }
|
8077 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
8078 | const propertyMap = this.getPropertyMap();
|
8079 | const key = path[0];
|
8080 | if (path.length === 0 ||
|
8081 | this.hasUnknownDeoptimizedProperty ||
|
8082 | typeof key !== 'string' ||
|
8083 | this.deoptimizedPaths.has(key)) {
|
8084 | return UnknownValue;
|
8085 | }
|
8086 | if (path.length === 1 &&
|
8087 | !propertyMap[key] &&
|
8088 | !objectMembers[key] &&
|
8089 | this.unmatchablePropertiesRead.length === 0) {
|
8090 | getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
|
8091 | return undefined;
|
8092 | }
|
8093 | if (!propertyMap[key] ||
|
8094 | propertyMap[key].exactMatchRead === null ||
|
8095 | propertyMap[key].propertiesRead.length > 1) {
|
8096 | return UnknownValue;
|
8097 | }
|
8098 | getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
|
8099 | return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
|
8100 | }
|
8101 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
8102 | const propertyMap = this.getPropertyMap();
|
8103 | const key = path[0];
|
8104 | if (path.length === 0 ||
|
8105 | this.hasUnknownDeoptimizedProperty ||
|
8106 | typeof key !== 'string' ||
|
8107 | this.deoptimizedPaths.has(key)) {
|
8108 | return UNKNOWN_EXPRESSION;
|
8109 | }
|
8110 | if (path.length === 1 &&
|
8111 | objectMembers[key] &&
|
8112 | this.unmatchablePropertiesRead.length === 0 &&
|
8113 | (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
|
8114 | return getMemberReturnExpressionWhenCalled(objectMembers, key);
|
8115 | }
|
8116 | if (!propertyMap[key] ||
|
8117 | propertyMap[key].exactMatchRead === null ||
|
8118 | propertyMap[key].propertiesRead.length > 1) {
|
8119 | return UNKNOWN_EXPRESSION;
|
8120 | }
|
8121 | getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
|
8122 | return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
|
8123 | }
|
8124 | hasEffectsWhenAccessedAtPath(path, context) {
|
8125 | if (path.length === 0)
|
8126 | return false;
|
8127 | const key = path[0];
|
8128 | const propertyMap = this.propertyMap;
|
8129 | if (path.length > 1 &&
|
8130 | (this.hasUnknownDeoptimizedProperty ||
|
8131 | typeof key !== 'string' ||
|
8132 | this.deoptimizedPaths.has(key) ||
|
8133 | !propertyMap[key] ||
|
8134 | propertyMap[key].exactMatchRead === null))
|
8135 | return true;
|
8136 | const subPath = path.slice(1);
|
8137 | for (const property of typeof key !== 'string'
|
8138 | ? this.properties
|
8139 | : propertyMap[key]
|
8140 | ? propertyMap[key].propertiesRead
|
8141 | : []) {
|
8142 | if (property.hasEffectsWhenAccessedAtPath(subPath, context))
|
8143 | return true;
|
8144 | }
|
8145 | return false;
|
8146 | }
|
8147 | hasEffectsWhenAssignedAtPath(path, context) {
|
8148 | const key = path[0];
|
8149 | const propertyMap = this.propertyMap;
|
8150 | if (path.length > 1 &&
|
8151 | (this.hasUnknownDeoptimizedProperty ||
|
8152 | this.deoptimizedPaths.has(key) ||
|
8153 | !propertyMap[key] ||
|
8154 | propertyMap[key].exactMatchRead === null)) {
|
8155 | return true;
|
8156 | }
|
8157 | const subPath = path.slice(1);
|
8158 | for (const property of typeof key !== 'string'
|
8159 | ? this.properties
|
8160 | : path.length > 1
|
8161 | ? propertyMap[key].propertiesRead
|
8162 | : propertyMap[key]
|
8163 | ? propertyMap[key].propertiesWrite
|
8164 | : []) {
|
8165 | if (property.hasEffectsWhenAssignedAtPath(subPath, context))
|
8166 | return true;
|
8167 | }
|
8168 | return false;
|
8169 | }
|
8170 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
8171 | const key = path[0];
|
8172 | if (typeof key !== 'string' ||
|
8173 | this.hasUnknownDeoptimizedProperty ||
|
8174 | this.deoptimizedPaths.has(key) ||
|
8175 | (this.propertyMap[key]
|
8176 | ? !this.propertyMap[key].exactMatchRead
|
8177 | : path.length > 1 || !objectMembers[key])) {
|
8178 | return true;
|
8179 | }
|
8180 | const subPath = path.slice(1);
|
8181 | if (this.propertyMap[key]) {
|
8182 | for (const property of this.propertyMap[key].propertiesRead) {
|
8183 | if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
|
8184 | return true;
|
8185 | }
|
8186 | }
|
8187 | if (path.length === 1 && objectMembers[key])
|
8188 | return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
|
8189 | return false;
|
8190 | }
|
8191 | render(code, options, { renderedParentType } = BLANK) {
|
8192 | super.render(code, options);
|
8193 | if (renderedParentType === ExpressionStatement ||
|
8194 | renderedParentType === ArrowFunctionExpression) {
|
8195 | code.appendRight(this.start, '(');
|
8196 | code.prependLeft(this.end, ')');
|
8197 | }
|
8198 | }
|
8199 | deoptimizeAllProperties() {
|
8200 | this.hasUnknownDeoptimizedProperty = true;
|
8201 | for (const property of this.properties) {
|
8202 | property.deoptimizePath(UNKNOWN_PATH);
|
8203 | }
|
8204 | for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
|
8205 | for (const expression of expressionsToBeDeoptimized) {
|
8206 | expression.deoptimizeCache();
|
8207 | }
|
8208 | }
|
8209 | }
|
8210 | getPropertyMap() {
|
8211 | if (this.propertyMap !== null) {
|
8212 | return this.propertyMap;
|
8213 | }
|
8214 | const propertyMap = (this.propertyMap = Object.create(null));
|
8215 | for (let index = this.properties.length - 1; index >= 0; index--) {
|
8216 | const property = this.properties[index];
|
8217 | if (property instanceof SpreadElement) {
|
8218 | this.unmatchablePropertiesRead.push(property);
|
8219 | continue;
|
8220 | }
|
8221 | const isWrite = property.kind !== 'get';
|
8222 | const isRead = property.kind !== 'set';
|
8223 | let key;
|
8224 | if (property.computed) {
|
8225 | const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
|
8226 | if (keyValue === UnknownValue) {
|
8227 | if (isRead) {
|
8228 | this.unmatchablePropertiesRead.push(property);
|
8229 | }
|
8230 | else {
|
8231 | this.unmatchablePropertiesWrite.push(property);
|
8232 | }
|
8233 | continue;
|
8234 | }
|
8235 | key = String(keyValue);
|
8236 | }
|
8237 | else if (property.key instanceof Identifier$1) {
|
8238 | key = property.key.name;
|
8239 | }
|
8240 | else {
|
8241 | key = String(property.key.value);
|
8242 | }
|
8243 | const propertyMapProperty = propertyMap[key];
|
8244 | if (!propertyMapProperty) {
|
8245 | propertyMap[key] = {
|
8246 | exactMatchRead: isRead ? property : null,
|
8247 | exactMatchWrite: isWrite ? property : null,
|
8248 | propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
|
8249 | propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
|
8250 | };
|
8251 | continue;
|
8252 | }
|
8253 | if (isRead && propertyMapProperty.exactMatchRead === null) {
|
8254 | propertyMapProperty.exactMatchRead = property;
|
8255 | propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
|
8256 | }
|
8257 | if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
|
8258 | propertyMapProperty.exactMatchWrite = property;
|
8259 | propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
|
8260 | }
|
8261 | }
|
8262 | return propertyMap;
|
8263 | }
|
8264 | }
|
8265 |
|
8266 | class ObjectPattern extends NodeBase {
|
8267 | addExportedVariables(variables, exportNamesByVariable) {
|
8268 | for (const property of this.properties) {
|
8269 | if (property.type === Property) {
|
8270 | property.value.addExportedVariables(variables, exportNamesByVariable);
|
8271 | }
|
8272 | else {
|
8273 | property.argument.addExportedVariables(variables, exportNamesByVariable);
|
8274 | }
|
8275 | }
|
8276 | }
|
8277 | declare(kind, init) {
|
8278 | const variables = [];
|
8279 | for (const property of this.properties) {
|
8280 | variables.push(...property.declare(kind, init));
|
8281 | }
|
8282 | return variables;
|
8283 | }
|
8284 | deoptimizePath(path) {
|
8285 | if (path.length === 0) {
|
8286 | for (const property of this.properties) {
|
8287 | property.deoptimizePath(path);
|
8288 | }
|
8289 | }
|
8290 | }
|
8291 | hasEffectsWhenAssignedAtPath(path, context) {
|
8292 | if (path.length > 0)
|
8293 | return true;
|
8294 | for (const property of this.properties) {
|
8295 | if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
|
8296 | return true;
|
8297 | }
|
8298 | return false;
|
8299 | }
|
8300 | }
|
8301 |
|
8302 | class PrivateName extends NodeBase {
|
8303 | }
|
8304 |
|
8305 | class Program$1 extends NodeBase {
|
8306 | constructor() {
|
8307 | super(...arguments);
|
8308 | this.hasCachedEffect = false;
|
8309 | }
|
8310 | hasEffects(context) {
|
8311 |
|
8312 | if (this.hasCachedEffect)
|
8313 | return true;
|
8314 | for (const node of this.body) {
|
8315 | if (node.hasEffects(context)) {
|
8316 | return (this.hasCachedEffect = true);
|
8317 | }
|
8318 | }
|
8319 | return false;
|
8320 | }
|
8321 | include(context, includeChildrenRecursively) {
|
8322 | this.included = true;
|
8323 | for (const node of this.body) {
|
8324 | if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
|
8325 | node.include(context, includeChildrenRecursively);
|
8326 | }
|
8327 | }
|
8328 | }
|
8329 | render(code, options) {
|
8330 | if (this.body.length) {
|
8331 | renderStatementList(this.body, code, this.start, this.end, options);
|
8332 | }
|
8333 | else {
|
8334 | super.render(code, options);
|
8335 | }
|
8336 | }
|
8337 | }
|
8338 |
|
8339 | class Property$1 extends NodeBase {
|
8340 | constructor() {
|
8341 | super(...arguments);
|
8342 | this.declarationInit = null;
|
8343 | this.returnExpression = null;
|
8344 | }
|
8345 | bind() {
|
8346 | super.bind();
|
8347 | if (this.kind === 'get') {
|
8348 |
|
8349 | this.getReturnExpression();
|
8350 | }
|
8351 | if (this.declarationInit !== null) {
|
8352 | this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
|
8353 | }
|
8354 | }
|
8355 | declare(kind, init) {
|
8356 | this.declarationInit = init;
|
8357 | return this.value.declare(kind, UNKNOWN_EXPRESSION);
|
8358 | }
|
8359 |
|
8360 |
|
8361 | deoptimizeCache() { }
|
8362 | deoptimizePath(path) {
|
8363 | if (this.kind === 'get') {
|
8364 | this.getReturnExpression().deoptimizePath(path);
|
8365 | }
|
8366 | else {
|
8367 | this.value.deoptimizePath(path);
|
8368 | }
|
8369 | }
|
8370 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
8371 | if (this.kind === 'get') {
|
8372 | return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
|
8373 | }
|
8374 | return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
|
8375 | }
|
8376 | getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
|
8377 | if (this.kind === 'get') {
|
8378 | return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
8379 | }
|
8380 | return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
8381 | }
|
8382 | hasEffects(context) {
|
8383 | return this.key.hasEffects(context) || this.value.hasEffects(context);
|
8384 | }
|
8385 | hasEffectsWhenAccessedAtPath(path, context) {
|
8386 | if (this.kind === 'get') {
|
8387 | const trackedExpressions = context.accessed.getEntities(path);
|
8388 | if (trackedExpressions.has(this))
|
8389 | return false;
|
8390 | trackedExpressions.add(this);
|
8391 | return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
|
8392 | (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
|
8393 | }
|
8394 | return this.value.hasEffectsWhenAccessedAtPath(path, context);
|
8395 | }
|
8396 | hasEffectsWhenAssignedAtPath(path, context) {
|
8397 | if (this.kind === 'get') {
|
8398 | const trackedExpressions = context.assigned.getEntities(path);
|
8399 | if (trackedExpressions.has(this))
|
8400 | return false;
|
8401 | trackedExpressions.add(this);
|
8402 | return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
|
8403 | }
|
8404 | if (this.kind === 'set') {
|
8405 | const trackedExpressions = context.assigned.getEntities(path);
|
8406 | if (trackedExpressions.has(this))
|
8407 | return false;
|
8408 | trackedExpressions.add(this);
|
8409 | return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
|
8410 | }
|
8411 | return this.value.hasEffectsWhenAssignedAtPath(path, context);
|
8412 | }
|
8413 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
8414 | if (this.kind === 'get') {
|
8415 | const trackedExpressions = (callOptions.withNew
|
8416 | ? context.instantiated
|
8417 | : context.called).getEntities(path, callOptions);
|
8418 | if (trackedExpressions.has(this))
|
8419 | return false;
|
8420 | trackedExpressions.add(this);
|
8421 | return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
8422 | }
|
8423 | return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
|
8424 | }
|
8425 | initialise() {
|
8426 | this.accessorCallOptions = {
|
8427 | args: NO_ARGS,
|
8428 | withNew: false
|
8429 | };
|
8430 | }
|
8431 | render(code, options) {
|
8432 | if (!this.shorthand) {
|
8433 | this.key.render(code, options);
|
8434 | }
|
8435 | this.value.render(code, options, { isShorthandProperty: this.shorthand });
|
8436 | }
|
8437 | getReturnExpression() {
|
8438 | if (this.returnExpression === null) {
|
8439 | this.returnExpression = UNKNOWN_EXPRESSION;
|
8440 | return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
|
8441 | }
|
8442 | return this.returnExpression;
|
8443 | }
|
8444 | }
|
8445 |
|
8446 | class ReturnStatement$1 extends NodeBase {
|
8447 | hasEffects(context) {
|
8448 | if (!context.ignore.returnAwaitYield ||
|
8449 | (this.argument !== null && this.argument.hasEffects(context)))
|
8450 | return true;
|
8451 | context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
|
8452 | return false;
|
8453 | }
|
8454 | include(context, includeChildrenRecursively) {
|
8455 | this.included = true;
|
8456 | if (this.argument) {
|
8457 | this.argument.include(context, includeChildrenRecursively);
|
8458 | }
|
8459 | context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
|
8460 | }
|
8461 | initialise() {
|
8462 | this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
|
8463 | }
|
8464 | render(code, options) {
|
8465 | if (this.argument) {
|
8466 | this.argument.render(code, options, { preventASI: true });
|
8467 | if (this.argument.start === this.start + 6 ) {
|
8468 | code.prependLeft(this.start + 6, ' ');
|
8469 | }
|
8470 | }
|
8471 | }
|
8472 | }
|
8473 |
|
8474 | class SequenceExpression extends NodeBase {
|
8475 | deoptimizePath(path) {
|
8476 | if (path.length > 0)
|
8477 | this.expressions[this.expressions.length - 1].deoptimizePath(path);
|
8478 | }
|
8479 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
8480 | return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
|
8481 | }
|
8482 | hasEffects(context) {
|
8483 | for (const expression of this.expressions) {
|
8484 | if (expression.hasEffects(context))
|
8485 | return true;
|
8486 | }
|
8487 | return false;
|
8488 | }
|
8489 | hasEffectsWhenAccessedAtPath(path, context) {
|
8490 | return (path.length > 0 &&
|
8491 | this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
|
8492 | }
|
8493 | hasEffectsWhenAssignedAtPath(path, context) {
|
8494 | return (path.length === 0 ||
|
8495 | this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
|
8496 | }
|
8497 | hasEffectsWhenCalledAtPath(path, callOptions, context) {
|
8498 | return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
|
8499 | }
|
8500 | include(context, includeChildrenRecursively) {
|
8501 | this.included = true;
|
8502 | for (let i = 0; i < this.expressions.length - 1; i++) {
|
8503 | const node = this.expressions[i];
|
8504 | if (includeChildrenRecursively || node.shouldBeIncluded(context))
|
8505 | node.include(context, includeChildrenRecursively);
|
8506 | }
|
8507 | this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
|
8508 | }
|
8509 | render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
|
8510 | let includedNodes = 0;
|
8511 | for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
|
8512 | if (!node.included) {
|
8513 | treeshakeNode(node, code, start, end);
|
8514 | continue;
|
8515 | }
|
8516 | includedNodes++;
|
8517 | if (includedNodes === 1 && preventASI) {
|
8518 | removeLineBreaks(code, start, node.start);
|
8519 | }
|
8520 | if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
|
8521 | node.render(code, options, {
|
8522 | isCalleeOfRenderedParent: renderedParentType
|
8523 | ? isCalleeOfRenderedParent
|
8524 | : this.parent.callee === this,
|
8525 | renderedParentType: renderedParentType || this.parent.type
|
8526 | });
|
8527 | }
|
8528 | else {
|
8529 | node.render(code, options);
|
8530 | }
|
8531 | }
|
8532 | }
|
8533 | }
|
8534 |
|
8535 | class Super extends NodeBase {
|
8536 | }
|
8537 |
|
8538 | class SwitchCase extends NodeBase {
|
8539 | hasEffects(context) {
|
8540 | if (this.test && this.test.hasEffects(context))
|
8541 | return true;
|
8542 | for (const node of this.consequent) {
|
8543 | if (context.brokenFlow)
|
8544 | break;
|
8545 | if (node.hasEffects(context))
|
8546 | return true;
|
8547 | }
|
8548 | return false;
|
8549 | }
|
8550 | include(context, includeChildrenRecursively) {
|
8551 | this.included = true;
|
8552 | if (this.test)
|
8553 | this.test.include(context, includeChildrenRecursively);
|
8554 | for (const node of this.consequent) {
|
8555 | if (includeChildrenRecursively || node.shouldBeIncluded(context))
|
8556 | node.include(context, includeChildrenRecursively);
|
8557 | }
|
8558 | }
|
8559 | render(code, options, nodeRenderOptions) {
|
8560 | if (this.consequent.length) {
|
8561 | this.test && this.test.render(code, options);
|
8562 | const testEnd = this.test
|
8563 | ? this.test.end
|
8564 | : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
|
8565 | const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
|
8566 | renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
|
8567 | }
|
8568 | else {
|
8569 | super.render(code, options);
|
8570 | }
|
8571 | }
|
8572 | }
|
8573 | SwitchCase.prototype.needsBoundaries = true;
|
8574 |
|
8575 | class SwitchStatement extends NodeBase {
|
8576 | createScope(parentScope) {
|
8577 | this.scope = new BlockScope(parentScope);
|
8578 | }
|
8579 | hasEffects(context) {
|
8580 | if (this.discriminant.hasEffects(context))
|
8581 | return true;
|
8582 | const { brokenFlow, ignore: { breaks } } = context;
|
8583 | let minBrokenFlow = Infinity;
|
8584 | context.ignore.breaks = true;
|
8585 | for (const switchCase of this.cases) {
|
8586 | if (switchCase.hasEffects(context))
|
8587 | return true;
|
8588 | minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
|
8589 | context.brokenFlow = brokenFlow;
|
8590 | }
|
8591 | if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
|
8592 | context.brokenFlow = minBrokenFlow;
|
8593 | }
|
8594 | context.ignore.breaks = breaks;
|
8595 | return false;
|
8596 | }
|
8597 | include(context, includeChildrenRecursively) {
|
8598 | this.included = true;
|
8599 | this.discriminant.include(context, includeChildrenRecursively);
|
8600 | const { brokenFlow } = context;
|
8601 | let minBrokenFlow = Infinity;
|
8602 | let isCaseIncluded = includeChildrenRecursively ||
|
8603 | (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
|
8604 | for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
|
8605 | const switchCase = this.cases[caseIndex];
|
8606 | if (switchCase.included) {
|
8607 | isCaseIncluded = true;
|
8608 | }
|
8609 | if (!isCaseIncluded) {
|
8610 | const hasEffectsContext = createHasEffectsContext();
|
8611 | hasEffectsContext.ignore.breaks = true;
|
8612 | isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
|
8613 | }
|
8614 | if (isCaseIncluded) {
|
8615 | switchCase.include(context, includeChildrenRecursively);
|
8616 | minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
|
8617 | context.brokenFlow = brokenFlow;
|
8618 | }
|
8619 | else {
|
8620 | minBrokenFlow = brokenFlow;
|
8621 | }
|
8622 | }
|
8623 | if (isCaseIncluded &&
|
8624 | this.defaultCase !== null &&
|
8625 | !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
|
8626 | context.brokenFlow = minBrokenFlow;
|
8627 | }
|
8628 | }
|
8629 | initialise() {
|
8630 | for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
|
8631 | if (this.cases[caseIndex].test === null) {
|
8632 | this.defaultCase = caseIndex;
|
8633 | return;
|
8634 | }
|
8635 | }
|
8636 | this.defaultCase = null;
|
8637 | }
|
8638 | render(code, options) {
|
8639 | this.discriminant.render(code, options);
|
8640 | if (this.cases.length > 0) {
|
8641 | renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
|
8642 | }
|
8643 | }
|
8644 | }
|
8645 |
|
8646 | class TaggedTemplateExpression extends NodeBase {
|
8647 | bind() {
|
8648 | super.bind();
|
8649 | if (this.tag.type === Identifier) {
|
8650 | const name = this.tag.name;
|
8651 | const variable = this.scope.findVariable(name);
|
8652 | if (variable.isNamespace) {
|
8653 | this.context.warn({
|
8654 | code: 'CANNOT_CALL_NAMESPACE',
|
8655 | message: `Cannot call a namespace ('${name}')`,
|
8656 | }, this.start);
|
8657 | }
|
8658 | if (name === 'eval') {
|
8659 | this.context.warn({
|
8660 | code: 'EVAL',
|
8661 | message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
|
8662 | url: 'https://rollupjs.org/guide/en/#avoiding-eval',
|
8663 | }, this.start);
|
8664 | }
|
8665 | }
|
8666 | }
|
8667 | hasEffects(context) {
|
8668 | return (super.hasEffects(context) ||
|
8669 | this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
|
8670 | }
|
8671 | initialise() {
|
8672 | this.callOptions = {
|
8673 | args: NO_ARGS,
|
8674 | withNew: false,
|
8675 | };
|
8676 | }
|
8677 | }
|
8678 |
|
8679 | class TemplateElement extends NodeBase {
|
8680 | bind() { }
|
8681 | hasEffects() {
|
8682 | return false;
|
8683 | }
|
8684 | include() {
|
8685 | this.included = true;
|
8686 | }
|
8687 | parseNode(esTreeNode) {
|
8688 | this.value = esTreeNode.value;
|
8689 | super.parseNode(esTreeNode);
|
8690 | }
|
8691 | render() { }
|
8692 | }
|
8693 |
|
8694 | class TemplateLiteral extends NodeBase {
|
8695 | getLiteralValueAtPath(path) {
|
8696 | if (path.length > 0 || this.quasis.length !== 1) {
|
8697 | return UnknownValue;
|
8698 | }
|
8699 | return this.quasis[0].value.cooked;
|
8700 | }
|
8701 | render(code, options) {
|
8702 | code.indentExclusionRanges.push([this.start, this.end]);
|
8703 | super.render(code, options);
|
8704 | }
|
8705 | }
|
8706 |
|
8707 | class ModuleScope extends ChildScope {
|
8708 | constructor(parent, context) {
|
8709 | super(parent);
|
8710 | this.context = context;
|
8711 | this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
|
8712 | }
|
8713 | addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
|
8714 | const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
|
8715 | this.variables.set('default', variable);
|
8716 | return variable;
|
8717 | }
|
8718 | addNamespaceMemberAccess() { }
|
8719 | deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
|
8720 |
|
8721 | for (const scope of this.children)
|
8722 | scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
|
8723 | }
|
8724 | findLexicalBoundary() {
|
8725 | return this;
|
8726 | }
|
8727 | findVariable(name) {
|
8728 | const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
|
8729 | if (knownVariable) {
|
8730 | return knownVariable;
|
8731 | }
|
8732 | const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
|
8733 | if (variable instanceof GlobalVariable) {
|
8734 | this.accessedOutsideVariables.set(name, variable);
|
8735 | }
|
8736 | return variable;
|
8737 | }
|
8738 | }
|
8739 |
|
8740 | class ThisExpression extends NodeBase {
|
8741 | bind() {
|
8742 | super.bind();
|
8743 | this.variable = this.scope.findVariable('this');
|
8744 | }
|
8745 | hasEffectsWhenAccessedAtPath(path, context) {
|
8746 | return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
|
8747 | }
|
8748 | hasEffectsWhenAssignedAtPath(path, context) {
|
8749 | return this.variable.hasEffectsWhenAssignedAtPath(path, context);
|
8750 | }
|
8751 | initialise() {
|
8752 | this.alias =
|
8753 | this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
|
8754 | if (this.alias === 'undefined') {
|
8755 | this.context.warn({
|
8756 | code: 'THIS_IS_UNDEFINED',
|
8757 | message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
|
8758 | url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
|
8759 | }, this.start);
|
8760 | }
|
8761 | }
|
8762 | render(code) {
|
8763 | if (this.alias !== null) {
|
8764 | code.overwrite(this.start, this.end, this.alias, {
|
8765 | contentOnly: false,
|
8766 | storeName: true
|
8767 | });
|
8768 | }
|
8769 | }
|
8770 | }
|
8771 |
|
8772 | class ThrowStatement extends NodeBase {
|
8773 | hasEffects() {
|
8774 | return true;
|
8775 | }
|
8776 | include(context, includeChildrenRecursively) {
|
8777 | this.included = true;
|
8778 | this.argument.include(context, includeChildrenRecursively);
|
8779 | context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
|
8780 | }
|
8781 | render(code, options) {
|
8782 | this.argument.render(code, options, { preventASI: true });
|
8783 | if (this.argument.start === this.start + 5 ) {
|
8784 | code.prependLeft(this.start + 5, ' ');
|
8785 | }
|
8786 | }
|
8787 | }
|
8788 |
|
8789 | class TryStatement extends NodeBase {
|
8790 | constructor() {
|
8791 | super(...arguments);
|
8792 | this.directlyIncluded = false;
|
8793 | }
|
8794 | hasEffects(context) {
|
8795 | return ((this.context.options.treeshake.tryCatchDeoptimization
|
8796 | ? this.block.body.length > 0
|
8797 | : this.block.hasEffects(context)) ||
|
8798 | (this.finalizer !== null && this.finalizer.hasEffects(context)));
|
8799 | }
|
8800 | include(context, includeChildrenRecursively) {
|
8801 | var _a;
|
8802 | const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
|
8803 | const { brokenFlow } = context;
|
8804 | if (!this.directlyIncluded || !tryCatchDeoptimization) {
|
8805 | this.included = true;
|
8806 | this.directlyIncluded = true;
|
8807 | this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
|
8808 | context.brokenFlow = brokenFlow;
|
8809 | }
|
8810 | if (this.handler !== null) {
|
8811 | this.handler.include(context, includeChildrenRecursively);
|
8812 | context.brokenFlow = brokenFlow;
|
8813 | }
|
8814 | if (this.finalizer !== null) {
|
8815 | this.finalizer.include(context, includeChildrenRecursively);
|
8816 | }
|
8817 | }
|
8818 | }
|
8819 |
|
8820 | const unaryOperators = {
|
8821 | '!': value => !value,
|
8822 | '+': value => +value,
|
8823 | '-': value => -value,
|
8824 | delete: () => UnknownValue,
|
8825 | typeof: value => typeof value,
|
8826 | void: () => undefined,
|
8827 | '~': value => ~value
|
8828 | };
|
8829 | class UnaryExpression extends NodeBase {
|
8830 | bind() {
|
8831 | super.bind();
|
8832 | if (this.operator === 'delete') {
|
8833 | this.argument.deoptimizePath(EMPTY_PATH);
|
8834 | }
|
8835 | }
|
8836 | getLiteralValueAtPath(path, recursionTracker, origin) {
|
8837 | if (path.length > 0)
|
8838 | return UnknownValue;
|
8839 | const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
8840 | if (argumentValue === UnknownValue)
|
8841 | return UnknownValue;
|
8842 | return unaryOperators[this.operator](argumentValue);
|
8843 | }
|
8844 | hasEffects(context) {
|
8845 | if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
|
8846 | return false;
|
8847 | return (this.argument.hasEffects(context) ||
|
8848 | (this.operator === 'delete' &&
|
8849 | this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
|
8850 | }
|
8851 | hasEffectsWhenAccessedAtPath(path) {
|
8852 | if (this.operator === 'void') {
|
8853 | return path.length > 0;
|
8854 | }
|
8855 | return path.length > 1;
|
8856 | }
|
8857 | }
|
8858 |
|
8859 | class UnknownNode extends NodeBase {
|
8860 | hasEffects() {
|
8861 | return true;
|
8862 | }
|
8863 | include(context) {
|
8864 | super.include(context, true);
|
8865 | }
|
8866 | }
|
8867 |
|
8868 | class UpdateExpression extends NodeBase {
|
8869 | bind() {
|
8870 | super.bind();
|
8871 | this.argument.deoptimizePath(EMPTY_PATH);
|
8872 | if (this.argument instanceof Identifier$1) {
|
8873 | const variable = this.scope.findVariable(this.argument.name);
|
8874 | variable.isReassigned = true;
|
8875 | }
|
8876 | }
|
8877 | hasEffects(context) {
|
8878 | return (this.argument.hasEffects(context) ||
|
8879 | this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
|
8880 | }
|
8881 | hasEffectsWhenAccessedAtPath(path) {
|
8882 | return path.length > 1;
|
8883 | }
|
8884 | render(code, options) {
|
8885 | this.argument.render(code, options);
|
8886 | if (options.format === 'system') {
|
8887 | const variable = this.argument.variable;
|
8888 | const exportNames = options.exportNamesByVariable.get(variable);
|
8889 | if (exportNames && exportNames.length) {
|
8890 | const _ = options.compact ? '' : ' ';
|
8891 | const name = variable.getName();
|
8892 | if (this.prefix) {
|
8893 | if (exportNames.length === 1) {
|
8894 | code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
|
8895 | }
|
8896 | else {
|
8897 | code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
|
8898 | }
|
8899 | }
|
8900 | else if (exportNames.length > 1) {
|
8901 | code.overwrite(this.start, this.end, `${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name})`);
|
8902 | }
|
8903 | else {
|
8904 | let op;
|
8905 | switch (this.operator) {
|
8906 | case '++':
|
8907 | op = `${name}${_}+${_}1`;
|
8908 | break;
|
8909 | case '--':
|
8910 | op = `${name}${_}-${_}1`;
|
8911 | break;
|
8912 | }
|
8913 | code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
|
8914 | }
|
8915 | }
|
8916 | }
|
8917 | }
|
8918 | }
|
8919 |
|
8920 | function isReassignedExportsMember(variable, exportNamesByVariable) {
|
8921 | return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
|
8922 | }
|
8923 | function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
|
8924 | for (const declarator of declarations) {
|
8925 | if (!declarator.included)
|
8926 | return false;
|
8927 | if (declarator.id.type === Identifier) {
|
8928 | if (exportNamesByVariable.has(declarator.id.variable))
|
8929 | return false;
|
8930 | }
|
8931 | else {
|
8932 | const exportedVariables = [];
|
8933 | declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
|
8934 | if (exportedVariables.length > 0)
|
8935 | return false;
|
8936 | }
|
8937 | }
|
8938 | return true;
|
8939 | }
|
8940 | class VariableDeclaration extends NodeBase {
|
8941 | deoptimizePath() {
|
8942 | for (const declarator of this.declarations) {
|
8943 | declarator.deoptimizePath(EMPTY_PATH);
|
8944 | }
|
8945 | }
|
8946 | hasEffectsWhenAssignedAtPath() {
|
8947 | return false;
|
8948 | }
|
8949 | include(context, includeChildrenRecursively) {
|
8950 | this.included = true;
|
8951 | for (const declarator of this.declarations) {
|
8952 | if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
|
8953 | declarator.include(context, includeChildrenRecursively);
|
8954 | }
|
8955 | }
|
8956 | includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
|
8957 | this.included = true;
|
8958 | for (const declarator of this.declarations) {
|
8959 | declarator.include(context, includeChildrenRecursively);
|
8960 | }
|
8961 | }
|
8962 | initialise() {
|
8963 | for (const declarator of this.declarations) {
|
8964 | declarator.declareDeclarator(this.kind);
|
8965 | }
|
8966 | }
|
8967 | render(code, options, nodeRenderOptions = BLANK) {
|
8968 | if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
|
8969 | for (const declarator of this.declarations) {
|
8970 | declarator.render(code, options);
|
8971 | }
|
8972 | if (!nodeRenderOptions.isNoStatement &&
|
8973 | code.original.charCodeAt(this.end - 1) !== 59 ) {
|
8974 | code.appendLeft(this.end, ';');
|
8975 | }
|
8976 | }
|
8977 | else {
|
8978 | this.renderReplacedDeclarations(code, options, nodeRenderOptions);
|
8979 | }
|
8980 | }
|
8981 | renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports, options) {
|
8982 | if (code.original.charCodeAt(this.end - 1) === 59 ) {
|
8983 | code.remove(this.end - 1, this.end);
|
8984 | }
|
8985 | if (addSemicolon) {
|
8986 | separatorString += ';';
|
8987 | }
|
8988 | if (lastSeparatorPos !== null) {
|
8989 | if (code.original.charCodeAt(actualContentEnd - 1) === 10 &&
|
8990 | (code.original.charCodeAt(this.end) === 10 ||
|
8991 | code.original.charCodeAt(this.end) === 13) ) {
|
8992 | actualContentEnd--;
|
8993 | if (code.original.charCodeAt(actualContentEnd) === 13 ) {
|
8994 | actualContentEnd--;
|
8995 | }
|
8996 | }
|
8997 | if (actualContentEnd === lastSeparatorPos + 1) {
|
8998 | code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
|
8999 | }
|
9000 | else {
|
9001 | code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
|
9002 | code.remove(actualContentEnd, renderedContentEnd);
|
9003 | }
|
9004 | }
|
9005 | else {
|
9006 | code.appendLeft(renderedContentEnd, separatorString);
|
9007 | }
|
9008 | if (systemPatternExports.length > 0) {
|
9009 | code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
|
9010 | }
|
9011 | }
|
9012 | renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
|
9013 | const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 ? 1 : 0));
|
9014 | let actualContentEnd, renderedContentEnd;
|
9015 | if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
|
9016 | renderedContentEnd = this.start + this.kind.length;
|
9017 | }
|
9018 | else {
|
9019 | renderedContentEnd = separatedNodes[0].start;
|
9020 | }
|
9021 | let lastSeparatorPos = renderedContentEnd - 1;
|
9022 | code.remove(this.start, lastSeparatorPos);
|
9023 | let isInDeclaration = false;
|
9024 | let hasRenderedContent = false;
|
9025 | let separatorString = '', leadingString, nextSeparatorString;
|
9026 | const systemPatternExports = [];
|
9027 | for (const { node, start, separator, contentEnd, end } of separatedNodes) {
|
9028 | if (!node.included ||
|
9029 | (node.id instanceof Identifier$1 &&
|
9030 | isReassignedExportsMember(node.id.variable, options.exportNamesByVariable) &&
|
9031 | node.init === null)) {
|
9032 | code.remove(start, end);
|
9033 | continue;
|
9034 | }
|
9035 | leadingString = '';
|
9036 | nextSeparatorString = '';
|
9037 | if (node.id instanceof Identifier$1 &&
|
9038 | isReassignedExportsMember(node.id.variable, options.exportNamesByVariable)) {
|
9039 | if (hasRenderedContent) {
|
9040 | separatorString += ';';
|
9041 | }
|
9042 | isInDeclaration = false;
|
9043 | }
|
9044 | else {
|
9045 | if (options.format === 'system' && node.init !== null) {
|
9046 | if (node.id.type !== Identifier) {
|
9047 | node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
|
9048 | }
|
9049 | else {
|
9050 | const exportNames = options.exportNamesByVariable.get(node.id.variable);
|
9051 | if (exportNames) {
|
9052 | const _ = options.compact ? '' : ' ';
|
9053 | const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
|
9054 | code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
|
9055 | ? `exports('${exportNames[0]}',${_}`
|
9056 | : getSystemExportFunctionLeft([node.id.variable], false, options));
|
9057 | nextSeparatorString += ')';
|
9058 | }
|
9059 | }
|
9060 | }
|
9061 | if (isInDeclaration) {
|
9062 | separatorString += ',';
|
9063 | }
|
9064 | else {
|
9065 | if (hasRenderedContent) {
|
9066 | separatorString += ';';
|
9067 | }
|
9068 | leadingString += `${this.kind} `;
|
9069 | isInDeclaration = true;
|
9070 | }
|
9071 | }
|
9072 | if (renderedContentEnd === lastSeparatorPos + 1) {
|
9073 | code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
|
9074 | }
|
9075 | else {
|
9076 | code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
|
9077 | code.appendLeft(renderedContentEnd, leadingString);
|
9078 | }
|
9079 | node.render(code, options);
|
9080 | actualContentEnd = contentEnd;
|
9081 | renderedContentEnd = end;
|
9082 | hasRenderedContent = true;
|
9083 | lastSeparatorPos = separator;
|
9084 | separatorString = nextSeparatorString;
|
9085 | }
|
9086 | if (hasRenderedContent) {
|
9087 | this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports, options);
|
9088 | }
|
9089 | else {
|
9090 | code.remove(start, end);
|
9091 | }
|
9092 | }
|
9093 | }
|
9094 |
|
9095 | class VariableDeclarator extends NodeBase {
|
9096 | declareDeclarator(kind) {
|
9097 | this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
|
9098 | }
|
9099 | deoptimizePath(path) {
|
9100 | this.id.deoptimizePath(path);
|
9101 | }
|
9102 | }
|
9103 |
|
9104 | class WhileStatement extends NodeBase {
|
9105 | hasEffects(context) {
|
9106 | if (this.test.hasEffects(context))
|
9107 | return true;
|
9108 | const { brokenFlow, ignore: { breaks, continues } } = context;
|
9109 | context.ignore.breaks = true;
|
9110 | context.ignore.continues = true;
|
9111 | if (this.body.hasEffects(context))
|
9112 | return true;
|
9113 | context.ignore.breaks = breaks;
|
9114 | context.ignore.continues = continues;
|
9115 | context.brokenFlow = brokenFlow;
|
9116 | return false;
|
9117 | }
|
9118 | include(context, includeChildrenRecursively) {
|
9119 | this.included = true;
|
9120 | this.test.include(context, includeChildrenRecursively);
|
9121 | const { brokenFlow } = context;
|
9122 | this.body.include(context, includeChildrenRecursively);
|
9123 | context.brokenFlow = brokenFlow;
|
9124 | }
|
9125 | }
|
9126 |
|
9127 | class YieldExpression extends NodeBase {
|
9128 | bind() {
|
9129 | super.bind();
|
9130 | if (this.argument !== null) {
|
9131 | this.argument.deoptimizePath(UNKNOWN_PATH);
|
9132 | }
|
9133 | }
|
9134 | hasEffects(context) {
|
9135 | return (!context.ignore.returnAwaitYield ||
|
9136 | (this.argument !== null && this.argument.hasEffects(context)));
|
9137 | }
|
9138 | render(code, options) {
|
9139 | if (this.argument) {
|
9140 | this.argument.render(code, options, { preventASI: true });
|
9141 | if (this.argument.start === this.start + 5 ) {
|
9142 | code.prependLeft(this.start + 5, ' ');
|
9143 | }
|
9144 | }
|
9145 | }
|
9146 | }
|
9147 |
|
9148 | const nodeConstructors = {
|
9149 | ArrayExpression,
|
9150 | ArrayPattern,
|
9151 | ArrowFunctionExpression: ArrowFunctionExpression$1,
|
9152 | AssignmentExpression,
|
9153 | AssignmentPattern,
|
9154 | AwaitExpression,
|
9155 | BinaryExpression,
|
9156 | BlockStatement: BlockStatement$1,
|
9157 | BreakStatement,
|
9158 | CallExpression: CallExpression$1,
|
9159 | CatchClause,
|
9160 | ChainExpression,
|
9161 | ClassBody,
|
9162 | ClassDeclaration,
|
9163 | ClassExpression,
|
9164 | ConditionalExpression,
|
9165 | ContinueStatement,
|
9166 | DoWhileStatement,
|
9167 | EmptyStatement,
|
9168 | ExportAllDeclaration,
|
9169 | ExportDefaultDeclaration,
|
9170 | ExportNamedDeclaration,
|
9171 | ExportSpecifier,
|
9172 | ExpressionStatement: ExpressionStatement$1,
|
9173 | FieldDefinition,
|
9174 | ForInStatement,
|
9175 | ForOfStatement,
|
9176 | ForStatement,
|
9177 | FunctionDeclaration,
|
9178 | FunctionExpression: FunctionExpression$1,
|
9179 | Identifier: Identifier$1,
|
9180 | IfStatement,
|
9181 | ImportDeclaration,
|
9182 | ImportDefaultSpecifier: ImportDefaultSpecifier$1,
|
9183 | ImportExpression,
|
9184 | ImportNamespaceSpecifier: ImportNamespaceSpecifier$1,
|
9185 | ImportSpecifier,
|
9186 | LabeledStatement,
|
9187 | Literal,
|
9188 | LogicalExpression,
|
9189 | MemberExpression,
|
9190 | MetaProperty,
|
9191 | MethodDefinition,
|
9192 | NewExpression,
|
9193 | ObjectExpression,
|
9194 | ObjectPattern,
|
9195 | PrivateName,
|
9196 | Program: Program$1,
|
9197 | Property: Property$1,
|
9198 | RestElement,
|
9199 | ReturnStatement: ReturnStatement$1,
|
9200 | SequenceExpression,
|
9201 | SpreadElement,
|
9202 | Super,
|
9203 | SwitchCase,
|
9204 | SwitchStatement,
|
9205 | TaggedTemplateExpression,
|
9206 | TemplateElement,
|
9207 | TemplateLiteral,
|
9208 | ThisExpression,
|
9209 | ThrowStatement,
|
9210 | TryStatement,
|
9211 | UnaryExpression,
|
9212 | UnknownNode,
|
9213 | UpdateExpression,
|
9214 | VariableDeclaration,
|
9215 | VariableDeclarator,
|
9216 | WhileStatement,
|
9217 | YieldExpression
|
9218 | };
|
9219 |
|
9220 | function getId(m) {
|
9221 | return m.id;
|
9222 | }
|
9223 |
|
9224 | function getOriginalLocation(sourcemapChain, location) {
|
9225 |
|
9226 | const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
|
9227 | while (filteredSourcemapChain.length > 0) {
|
9228 | const sourcemap = filteredSourcemapChain.pop();
|
9229 | const line = sourcemap.mappings[location.line - 1];
|
9230 | let locationFound = false;
|
9231 | if (line !== undefined) {
|
9232 | for (const segment of line) {
|
9233 | if (segment[0] >= location.column) {
|
9234 | if (segment.length === 1)
|
9235 | break;
|
9236 | location = {
|
9237 | column: segment[3],
|
9238 | line: segment[2] + 1,
|
9239 | name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
|
9240 | source: sourcemap.sources[segment[1]]
|
9241 | };
|
9242 | locationFound = true;
|
9243 | break;
|
9244 | }
|
9245 | }
|
9246 | }
|
9247 | if (!locationFound) {
|
9248 | throw new Error("Can't resolve original location of error.");
|
9249 | }
|
9250 | }
|
9251 | return location;
|
9252 | }
|
9253 |
|
9254 |
|
9255 |
|
9256 | function skipThrough(node, st, c) { c(node, st); }
|
9257 | function ignore(_node, _st, _c) {}
|
9258 |
|
9259 |
|
9260 |
|
9261 | var base$1 = {};
|
9262 |
|
9263 | base$1.Program = base$1.BlockStatement = function (node, st, c) {
|
9264 | for (var i = 0, list = node.body; i < list.length; i += 1)
|
9265 | {
|
9266 | var stmt = list[i];
|
9267 |
|
9268 | c(stmt, st, "Statement");
|
9269 | }
|
9270 | };
|
9271 | base$1.Statement = skipThrough;
|
9272 | base$1.EmptyStatement = ignore;
|
9273 | base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
|
9274 | function (node, st, c) { return c(node.expression, st, "Expression"); };
|
9275 | base$1.IfStatement = function (node, st, c) {
|
9276 | c(node.test, st, "Expression");
|
9277 | c(node.consequent, st, "Statement");
|
9278 | if (node.alternate) { c(node.alternate, st, "Statement"); }
|
9279 | };
|
9280 | base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
9281 | base$1.BreakStatement = base$1.ContinueStatement = ignore;
|
9282 | base$1.WithStatement = function (node, st, c) {
|
9283 | c(node.object, st, "Expression");
|
9284 | c(node.body, st, "Statement");
|
9285 | };
|
9286 | base$1.SwitchStatement = function (node, st, c) {
|
9287 | c(node.discriminant, st, "Expression");
|
9288 | for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
|
9289 | var cs = list$1[i$1];
|
9290 |
|
9291 | if (cs.test) { c(cs.test, st, "Expression"); }
|
9292 | for (var i = 0, list = cs.consequent; i < list.length; i += 1)
|
9293 | {
|
9294 | var cons = list[i];
|
9295 |
|
9296 | c(cons, st, "Statement");
|
9297 | }
|
9298 | }
|
9299 | };
|
9300 | base$1.SwitchCase = function (node, st, c) {
|
9301 | if (node.test) { c(node.test, st, "Expression"); }
|
9302 | for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
9303 | {
|
9304 | var cons = list[i];
|
9305 |
|
9306 | c(cons, st, "Statement");
|
9307 | }
|
9308 | };
|
9309 | base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
|
9310 | if (node.argument) { c(node.argument, st, "Expression"); }
|
9311 | };
|
9312 | base$1.ThrowStatement = base$1.SpreadElement =
|
9313 | function (node, st, c) { return c(node.argument, st, "Expression"); };
|
9314 | base$1.TryStatement = function (node, st, c) {
|
9315 | c(node.block, st, "Statement");
|
9316 | if (node.handler) { c(node.handler, st); }
|
9317 | if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
9318 | };
|
9319 | base$1.CatchClause = function (node, st, c) {
|
9320 | if (node.param) { c(node.param, st, "Pattern"); }
|
9321 | c(node.body, st, "Statement");
|
9322 | };
|
9323 | base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
|
9324 | c(node.test, st, "Expression");
|
9325 | c(node.body, st, "Statement");
|
9326 | };
|
9327 | base$1.ForStatement = function (node, st, c) {
|
9328 | if (node.init) { c(node.init, st, "ForInit"); }
|
9329 | if (node.test) { c(node.test, st, "Expression"); }
|
9330 | if (node.update) { c(node.update, st, "Expression"); }
|
9331 | c(node.body, st, "Statement");
|
9332 | };
|
9333 | base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
|
9334 | c(node.left, st, "ForInit");
|
9335 | c(node.right, st, "Expression");
|
9336 | c(node.body, st, "Statement");
|
9337 | };
|
9338 | base$1.ForInit = function (node, st, c) {
|
9339 | if (node.type === "VariableDeclaration") { c(node, st); }
|
9340 | else { c(node, st, "Expression"); }
|
9341 | };
|
9342 | base$1.DebuggerStatement = ignore;
|
9343 |
|
9344 | base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
9345 | base$1.VariableDeclaration = function (node, st, c) {
|
9346 | for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
9347 | {
|
9348 | var decl = list[i];
|
9349 |
|
9350 | c(decl, st);
|
9351 | }
|
9352 | };
|
9353 | base$1.VariableDeclarator = function (node, st, c) {
|
9354 | c(node.id, st, "Pattern");
|
9355 | if (node.init) { c(node.init, st, "Expression"); }
|
9356 | };
|
9357 |
|
9358 | base$1.Function = function (node, st, c) {
|
9359 | if (node.id) { c(node.id, st, "Pattern"); }
|
9360 | for (var i = 0, list = node.params; i < list.length; i += 1)
|
9361 | {
|
9362 | var param = list[i];
|
9363 |
|
9364 | c(param, st, "Pattern");
|
9365 | }
|
9366 | c(node.body, st, node.expression ? "Expression" : "Statement");
|
9367 | };
|
9368 |
|
9369 | base$1.Pattern = function (node, st, c) {
|
9370 | if (node.type === "Identifier")
|
9371 | { c(node, st, "VariablePattern"); }
|
9372 | else if (node.type === "MemberExpression")
|
9373 | { c(node, st, "MemberPattern"); }
|
9374 | else
|
9375 | { c(node, st); }
|
9376 | };
|
9377 | base$1.VariablePattern = ignore;
|
9378 | base$1.MemberPattern = skipThrough;
|
9379 | base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
9380 | base$1.ArrayPattern = function (node, st, c) {
|
9381 | for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
9382 | var elt = list[i];
|
9383 |
|
9384 | if (elt) { c(elt, st, "Pattern"); }
|
9385 | }
|
9386 | };
|
9387 | base$1.ObjectPattern = function (node, st, c) {
|
9388 | for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
9389 | var prop = list[i];
|
9390 |
|
9391 | if (prop.type === "Property") {
|
9392 | if (prop.computed) { c(prop.key, st, "Expression"); }
|
9393 | c(prop.value, st, "Pattern");
|
9394 | } else if (prop.type === "RestElement") {
|
9395 | c(prop.argument, st, "Pattern");
|
9396 | }
|
9397 | }
|
9398 | };
|
9399 |
|
9400 | base$1.Expression = skipThrough;
|
9401 | base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
|
9402 | base$1.ArrayExpression = function (node, st, c) {
|
9403 | for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
9404 | var elt = list[i];
|
9405 |
|
9406 | if (elt) { c(elt, st, "Expression"); }
|
9407 | }
|
9408 | };
|
9409 | base$1.ObjectExpression = function (node, st, c) {
|
9410 | for (var i = 0, list = node.properties; i < list.length; i += 1)
|
9411 | {
|
9412 | var prop = list[i];
|
9413 |
|
9414 | c(prop, st);
|
9415 | }
|
9416 | };
|
9417 | base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
|
9418 | base$1.SequenceExpression = function (node, st, c) {
|
9419 | for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
9420 | {
|
9421 | var expr = list[i];
|
9422 |
|
9423 | c(expr, st, "Expression");
|
9424 | }
|
9425 | };
|
9426 | base$1.TemplateLiteral = function (node, st, c) {
|
9427 | for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
9428 | {
|
9429 | var quasi = list[i];
|
9430 |
|
9431 | c(quasi, st);
|
9432 | }
|
9433 |
|
9434 | for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
9435 | {
|
9436 | var expr = list$1[i$1];
|
9437 |
|
9438 | c(expr, st, "Expression");
|
9439 | }
|
9440 | };
|
9441 | base$1.TemplateElement = ignore;
|
9442 | base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
|
9443 | c(node.argument, st, "Expression");
|
9444 | };
|
9445 | base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
|
9446 | c(node.left, st, "Expression");
|
9447 | c(node.right, st, "Expression");
|
9448 | };
|
9449 | base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
|
9450 | c(node.left, st, "Pattern");
|
9451 | c(node.right, st, "Expression");
|
9452 | };
|
9453 | base$1.ConditionalExpression = function (node, st, c) {
|
9454 | c(node.test, st, "Expression");
|
9455 | c(node.consequent, st, "Expression");
|
9456 | c(node.alternate, st, "Expression");
|
9457 | };
|
9458 | base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
|
9459 | c(node.callee, st, "Expression");
|
9460 | if (node.arguments)
|
9461 | { for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
9462 | {
|
9463 | var arg = list[i];
|
9464 |
|
9465 | c(arg, st, "Expression");
|
9466 | } }
|
9467 | };
|
9468 | base$1.MemberExpression = function (node, st, c) {
|
9469 | c(node.object, st, "Expression");
|
9470 | if (node.computed) { c(node.property, st, "Expression"); }
|
9471 | };
|
9472 | base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
|
9473 | if (node.declaration)
|
9474 | { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
9475 | if (node.source) { c(node.source, st, "Expression"); }
|
9476 | };
|
9477 | base$1.ExportAllDeclaration = function (node, st, c) {
|
9478 | if (node.exported)
|
9479 | { c(node.exported, st); }
|
9480 | c(node.source, st, "Expression");
|
9481 | };
|
9482 | base$1.ImportDeclaration = function (node, st, c) {
|
9483 | for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
9484 | {
|
9485 | var spec = list[i];
|
9486 |
|
9487 | c(spec, st);
|
9488 | }
|
9489 | c(node.source, st, "Expression");
|
9490 | };
|
9491 | base$1.ImportExpression = function (node, st, c) {
|
9492 | c(node.source, st, "Expression");
|
9493 | };
|
9494 | base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
|
9495 |
|
9496 | base$1.TaggedTemplateExpression = function (node, st, c) {
|
9497 | c(node.tag, st, "Expression");
|
9498 | c(node.quasi, st, "Expression");
|
9499 | };
|
9500 | base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
9501 | base$1.Class = function (node, st, c) {
|
9502 | if (node.id) { c(node.id, st, "Pattern"); }
|
9503 | if (node.superClass) { c(node.superClass, st, "Expression"); }
|
9504 | c(node.body, st);
|
9505 | };
|
9506 | base$1.ClassBody = function (node, st, c) {
|
9507 | for (var i = 0, list = node.body; i < list.length; i += 1)
|
9508 | {
|
9509 | var elt = list[i];
|
9510 |
|
9511 | c(elt, st);
|
9512 | }
|
9513 | };
|
9514 | base$1.MethodDefinition = base$1.Property = function (node, st, c) {
|
9515 | if (node.computed) { c(node.key, st, "Expression"); }
|
9516 | c(node.value, st, "Expression");
|
9517 | };
|
9518 |
|
9519 |
|
9520 |
|
9521 | base$1.FieldDefinition = function (node, st, c) {
|
9522 | if (node.computed) {
|
9523 | c(node.key, st, 'Expression');
|
9524 | }
|
9525 | if (node.value) {
|
9526 | c(node.value, st, 'Expression');
|
9527 | }
|
9528 | };
|
9529 | function handlePureAnnotationsOfNode(node, state, type = node.type) {
|
9530 | let commentNode = state.commentNodes[state.commentIndex];
|
9531 | while (commentNode && node.start >= commentNode.end) {
|
9532 | markPureNode(node, commentNode);
|
9533 | commentNode = state.commentNodes[++state.commentIndex];
|
9534 | }
|
9535 | if (commentNode && commentNode.end <= node.end) {
|
9536 | base$1[type](node, state, handlePureAnnotationsOfNode);
|
9537 | }
|
9538 | }
|
9539 | function markPureNode(node, comment) {
|
9540 | if (node.annotations) {
|
9541 | node.annotations.push(comment);
|
9542 | }
|
9543 | else {
|
9544 | node.annotations = [comment];
|
9545 | }
|
9546 | if (node.type === 'ExpressionStatement') {
|
9547 | node = node.expression;
|
9548 | }
|
9549 | if (node.type === 'CallExpression' || node.type === 'NewExpression') {
|
9550 | node.annotatedPure = true;
|
9551 | }
|
9552 | }
|
9553 | const pureCommentRegex = /[@#]__PURE__/;
|
9554 | const isPureComment = (comment) => pureCommentRegex.test(comment.text);
|
9555 | function markPureCallExpressions(comments, esTreeAst) {
|
9556 | handlePureAnnotationsOfNode(esTreeAst, {
|
9557 | commentIndex: 0,
|
9558 | commentNodes: comments.filter(isPureComment)
|
9559 | });
|
9560 | }
|
9561 |
|
9562 |
|
9563 |
|
9564 | let SOURCEMAPPING_URL = 'sourceMa';
|
9565 | SOURCEMAPPING_URL += 'ppingURL';
|
9566 | const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
|
9567 |
|
9568 | const NOOP = () => { };
|
9569 | let getStartTime = () => [0, 0];
|
9570 | let getElapsedTime = () => 0;
|
9571 | let getMemory = () => 0;
|
9572 | let timers = {};
|
9573 | const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
|
9574 | function setTimeHelpers() {
|
9575 | if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
|
9576 | getStartTime = process.hrtime.bind(process);
|
9577 | getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
|
9578 | }
|
9579 | else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
|
9580 | getStartTime = () => [performance.now(), 0];
|
9581 | getElapsedTime = previous => performance.now() - previous[0];
|
9582 | }
|
9583 | if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
|
9584 | getMemory = () => process.memoryUsage().heapUsed;
|
9585 | }
|
9586 | }
|
9587 | function getPersistedLabel(label, level) {
|
9588 | switch (level) {
|
9589 | case 1:
|
9590 | return `# ${label}`;
|
9591 | case 2:
|
9592 | return `## ${label}`;
|
9593 | case 3:
|
9594 | return label;
|
9595 | default:
|
9596 | return `${' '.repeat(level - 4)}- ${label}`;
|
9597 | }
|
9598 | }
|
9599 | function timeStartImpl(label, level = 3) {
|
9600 | label = getPersistedLabel(label, level);
|
9601 | if (!timers.hasOwnProperty(label)) {
|
9602 | timers[label] = {
|
9603 | memory: 0,
|
9604 | startMemory: undefined,
|
9605 | startTime: undefined,
|
9606 | time: 0,
|
9607 | totalMemory: 0
|
9608 | };
|
9609 | }
|
9610 | const currentMemory = getMemory();
|
9611 | timers[label].startTime = getStartTime();
|
9612 | timers[label].startMemory = currentMemory;
|
9613 | }
|
9614 | function timeEndImpl(label, level = 3) {
|
9615 | label = getPersistedLabel(label, level);
|
9616 | if (timers.hasOwnProperty(label)) {
|
9617 | const currentMemory = getMemory();
|
9618 | timers[label].time += getElapsedTime(timers[label].startTime);
|
9619 | timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
|
9620 | timers[label].memory += currentMemory - timers[label].startMemory;
|
9621 | }
|
9622 | }
|
9623 | function getTimings() {
|
9624 | const newTimings = {};
|
9625 | for (const label of Object.keys(timers)) {
|
9626 | newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
|
9627 | }
|
9628 | return newTimings;
|
9629 | }
|
9630 | let timeStart = NOOP, timeEnd = NOOP;
|
9631 | const TIMED_PLUGIN_HOOKS = {
|
9632 | load: true,
|
9633 | resolveDynamicImport: true,
|
9634 | resolveId: true,
|
9635 | transform: true
|
9636 | };
|
9637 | function getPluginWithTimers(plugin, index) {
|
9638 | const timedPlugin = {};
|
9639 | for (const hook of Object.keys(plugin)) {
|
9640 | if (TIMED_PLUGIN_HOOKS[hook] === true) {
|
9641 | let timerLabel = `plugin ${index}`;
|
9642 | if (plugin.name) {
|
9643 | timerLabel += ` (${plugin.name})`;
|
9644 | }
|
9645 | timerLabel += ` - ${hook}`;
|
9646 | timedPlugin[hook] = function () {
|
9647 | timeStart(timerLabel, 4);
|
9648 | const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
|
9649 | timeEnd(timerLabel, 4);
|
9650 | if (result && typeof result.then === 'function') {
|
9651 | timeStart(`${timerLabel} (async)`, 4);
|
9652 | result.then(() => timeEnd(`${timerLabel} (async)`, 4));
|
9653 | }
|
9654 | return result;
|
9655 | };
|
9656 | }
|
9657 | else {
|
9658 | timedPlugin[hook] = plugin[hook];
|
9659 | }
|
9660 | }
|
9661 | return timedPlugin;
|
9662 | }
|
9663 | function initialiseTimers(inputOptions) {
|
9664 | if (inputOptions.perf) {
|
9665 | timers = {};
|
9666 | setTimeHelpers();
|
9667 | timeStart = timeStartImpl;
|
9668 | timeEnd = timeEndImpl;
|
9669 | inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
|
9670 | }
|
9671 | else {
|
9672 | timeStart = NOOP;
|
9673 | timeEnd = NOOP;
|
9674 | }
|
9675 | }
|
9676 |
|
9677 | function tryParse(module, Parser, acornOptions) {
|
9678 | try {
|
9679 | return Parser.parse(module.info.code, {
|
9680 | ...acornOptions,
|
9681 | onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
|
9682 | });
|
9683 | }
|
9684 | catch (err) {
|
9685 | let message = err.message.replace(/ \(\d+:\d+\)$/, '');
|
9686 | if (module.id.endsWith('.json')) {
|
9687 | message += ' (Note that you need @rollup/plugin-json to import JSON files)';
|
9688 | }
|
9689 | else if (!module.id.endsWith('.js')) {
|
9690 | message += ' (Note that you need plugins to import files that are not JavaScript)';
|
9691 | }
|
9692 | return module.error({
|
9693 | code: 'PARSE_ERROR',
|
9694 | message,
|
9695 | parserError: err
|
9696 | }, err.pos);
|
9697 | }
|
9698 | }
|
9699 | function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
|
9700 | return importingModule.error({
|
9701 | code: 'MISSING_EXPORT',
|
9702 | message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule.id)}`,
|
9703 | url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
|
9704 | }, importerStart);
|
9705 | }
|
9706 | const MISSING_EXPORT_SHIM_DESCRIPTION = {
|
9707 | identifier: null,
|
9708 | localName: MISSING_EXPORT_SHIM_VARIABLE
|
9709 | };
|
9710 | function getVariableForExportNameRecursive(target, name, isExportAllSearch, searchedNamesAndModules = new Map()) {
|
9711 | const searchedModules = searchedNamesAndModules.get(name);
|
9712 | if (searchedModules) {
|
9713 | if (searchedModules.has(target)) {
|
9714 | return null;
|
9715 | }
|
9716 | searchedModules.add(target);
|
9717 | }
|
9718 | else {
|
9719 | searchedNamesAndModules.set(name, new Set([target]));
|
9720 | }
|
9721 | return target.getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules);
|
9722 | }
|
9723 | class Module {
|
9724 | constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
|
9725 | this.graph = graph;
|
9726 | this.id = id;
|
9727 | this.options = options;
|
9728 | this.ast = null;
|
9729 | this.chunkFileNames = new Set();
|
9730 | this.chunkName = null;
|
9731 | this.comments = [];
|
9732 | this.dependencies = new Set();
|
9733 | this.dynamicDependencies = new Set();
|
9734 | this.dynamicImporters = [];
|
9735 | this.dynamicImports = [];
|
9736 | this.execIndex = Infinity;
|
9737 | this.exportAllSources = new Set();
|
9738 | this.exports = Object.create(null);
|
9739 | this.exportsAll = Object.create(null);
|
9740 | this.implicitlyLoadedAfter = new Set();
|
9741 | this.implicitlyLoadedBefore = new Set();
|
9742 | this.importDescriptions = Object.create(null);
|
9743 | this.importers = [];
|
9744 | this.importMetas = [];
|
9745 | this.imports = new Set();
|
9746 | this.includedDynamicImporters = [];
|
9747 | this.isExecuted = false;
|
9748 | this.isUserDefinedEntryPoint = false;
|
9749 | this.preserveSignature = this.options.preserveEntrySignatures;
|
9750 | this.reexportDescriptions = Object.create(null);
|
9751 | this.sources = new Set();
|
9752 | this.userChunkNames = new Set();
|
9753 | this.usesTopLevelAwait = false;
|
9754 | this.allExportNames = null;
|
9755 | this.exportAllModules = [];
|
9756 | this.exportNamesByVariable = null;
|
9757 | this.exportShimVariable = new ExportShimVariable(this);
|
9758 | this.relevantDependencies = null;
|
9759 | this.syntheticExports = new Map();
|
9760 | this.syntheticNamespace = null;
|
9761 | this.transformDependencies = [];
|
9762 | this.transitiveReexports = null;
|
9763 | this.excludeFromSourcemap = /\0/.test(id);
|
9764 | this.context = options.moduleContext(id);
|
9765 | const module = this;
|
9766 | this.info = {
|
9767 | ast: null,
|
9768 | code: null,
|
9769 | get dynamicallyImportedIds() {
|
9770 | const dynamicallyImportedIds = [];
|
9771 | for (const { resolution } of module.dynamicImports) {
|
9772 | if (resolution instanceof Module || resolution instanceof ExternalModule) {
|
9773 | dynamicallyImportedIds.push(resolution.id);
|
9774 | }
|
9775 | }
|
9776 | return dynamicallyImportedIds;
|
9777 | },
|
9778 | get dynamicImporters() {
|
9779 | return module.dynamicImporters.sort();
|
9780 | },
|
9781 | hasModuleSideEffects,
|
9782 | id,
|
9783 | get implicitlyLoadedAfterOneOf() {
|
9784 | return Array.from(module.implicitlyLoadedAfter, getId);
|
9785 | },
|
9786 | get implicitlyLoadedBefore() {
|
9787 | return Array.from(module.implicitlyLoadedBefore, getId);
|
9788 | },
|
9789 | get importedIds() {
|
9790 | return Array.from(module.sources, source => module.resolvedIds[source].id);
|
9791 | },
|
9792 | get importers() {
|
9793 | return module.importers.sort();
|
9794 | },
|
9795 | isEntry,
|
9796 | isExternal: false,
|
9797 | meta,
|
9798 | syntheticNamedExports
|
9799 | };
|
9800 | }
|
9801 | basename() {
|
9802 | const base = sysPath.basename(this.id);
|
9803 | const ext = sysPath.extname(this.id);
|
9804 | return makeLegal(ext ? base.slice(0, -ext.length) : base);
|
9805 | }
|
9806 | bindReferences() {
|
9807 | this.ast.bind();
|
9808 | }
|
9809 | error(props, pos) {
|
9810 | this.addLocationToLogProps(props, pos);
|
9811 | return error(props);
|
9812 | }
|
9813 | getAllExportNames() {
|
9814 | if (this.allExportNames) {
|
9815 | return this.allExportNames;
|
9816 | }
|
9817 | const allExportNames = (this.allExportNames = new Set());
|
9818 | for (const name of Object.keys(this.exports)) {
|
9819 | allExportNames.add(name);
|
9820 | }
|
9821 | for (const name of Object.keys(this.reexportDescriptions)) {
|
9822 | allExportNames.add(name);
|
9823 | }
|
9824 | for (const module of this.exportAllModules) {
|
9825 | if (module instanceof ExternalModule) {
|
9826 | allExportNames.add(`*${module.id}`);
|
9827 | continue;
|
9828 | }
|
9829 | for (const name of module.getAllExportNames()) {
|
9830 | if (name !== 'default')
|
9831 | allExportNames.add(name);
|
9832 | }
|
9833 | }
|
9834 | return allExportNames;
|
9835 | }
|
9836 | getDependenciesToBeIncluded() {
|
9837 | if (this.relevantDependencies)
|
9838 | return this.relevantDependencies;
|
9839 | const relevantDependencies = new Set();
|
9840 | const additionalSideEffectModules = new Set();
|
9841 | const possibleDependencies = new Set(this.dependencies);
|
9842 | let dependencyVariables = this.imports;
|
9843 | if (this.info.isEntry ||
|
9844 | this.includedDynamicImporters.length > 0 ||
|
9845 | this.namespace.included ||
|
9846 | this.implicitlyLoadedAfter.size > 0) {
|
9847 | dependencyVariables = new Set(dependencyVariables);
|
9848 | for (const exportName of [...this.getReexports(), ...this.getExports()]) {
|
9849 | dependencyVariables.add(this.getVariableForExportName(exportName));
|
9850 | }
|
9851 | }
|
9852 | for (let variable of dependencyVariables) {
|
9853 | if (variable instanceof SyntheticNamedExportVariable) {
|
9854 | variable = variable.getBaseVariable();
|
9855 | }
|
9856 | else if (variable instanceof ExportDefaultVariable) {
|
9857 | const { modules, original } = variable.getOriginalVariableAndDeclarationModules();
|
9858 | variable = original;
|
9859 | for (const module of modules) {
|
9860 | additionalSideEffectModules.add(module);
|
9861 | possibleDependencies.add(module);
|
9862 | }
|
9863 | }
|
9864 | relevantDependencies.add(variable.module);
|
9865 | }
|
9866 | if (this.options.treeshake && this.info.hasModuleSideEffects !== 'no-treeshake') {
|
9867 | for (const dependency of possibleDependencies) {
|
9868 | if (!(dependency.info.hasModuleSideEffects ||
|
9869 | additionalSideEffectModules.has(dependency)) ||
|
9870 | relevantDependencies.has(dependency)) {
|
9871 | continue;
|
9872 | }
|
9873 | if (dependency instanceof ExternalModule || dependency.hasEffects()) {
|
9874 | relevantDependencies.add(dependency);
|
9875 | }
|
9876 | else {
|
9877 | for (const transitiveDependency of dependency.dependencies) {
|
9878 | possibleDependencies.add(transitiveDependency);
|
9879 | }
|
9880 | }
|
9881 | }
|
9882 | }
|
9883 | else {
|
9884 | for (const dependency of this.dependencies) {
|
9885 | relevantDependencies.add(dependency);
|
9886 | }
|
9887 | }
|
9888 | return (this.relevantDependencies = relevantDependencies);
|
9889 | }
|
9890 | getExportNamesByVariable() {
|
9891 | if (this.exportNamesByVariable) {
|
9892 | return this.exportNamesByVariable;
|
9893 | }
|
9894 | const exportNamesByVariable = new Map();
|
9895 | for (const exportName of this.getAllExportNames()) {
|
9896 | if (exportName === this.info.syntheticNamedExports)
|
9897 | continue;
|
9898 | let tracedVariable = this.getVariableForExportName(exportName);
|
9899 | if (tracedVariable instanceof ExportDefaultVariable) {
|
9900 | tracedVariable = tracedVariable.getOriginalVariable();
|
9901 | }
|
9902 | if (!tracedVariable ||
|
9903 | !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
|
9904 | continue;
|
9905 | }
|
9906 | const existingExportNames = exportNamesByVariable.get(tracedVariable);
|
9907 | if (existingExportNames) {
|
9908 | existingExportNames.push(exportName);
|
9909 | }
|
9910 | else {
|
9911 | exportNamesByVariable.set(tracedVariable, [exportName]);
|
9912 | }
|
9913 | }
|
9914 | return (this.exportNamesByVariable = exportNamesByVariable);
|
9915 | }
|
9916 | getExports() {
|
9917 | return Object.keys(this.exports);
|
9918 | }
|
9919 | getReexports() {
|
9920 | if (this.transitiveReexports) {
|
9921 | return this.transitiveReexports;
|
9922 | }
|
9923 |
|
9924 | this.transitiveReexports = [];
|
9925 | const reexports = new Set();
|
9926 | for (const name in this.reexportDescriptions) {
|
9927 | reexports.add(name);
|
9928 | }
|
9929 | for (const module of this.exportAllModules) {
|
9930 | if (module instanceof ExternalModule) {
|
9931 | reexports.add(`*${module.id}`);
|
9932 | }
|
9933 | else {
|
9934 | for (const name of [...module.getReexports(), ...module.getExports()]) {
|
9935 | if (name !== 'default')
|
9936 | reexports.add(name);
|
9937 | }
|
9938 | }
|
9939 | }
|
9940 | return (this.transitiveReexports = [...reexports]);
|
9941 | }
|
9942 | getRenderedExports() {
|
9943 |
|
9944 | const renderedExports = [];
|
9945 | const removedExports = [];
|
9946 | for (const exportName in this.exports) {
|
9947 | const variable = this.getVariableForExportName(exportName);
|
9948 | (variable && variable.included ? renderedExports : removedExports).push(exportName);
|
9949 | }
|
9950 | return { renderedExports, removedExports };
|
9951 | }
|
9952 | getSyntheticNamespace() {
|
9953 | if (this.syntheticNamespace === null) {
|
9954 | this.syntheticNamespace = undefined;
|
9955 | this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
|
9956 | ? this.info.syntheticNamedExports
|
9957 | : 'default');
|
9958 | }
|
9959 | if (!this.syntheticNamespace) {
|
9960 | return error({
|
9961 | code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
|
9962 | id: this.id,
|
9963 | message: `Module "${relativeId(this.id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(this.info.syntheticNamedExports)}' needs ${typeof this.info.syntheticNamedExports === 'string' &&
|
9964 | this.info.syntheticNamedExports !== 'default'
|
9965 | ? `an export named "${this.info.syntheticNamedExports}"`
|
9966 | : 'a default export'}.`
|
9967 | });
|
9968 | }
|
9969 | return this.syntheticNamespace;
|
9970 | }
|
9971 | getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules) {
|
9972 | if (name[0] === '*') {
|
9973 | if (name.length === 1) {
|
9974 | return this.namespace;
|
9975 | }
|
9976 | else {
|
9977 |
|
9978 | const module = this.graph.modulesById.get(name.slice(1));
|
9979 | return module.getVariableForExportName('*');
|
9980 | }
|
9981 | }
|
9982 |
|
9983 | const reexportDeclaration = this.reexportDescriptions[name];
|
9984 | if (reexportDeclaration) {
|
9985 | const declaration = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, false, searchedNamesAndModules);
|
9986 | if (!declaration) {
|
9987 | return handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
|
9988 | }
|
9989 | return declaration;
|
9990 | }
|
9991 | const exportDeclaration = this.exports[name];
|
9992 | if (exportDeclaration) {
|
9993 | if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
|
9994 | return this.exportShimVariable;
|
9995 | }
|
9996 | const name = exportDeclaration.localName;
|
9997 | return this.traceVariable(name);
|
9998 | }
|
9999 | if (name !== 'default') {
|
10000 | for (const module of this.exportAllModules) {
|
10001 | const declaration = getVariableForExportNameRecursive(module, name, true, searchedNamesAndModules);
|
10002 | if (declaration)
|
10003 | return declaration;
|
10004 | }
|
10005 | }
|
10006 |
|
10007 |
|
10008 | if (!isExportAllSearch) {
|
10009 | if (this.info.syntheticNamedExports) {
|
10010 | let syntheticExport = this.syntheticExports.get(name);
|
10011 | if (!syntheticExport) {
|
10012 | const syntheticNamespace = this.getSyntheticNamespace();
|
10013 | syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
|
10014 | this.syntheticExports.set(name, syntheticExport);
|
10015 | return syntheticExport;
|
10016 | }
|
10017 | return syntheticExport;
|
10018 | }
|
10019 | if (this.options.shimMissingExports) {
|
10020 | this.shimMissingExport(name);
|
10021 | return this.exportShimVariable;
|
10022 | }
|
10023 | }
|
10024 | return null;
|
10025 | }
|
10026 | hasEffects() {
|
10027 | return (this.info.hasModuleSideEffects === 'no-treeshake' ||
|
10028 | (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
|
10029 | }
|
10030 | include() {
|
10031 | const context = createInclusionContext();
|
10032 | if (this.ast.shouldBeIncluded(context))
|
10033 | this.ast.include(context, false);
|
10034 | }
|
10035 | includeAllExports(includeNamespaceMembers) {
|
10036 | if (!this.isExecuted) {
|
10037 | this.graph.needsTreeshakingPass = true;
|
10038 | markModuleAndImpureDependenciesAsExecuted(this);
|
10039 | }
|
10040 | for (const exportName of this.getExports()) {
|
10041 | if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
|
10042 | const variable = this.getVariableForExportName(exportName);
|
10043 | variable.deoptimizePath(UNKNOWN_PATH);
|
10044 | if (!variable.included) {
|
10045 | variable.include();
|
10046 | this.graph.needsTreeshakingPass = true;
|
10047 | }
|
10048 | }
|
10049 | }
|
10050 | for (const name of this.getReexports()) {
|
10051 | const variable = this.getVariableForExportName(name);
|
10052 | variable.deoptimizePath(UNKNOWN_PATH);
|
10053 | if (!variable.included) {
|
10054 | variable.include();
|
10055 | this.graph.needsTreeshakingPass = true;
|
10056 | }
|
10057 | if (variable instanceof ExternalVariable) {
|
10058 | variable.module.reexported = true;
|
10059 | }
|
10060 | }
|
10061 | if (includeNamespaceMembers) {
|
10062 | this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
|
10063 | }
|
10064 | }
|
10065 | includeAllInBundle() {
|
10066 | this.ast.include(createInclusionContext(), true);
|
10067 | }
|
10068 | isIncluded() {
|
10069 | return this.ast.included || this.namespace.included;
|
10070 | }
|
10071 | linkImports() {
|
10072 | this.addModulesToImportDescriptions(this.importDescriptions);
|
10073 | this.addModulesToImportDescriptions(this.reexportDescriptions);
|
10074 | for (const name in this.exports) {
|
10075 | if (name !== 'default') {
|
10076 | this.exportsAll[name] = this.id;
|
10077 | }
|
10078 | }
|
10079 | const externalExportAllModules = [];
|
10080 | for (const source of this.exportAllSources) {
|
10081 | const module = this.graph.modulesById.get(this.resolvedIds[source].id);
|
10082 | if (module instanceof ExternalModule) {
|
10083 | externalExportAllModules.push(module);
|
10084 | continue;
|
10085 | }
|
10086 | this.exportAllModules.push(module);
|
10087 | for (const name in module.exportsAll) {
|
10088 | if (name in this.exportsAll) {
|
10089 | this.options.onwarn(errNamespaceConflict(name, this, module));
|
10090 | }
|
10091 | else {
|
10092 | this.exportsAll[name] = module.exportsAll[name];
|
10093 | }
|
10094 | }
|
10095 | }
|
10096 | this.exportAllModules.push(...externalExportAllModules);
|
10097 | }
|
10098 | render(options) {
|
10099 | const magicString = this.magicString.clone();
|
10100 | this.ast.render(magicString, options);
|
10101 | this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
|
10102 | return magicString;
|
10103 | }
|
10104 | setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
|
10105 | this.info.code = code;
|
10106 | this.originalCode = originalCode;
|
10107 | this.originalSourcemap = originalSourcemap;
|
10108 | this.sourcemapChain = sourcemapChain;
|
10109 | if (transformFiles) {
|
10110 | this.transformFiles = transformFiles;
|
10111 | }
|
10112 | this.transformDependencies = transformDependencies;
|
10113 | this.customTransformCache = customTransformCache;
|
10114 | this.updateOptions(moduleOptions);
|
10115 | timeStart('generate ast', 3);
|
10116 | this.alwaysRemovedCode = alwaysRemovedCode || [];
|
10117 | if (!ast) {
|
10118 | ast = tryParse(this, this.graph.acornParser, this.options.acorn);
|
10119 | for (const comment of this.comments) {
|
10120 | if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
|
10121 | this.alwaysRemovedCode.push([comment.start, comment.end]);
|
10122 | }
|
10123 | }
|
10124 | markPureCallExpressions(this.comments, ast);
|
10125 | }
|
10126 | timeEnd('generate ast', 3);
|
10127 | this.resolvedIds = resolvedIds || Object.create(null);
|
10128 |
|
10129 |
|
10130 | const fileName = this.id;
|
10131 | this.magicString = new MagicString(code, {
|
10132 | filename: (this.excludeFromSourcemap ? null : fileName),
|
10133 | indentExclusionRanges: []
|
10134 | });
|
10135 | for (const [start, end] of this.alwaysRemovedCode) {
|
10136 | this.magicString.remove(start, end);
|
10137 | }
|
10138 | timeStart('analyse ast', 3);
|
10139 | this.astContext = {
|
10140 | addDynamicImport: this.addDynamicImport.bind(this),
|
10141 | addExport: this.addExport.bind(this),
|
10142 | addImport: this.addImport.bind(this),
|
10143 | addImportMeta: this.addImportMeta.bind(this),
|
10144 | code,
|
10145 | deoptimizationTracker: this.graph.deoptimizationTracker,
|
10146 | error: this.error.bind(this),
|
10147 | fileName,
|
10148 | getExports: this.getExports.bind(this),
|
10149 | getModuleExecIndex: () => this.execIndex,
|
10150 | getModuleName: this.basename.bind(this),
|
10151 | getReexports: this.getReexports.bind(this),
|
10152 | importDescriptions: this.importDescriptions,
|
10153 | includeAllExports: () => this.includeAllExports(true),
|
10154 | includeDynamicImport: this.includeDynamicImport.bind(this),
|
10155 | includeVariable: this.includeVariable.bind(this),
|
10156 | magicString: this.magicString,
|
10157 | module: this,
|
10158 | moduleContext: this.context,
|
10159 | nodeConstructors,
|
10160 | options: this.options,
|
10161 | traceExport: this.getVariableForExportName.bind(this),
|
10162 | traceVariable: this.traceVariable.bind(this),
|
10163 | usesTopLevelAwait: false,
|
10164 | warn: this.warn.bind(this)
|
10165 | };
|
10166 | this.scope = new ModuleScope(this.graph.scope, this.astContext);
|
10167 | this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
|
10168 | this.ast = new Program$1(ast, { type: 'Module', context: this.astContext }, this.scope);
|
10169 | this.info.ast = ast;
|
10170 | timeEnd('analyse ast', 3);
|
10171 | }
|
10172 | toJSON() {
|
10173 | return {
|
10174 | alwaysRemovedCode: this.alwaysRemovedCode,
|
10175 | ast: this.ast.esTreeNode,
|
10176 | code: this.info.code,
|
10177 | customTransformCache: this.customTransformCache,
|
10178 | dependencies: Array.from(this.dependencies, getId),
|
10179 | id: this.id,
|
10180 | meta: this.info.meta,
|
10181 | moduleSideEffects: this.info.hasModuleSideEffects,
|
10182 | originalCode: this.originalCode,
|
10183 | originalSourcemap: this.originalSourcemap,
|
10184 | resolvedIds: this.resolvedIds,
|
10185 | sourcemapChain: this.sourcemapChain,
|
10186 | syntheticNamedExports: this.info.syntheticNamedExports,
|
10187 | transformDependencies: this.transformDependencies,
|
10188 | transformFiles: this.transformFiles
|
10189 | };
|
10190 | }
|
10191 | traceVariable(name) {
|
10192 | const localVariable = this.scope.variables.get(name);
|
10193 | if (localVariable) {
|
10194 | return localVariable;
|
10195 | }
|
10196 | if (name in this.importDescriptions) {
|
10197 | const importDeclaration = this.importDescriptions[name];
|
10198 | const otherModule = importDeclaration.module;
|
10199 | if (otherModule instanceof Module && importDeclaration.name === '*') {
|
10200 | return otherModule.namespace;
|
10201 | }
|
10202 | const declaration = otherModule.getVariableForExportName(importDeclaration.name);
|
10203 | if (!declaration) {
|
10204 | return handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
|
10205 | }
|
10206 | return declaration;
|
10207 | }
|
10208 | return null;
|
10209 | }
|
10210 | updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
|
10211 | if (moduleSideEffects != null) {
|
10212 | this.info.hasModuleSideEffects = moduleSideEffects;
|
10213 | }
|
10214 | if (syntheticNamedExports != null) {
|
10215 | this.info.syntheticNamedExports = syntheticNamedExports;
|
10216 | }
|
10217 | if (meta != null) {
|
10218 | this.info.meta = { ...this.info.meta, ...meta };
|
10219 | }
|
10220 | }
|
10221 | warn(props, pos) {
|
10222 | this.addLocationToLogProps(props, pos);
|
10223 | this.options.onwarn(props);
|
10224 | }
|
10225 | addDynamicImport(node) {
|
10226 | let argument = node.source;
|
10227 | if (argument instanceof TemplateLiteral) {
|
10228 | if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
|
10229 | argument = argument.quasis[0].value.cooked;
|
10230 | }
|
10231 | }
|
10232 | else if (argument instanceof Literal && typeof argument.value === 'string') {
|
10233 | argument = argument.value;
|
10234 | }
|
10235 | this.dynamicImports.push({ node, resolution: null, argument });
|
10236 | }
|
10237 | addExport(node) {
|
10238 | if (node instanceof ExportDefaultDeclaration) {
|
10239 |
|
10240 | this.exports.default = {
|
10241 | identifier: node.variable.getAssignedVariableName(),
|
10242 | localName: 'default'
|
10243 | };
|
10244 | }
|
10245 | else if (node instanceof ExportAllDeclaration) {
|
10246 | const source = node.source.value;
|
10247 | this.sources.add(source);
|
10248 | if (node.exported) {
|
10249 |
|
10250 | const name = node.exported.name;
|
10251 | this.reexportDescriptions[name] = {
|
10252 | localName: '*',
|
10253 | module: null,
|
10254 | source,
|
10255 | start: node.start
|
10256 | };
|
10257 | }
|
10258 | else {
|
10259 |
|
10260 | this.exportAllSources.add(source);
|
10261 | }
|
10262 | }
|
10263 | else if (node.source instanceof Literal) {
|
10264 |
|
10265 | const source = node.source.value;
|
10266 | this.sources.add(source);
|
10267 | for (const specifier of node.specifiers) {
|
10268 | const name = specifier.exported.name;
|
10269 | this.reexportDescriptions[name] = {
|
10270 | localName: specifier.local.name,
|
10271 | module: null,
|
10272 | source,
|
10273 | start: specifier.start
|
10274 | };
|
10275 | }
|
10276 | }
|
10277 | else if (node.declaration) {
|
10278 | const declaration = node.declaration;
|
10279 | if (declaration instanceof VariableDeclaration) {
|
10280 |
|
10281 |
|
10282 | for (const declarator of declaration.declarations) {
|
10283 | for (const localName of extractAssignedNames(declarator.id)) {
|
10284 | this.exports[localName] = { identifier: null, localName };
|
10285 | }
|
10286 | }
|
10287 | }
|
10288 | else {
|
10289 |
|
10290 | const localName = declaration.id.name;
|
10291 | this.exports[localName] = { identifier: null, localName };
|
10292 | }
|
10293 | }
|
10294 | else {
|
10295 |
|
10296 | for (const specifier of node.specifiers) {
|
10297 | const localName = specifier.local.name;
|
10298 | const exportedName = specifier.exported.name;
|
10299 | this.exports[exportedName] = { identifier: null, localName };
|
10300 | }
|
10301 | }
|
10302 | }
|
10303 | addImport(node) {
|
10304 | const source = node.source.value;
|
10305 | this.sources.add(source);
|
10306 | for (const specifier of node.specifiers) {
|
10307 | const isDefault = specifier.type === ImportDefaultSpecifier;
|
10308 | const isNamespace = specifier.type === ImportNamespaceSpecifier;
|
10309 | const name = isDefault
|
10310 | ? 'default'
|
10311 | : isNamespace
|
10312 | ? '*'
|
10313 | : specifier.imported.name;
|
10314 | this.importDescriptions[specifier.local.name] = {
|
10315 | module: null,
|
10316 | name,
|
10317 | source,
|
10318 | start: specifier.start
|
10319 | };
|
10320 | }
|
10321 | }
|
10322 | addImportMeta(node) {
|
10323 | this.importMetas.push(node);
|
10324 | }
|
10325 | addLocationToLogProps(props, pos) {
|
10326 | props.id = this.id;
|
10327 | props.pos = pos;
|
10328 | let code = this.info.code;
|
10329 | let { column, line } = locate(code, pos, { offsetLine: 1 });
|
10330 | try {
|
10331 | ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
|
10332 | code = this.originalCode;
|
10333 | }
|
10334 | catch (e) {
|
10335 | this.options.onwarn({
|
10336 | code: 'SOURCEMAP_ERROR',
|
10337 | id: this.id,
|
10338 | loc: {
|
10339 | column,
|
10340 | file: this.id,
|
10341 | line
|
10342 | },
|
10343 | message: `Error when using sourcemap for reporting an error: ${e.message}`,
|
10344 | pos
|
10345 | });
|
10346 | }
|
10347 | augmentCodeLocation(props, { column, line }, code, this.id);
|
10348 | }
|
10349 | addModulesToImportDescriptions(importDescription) {
|
10350 | for (const name of Object.keys(importDescription)) {
|
10351 | const specifier = importDescription[name];
|
10352 | const id = this.resolvedIds[specifier.source].id;
|
10353 | specifier.module = this.graph.modulesById.get(id);
|
10354 | }
|
10355 | }
|
10356 | includeAndGetAdditionalMergedNamespaces() {
|
10357 | const mergedNamespaces = [];
|
10358 | for (const module of this.exportAllModules) {
|
10359 | if (module instanceof ExternalModule) {
|
10360 | const externalVariable = module.getVariableForExportName('*');
|
10361 | externalVariable.include();
|
10362 | this.imports.add(externalVariable);
|
10363 | mergedNamespaces.push(externalVariable);
|
10364 | }
|
10365 | else if (module.info.syntheticNamedExports) {
|
10366 | const syntheticNamespace = module.getSyntheticNamespace();
|
10367 | syntheticNamespace.include();
|
10368 | this.imports.add(syntheticNamespace);
|
10369 | mergedNamespaces.push(syntheticNamespace);
|
10370 | }
|
10371 | }
|
10372 | return mergedNamespaces;
|
10373 | }
|
10374 | includeDynamicImport(node) {
|
10375 | const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
|
10376 | if (resolution instanceof Module) {
|
10377 | resolution.includedDynamicImporters.push(this);
|
10378 | resolution.includeAllExports(true);
|
10379 | }
|
10380 | }
|
10381 | includeVariable(variable) {
|
10382 | const variableModule = variable.module;
|
10383 | if (!variable.included) {
|
10384 | variable.include();
|
10385 | this.graph.needsTreeshakingPass = true;
|
10386 | }
|
10387 | if (variableModule && variableModule !== this) {
|
10388 | this.imports.add(variable);
|
10389 | }
|
10390 | }
|
10391 | shimMissingExport(name) {
|
10392 | this.options.onwarn({
|
10393 | code: 'SHIMMED_EXPORT',
|
10394 | exporter: relativeId(this.id),
|
10395 | exportName: name,
|
10396 | message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
|
10397 | });
|
10398 | this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
|
10399 | }
|
10400 | }
|
10401 |
|
10402 | class Source {
|
10403 | constructor(filename, content) {
|
10404 | this.isOriginal = true;
|
10405 | this.filename = filename;
|
10406 | this.content = content;
|
10407 | }
|
10408 | traceSegment(line, column, name) {
|
10409 | return { line, column, name, source: this };
|
10410 | }
|
10411 | }
|
10412 | class Link {
|
10413 | constructor(map, sources) {
|
10414 | this.sources = sources;
|
10415 | this.names = map.names;
|
10416 | this.mappings = map.mappings;
|
10417 | }
|
10418 | traceMappings() {
|
10419 | const sources = [];
|
10420 | const sourcesContent = [];
|
10421 | const names = [];
|
10422 | const mappings = [];
|
10423 | for (const line of this.mappings) {
|
10424 | const tracedLine = [];
|
10425 | for (const segment of line) {
|
10426 | if (segment.length == 1)
|
10427 | continue;
|
10428 | const source = this.sources[segment[1]];
|
10429 | if (!source)
|
10430 | continue;
|
10431 | const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
|
10432 | if (traced) {
|
10433 |
|
10434 | let sourceIndex = sources.lastIndexOf(traced.source.filename);
|
10435 | if (sourceIndex === -1) {
|
10436 | sourceIndex = sources.length;
|
10437 | sources.push(traced.source.filename);
|
10438 | sourcesContent[sourceIndex] = traced.source.content;
|
10439 | }
|
10440 | else if (sourcesContent[sourceIndex] == null) {
|
10441 | sourcesContent[sourceIndex] = traced.source.content;
|
10442 | }
|
10443 | else if (traced.source.content != null &&
|
10444 | sourcesContent[sourceIndex] !== traced.source.content) {
|
10445 | return error({
|
10446 | message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
|
10447 | });
|
10448 | }
|
10449 | const tracedSegment = [
|
10450 | segment[0],
|
10451 | sourceIndex,
|
10452 | traced.line,
|
10453 | traced.column
|
10454 | ];
|
10455 | if (traced.name) {
|
10456 | let nameIndex = names.indexOf(traced.name);
|
10457 | if (nameIndex === -1) {
|
10458 | nameIndex = names.length;
|
10459 | names.push(traced.name);
|
10460 | }
|
10461 | tracedSegment[4] = nameIndex;
|
10462 | }
|
10463 | tracedLine.push(tracedSegment);
|
10464 | }
|
10465 | }
|
10466 | mappings.push(tracedLine);
|
10467 | }
|
10468 | return { sources, sourcesContent, names, mappings };
|
10469 | }
|
10470 | traceSegment(line, column, name) {
|
10471 | const segments = this.mappings[line];
|
10472 | if (!segments)
|
10473 | return null;
|
10474 |
|
10475 | let i = 0;
|
10476 | let j = segments.length - 1;
|
10477 | while (i <= j) {
|
10478 | const m = (i + j) >> 1;
|
10479 | const segment = segments[m];
|
10480 | if (segment[0] === column) {
|
10481 | if (segment.length == 1)
|
10482 | return null;
|
10483 | const source = this.sources[segment[1]];
|
10484 | if (!source)
|
10485 | return null;
|
10486 | return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
|
10487 | }
|
10488 | if (segment[0] > column) {
|
10489 | j = m - 1;
|
10490 | }
|
10491 | else {
|
10492 | i = m + 1;
|
10493 | }
|
10494 | }
|
10495 | return null;
|
10496 | }
|
10497 | }
|
10498 | function getLinkMap(warn) {
|
10499 | return function linkMap(source, map) {
|
10500 | if (map.mappings) {
|
10501 | return new Link(map, [source]);
|
10502 | }
|
10503 | warn({
|
10504 | code: 'SOURCEMAP_BROKEN',
|
10505 | message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
|
10506 | "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
|
10507 | 'documentation for help',
|
10508 | plugin: map.plugin,
|
10509 | url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
|
10510 | });
|
10511 | return new Link({
|
10512 | mappings: [],
|
10513 | names: []
|
10514 | }, [source]);
|
10515 | };
|
10516 | }
|
10517 | function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
|
10518 | let source;
|
10519 | if (!originalSourcemap) {
|
10520 | source = new Source(id, originalCode);
|
10521 | }
|
10522 | else {
|
10523 | const sources = originalSourcemap.sources;
|
10524 | const sourcesContent = originalSourcemap.sourcesContent || [];
|
10525 | const directory = sysPath.dirname(id) || '.';
|
10526 | const sourceRoot = originalSourcemap.sourceRoot || '.';
|
10527 | const baseSources = sources.map((source, i) => new Source(sysPath.resolve(directory, sourceRoot, source), sourcesContent[i]));
|
10528 | source = new Link(originalSourcemap, baseSources);
|
10529 | }
|
10530 | return sourcemapChain.reduce(linkMap, source);
|
10531 | }
|
10532 | function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
|
10533 | const linkMap = getLinkMap(warn);
|
10534 | const moduleSources = modules
|
10535 | .filter(module => !module.excludeFromSourcemap)
|
10536 | .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
|
10537 |
|
10538 |
|
10539 | let source = new Link(map, moduleSources);
|
10540 | source = bundleSourcemapChain.reduce(linkMap, source);
|
10541 | let { sources, sourcesContent, names, mappings } = source.traceMappings();
|
10542 | if (file) {
|
10543 | const directory = sysPath.dirname(file);
|
10544 | sources = sources.map((source) => sysPath.relative(directory, source));
|
10545 | file = sysPath.basename(file);
|
10546 | }
|
10547 | sourcesContent = (excludeContent ? null : sourcesContent);
|
10548 | return new SourceMap({ file, sources, sourcesContent, names, mappings });
|
10549 | }
|
10550 | function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
|
10551 | if (!sourcemapChain.length) {
|
10552 | return originalSourcemap;
|
10553 | }
|
10554 | const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
|
10555 | const map = source.traceMappings();
|
10556 | return { version: 3, ...map };
|
10557 | }
|
10558 |
|
10559 | const createHash = () => crypto.createHash('sha256');
|
10560 |
|
10561 | const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
|
10562 | amd: deconflictImportsOther,
|
10563 | cjs: deconflictImportsOther,
|
10564 | es: deconflictImportsEsmOrSystem,
|
10565 | iife: deconflictImportsOther,
|
10566 | system: deconflictImportsEsmOrSystem,
|
10567 | umd: deconflictImportsOther
|
10568 | };
|
10569 | function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
|
10570 | for (const module of modules) {
|
10571 | module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
|
10572 | }
|
10573 | deconflictTopLevelVariables(usedNames, modules, includedNamespaces);
|
10574 | DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
|
10575 | for (const module of modules) {
|
10576 | module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
|
10577 | }
|
10578 | }
|
10579 | function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
|
10580 |
|
10581 | for (const dependency of dependenciesToBeDeconflicted.dependencies) {
|
10582 | if (preserveModules || dependency instanceof ExternalModule) {
|
10583 | dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
|
10584 | }
|
10585 | }
|
10586 | for (const variable of imports) {
|
10587 | const module = variable.module;
|
10588 | const name = variable.name;
|
10589 | if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
|
10590 | variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
|
10591 | }
|
10592 | else if (module instanceof ExternalModule && name === 'default') {
|
10593 | variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
|
10594 | ? module.suggestedVariableName + '__default'
|
10595 | : module.suggestedVariableName, usedNames));
|
10596 | }
|
10597 | else {
|
10598 | variable.setRenderNames(null, getSafeName(name, usedNames));
|
10599 | }
|
10600 | }
|
10601 | for (const variable of syntheticExports) {
|
10602 | variable.setRenderNames(null, getSafeName(variable.name, usedNames));
|
10603 | }
|
10604 | }
|
10605 | function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
|
10606 | for (const chunkOrExternalModule of dependencies) {
|
10607 | chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
|
10608 | }
|
10609 | for (const externalModuleOrChunk of deconflictedNamespace) {
|
10610 | externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
|
10611 | }
|
10612 | for (const externalModule of deconflictedDefault) {
|
10613 | if (deconflictedNamespace.has(externalModule) &&
|
10614 | canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
|
10615 | externalModule.defaultVariableName = externalModule.namespaceVariableName;
|
10616 | }
|
10617 | else {
|
10618 | externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
|
10619 | }
|
10620 | }
|
10621 | for (const variable of imports) {
|
10622 | const module = variable.module;
|
10623 | if (module instanceof ExternalModule) {
|
10624 | const name = variable.name;
|
10625 | if (name === 'default') {
|
10626 | const moduleInterop = String(interop(module.id));
|
10627 | const variableName = defaultInteropHelpersByInteropType[moduleInterop]
|
10628 | ? module.defaultVariableName
|
10629 | : module.variableName;
|
10630 | if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
|
10631 | variable.setRenderNames(variableName, 'default');
|
10632 | }
|
10633 | else {
|
10634 | variable.setRenderNames(null, variableName);
|
10635 | }
|
10636 | }
|
10637 | else if (name === '*') {
|
10638 | variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
|
10639 | ? module.namespaceVariableName
|
10640 | : module.variableName);
|
10641 | }
|
10642 | else {
|
10643 |
|
10644 | variable.setRenderNames(module.variableName, null);
|
10645 | }
|
10646 | }
|
10647 | else {
|
10648 | const chunk = chunkByModule.get(module);
|
10649 | if (preserveModules && variable.isNamespace) {
|
10650 | variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
|
10651 | }
|
10652 | else if (chunk.exportMode === 'default') {
|
10653 | variable.setRenderNames(null, chunk.variableName);
|
10654 | }
|
10655 | else {
|
10656 | variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
|
10657 | }
|
10658 | }
|
10659 | }
|
10660 | }
|
10661 | function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
|
10662 | for (const module of modules) {
|
10663 | for (const variable of module.scope.variables.values()) {
|
10664 | if (variable.included &&
|
10665 |
|
10666 | !(variable.renderBaseName ||
|
10667 | (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
|
10668 | variable.setRenderNames(null, getSafeName(variable.name, usedNames));
|
10669 | }
|
10670 | }
|
10671 | if (includedNamespaces.has(module)) {
|
10672 | const namespace = module.namespace;
|
10673 | namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
|
10674 | }
|
10675 | }
|
10676 | }
|
10677 |
|
10678 | const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
|
10679 | const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
|
10680 | const backSlashRegEx = /\\/g;
|
10681 | function escapeId(id) {
|
10682 | if (!id.match(needsEscapeRegEx))
|
10683 | return id;
|
10684 | return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
|
10685 | }
|
10686 |
|
10687 | const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
|
10688 | function sortByExecutionOrder(units) {
|
10689 | units.sort(compareExecIndex);
|
10690 | }
|
10691 | function analyseModuleExecution(entryModules) {
|
10692 | let nextExecIndex = 0;
|
10693 | const cyclePaths = [];
|
10694 | const analysedModules = new Set();
|
10695 | const dynamicImports = new Set();
|
10696 | const parents = new Map();
|
10697 | const orderedModules = [];
|
10698 | const analyseModule = (module) => {
|
10699 | if (module instanceof Module) {
|
10700 | for (const dependency of module.dependencies) {
|
10701 | if (parents.has(dependency)) {
|
10702 | if (!analysedModules.has(dependency)) {
|
10703 | cyclePaths.push(getCyclePath(dependency, module, parents));
|
10704 | }
|
10705 | continue;
|
10706 | }
|
10707 | parents.set(dependency, module);
|
10708 | analyseModule(dependency);
|
10709 | }
|
10710 | for (const dependency of module.implicitlyLoadedBefore) {
|
10711 | dynamicImports.add(dependency);
|
10712 | }
|
10713 | for (const { resolution } of module.dynamicImports) {
|
10714 | if (resolution instanceof Module) {
|
10715 | dynamicImports.add(resolution);
|
10716 | }
|
10717 | }
|
10718 | orderedModules.push(module);
|
10719 | }
|
10720 | module.execIndex = nextExecIndex++;
|
10721 | analysedModules.add(module);
|
10722 | };
|
10723 | for (const curEntry of entryModules) {
|
10724 | if (!parents.has(curEntry)) {
|
10725 | parents.set(curEntry, null);
|
10726 | analyseModule(curEntry);
|
10727 | }
|
10728 | }
|
10729 | for (const curEntry of dynamicImports) {
|
10730 | if (!parents.has(curEntry)) {
|
10731 | parents.set(curEntry, null);
|
10732 | analyseModule(curEntry);
|
10733 | }
|
10734 | }
|
10735 | return { orderedModules, cyclePaths };
|
10736 | }
|
10737 | function getCyclePath(module, parent, parents) {
|
10738 | const path = [relativeId(module.id)];
|
10739 | let nextModule = parent;
|
10740 | while (nextModule !== module) {
|
10741 | path.push(relativeId(nextModule.id));
|
10742 | nextModule = parents.get(nextModule);
|
10743 | }
|
10744 | path.push(path[0]);
|
10745 | path.reverse();
|
10746 | return path;
|
10747 | }
|
10748 |
|
10749 | function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
|
10750 | let nameIndex = 0;
|
10751 | for (const variable of exports) {
|
10752 | let exportName = variable.name[0];
|
10753 | if (exportsByName[exportName]) {
|
10754 | do {
|
10755 | exportName = toBase64(++nameIndex);
|
10756 |
|
10757 | if (exportName.charCodeAt(0) === 49 ) {
|
10758 | nameIndex += 9 * 64 ** (exportName.length - 1);
|
10759 | exportName = toBase64(nameIndex);
|
10760 | }
|
10761 | } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
|
10762 | }
|
10763 | exportsByName[exportName] = variable;
|
10764 | exportNamesByVariable.set(variable, [exportName]);
|
10765 | }
|
10766 | }
|
10767 | function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
|
10768 | for (const variable of exports) {
|
10769 | let nameIndex = 0;
|
10770 | let exportName = variable.name;
|
10771 | while (exportsByName[exportName]) {
|
10772 | exportName = variable.name + '$' + ++nameIndex;
|
10773 | }
|
10774 | exportsByName[exportName] = variable;
|
10775 | exportNamesByVariable.set(variable, [exportName]);
|
10776 | }
|
10777 | }
|
10778 |
|
10779 | function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
|
10780 | const exportKeys = chunk.getExportNames();
|
10781 | if (exportMode === 'default') {
|
10782 | if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
|
10783 | return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
|
10784 | }
|
10785 | }
|
10786 | else if (exportMode === 'none' && exportKeys.length) {
|
10787 | return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
|
10788 | }
|
10789 | if (exportMode === 'auto') {
|
10790 | if (exportKeys.length === 0) {
|
10791 | exportMode = 'none';
|
10792 | }
|
10793 | else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
|
10794 | if (format === 'cjs' && unsetOptions.has('exports')) {
|
10795 | warn(errPreferNamedExports(facadeModuleId));
|
10796 | }
|
10797 | exportMode = 'default';
|
10798 | }
|
10799 | else {
|
10800 | if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
|
10801 | warn(errMixedExport(facadeModuleId, name));
|
10802 | }
|
10803 | exportMode = 'named';
|
10804 | }
|
10805 | }
|
10806 | return exportMode;
|
10807 | }
|
10808 |
|
10809 | function guessIndentString(code) {
|
10810 | const lines = code.split('\n');
|
10811 | const tabbed = lines.filter(line => /^\t+/.test(line));
|
10812 | const spaced = lines.filter(line => /^ {2,}/.test(line));
|
10813 | if (tabbed.length === 0 && spaced.length === 0) {
|
10814 | return null;
|
10815 | }
|
10816 |
|
10817 |
|
10818 |
|
10819 | if (tabbed.length >= spaced.length) {
|
10820 | return '\t';
|
10821 | }
|
10822 |
|
10823 | const min = spaced.reduce((previous, current) => {
|
10824 | const numSpaces = /^ +/.exec(current)[0].length;
|
10825 | return Math.min(numSpaces, previous);
|
10826 | }, Infinity);
|
10827 | return new Array(min + 1).join(' ');
|
10828 | }
|
10829 | function getIndentString(modules, options) {
|
10830 | if (options.indent !== true)
|
10831 | return options.indent;
|
10832 | for (let i = 0; i < modules.length; i++) {
|
10833 | const indent = guessIndentString(modules[i].originalCode);
|
10834 | if (indent !== null)
|
10835 | return indent;
|
10836 | }
|
10837 | return '\t';
|
10838 | }
|
10839 |
|
10840 | function decodedSourcemap(map) {
|
10841 | if (!map)
|
10842 | return null;
|
10843 | if (typeof map === 'string') {
|
10844 | map = JSON.parse(map);
|
10845 | }
|
10846 | if (map.mappings === '') {
|
10847 | return {
|
10848 | mappings: [],
|
10849 | names: [],
|
10850 | sources: [],
|
10851 | version: 3
|
10852 | };
|
10853 | }
|
10854 | let mappings;
|
10855 | if (typeof map.mappings === 'string') {
|
10856 | mappings = decode(map.mappings);
|
10857 | }
|
10858 | else {
|
10859 | mappings = map.mappings;
|
10860 | }
|
10861 | return { ...map, mappings };
|
10862 | }
|
10863 |
|
10864 | function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
|
10865 | const renderChunkReducer = (code, result, plugin) => {
|
10866 | if (result == null)
|
10867 | return code;
|
10868 | if (typeof result === 'string')
|
10869 | result = {
|
10870 | code: result,
|
10871 | map: undefined
|
10872 | };
|
10873 |
|
10874 | if (result.map !== null) {
|
10875 | const map = decodedSourcemap(result.map);
|
10876 | sourcemapChain.push(map || { missing: true, plugin: plugin.name });
|
10877 | }
|
10878 | return result.code;
|
10879 | };
|
10880 | return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
|
10881 | }
|
10882 |
|
10883 | function renderNamePattern(pattern, patternName, replacements, getFileInfo) {
|
10884 | if (typeof pattern === 'function') {
|
10885 | pattern = pattern(getFileInfo());
|
10886 | }
|
10887 | if (!isPlainPathFragment(pattern))
|
10888 | return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
|
10889 | return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
|
10890 | if (!replacements.hasOwnProperty(type)) {
|
10891 | return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
|
10892 | }
|
10893 | const replacement = replacements[type]();
|
10894 | if (!isPlainPathFragment(replacement))
|
10895 | return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
|
10896 | return replacement;
|
10897 | });
|
10898 | }
|
10899 | function makeUnique(name, existingNames) {
|
10900 | const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
|
10901 | if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
|
10902 | return name;
|
10903 | const ext = sysPath.extname(name);
|
10904 | name = name.substr(0, name.length - ext.length);
|
10905 | let uniqueName, uniqueIndex = 1;
|
10906 | while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
|
10907 | ;
|
10908 | return uniqueName;
|
10909 | }
|
10910 |
|
10911 | const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
|
10912 | function getGlobalName(module, globals, hasExports, warn) {
|
10913 | const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
|
10914 | if (globalName) {
|
10915 | return globalName;
|
10916 | }
|
10917 | if (hasExports) {
|
10918 | warn({
|
10919 | code: 'MISSING_GLOBAL_NAME',
|
10920 | guess: module.variableName,
|
10921 | message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
|
10922 | source: module.id
|
10923 | });
|
10924 | return module.variableName;
|
10925 | }
|
10926 | }
|
10927 | class Chunk$1 {
|
10928 | constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
|
10929 | this.orderedModules = orderedModules;
|
10930 | this.inputOptions = inputOptions;
|
10931 | this.outputOptions = outputOptions;
|
10932 | this.unsetOptions = unsetOptions;
|
10933 | this.pluginDriver = pluginDriver;
|
10934 | this.modulesById = modulesById;
|
10935 | this.chunkByModule = chunkByModule;
|
10936 | this.facadeChunkByModule = facadeChunkByModule;
|
10937 | this.includedNamespaces = includedNamespaces;
|
10938 | this.manualChunkAlias = manualChunkAlias;
|
10939 | this.entryModules = [];
|
10940 | this.exportMode = 'named';
|
10941 | this.facadeModule = null;
|
10942 | this.id = null;
|
10943 | this.namespaceVariableName = '';
|
10944 | this.variableName = '';
|
10945 | this.accessedGlobalsByScope = new Map();
|
10946 | this.dependencies = new Set();
|
10947 | this.dynamicDependencies = new Set();
|
10948 | this.dynamicEntryModules = [];
|
10949 | this.exportNamesByVariable = new Map();
|
10950 | this.exports = new Set();
|
10951 | this.exportsByName = Object.create(null);
|
10952 | this.fileName = null;
|
10953 | this.implicitEntryModules = [];
|
10954 | this.implicitlyLoadedBefore = new Set();
|
10955 | this.imports = new Set();
|
10956 | this.indentString = undefined;
|
10957 | this.isEmpty = true;
|
10958 | this.name = null;
|
10959 | this.needsExportsShim = false;
|
10960 | this.renderedDependencies = null;
|
10961 | this.renderedExports = null;
|
10962 | this.renderedHash = undefined;
|
10963 | this.renderedModules = Object.create(null);
|
10964 | this.renderedModuleSources = new Map();
|
10965 | this.renderedSource = null;
|
10966 | this.sortedExportNames = null;
|
10967 | this.strictFacade = false;
|
10968 | this.usedModules = undefined;
|
10969 | this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
|
10970 | const chunkModules = new Set(orderedModules);
|
10971 | for (const module of orderedModules) {
|
10972 | if (module.namespace.included) {
|
10973 | includedNamespaces.add(module);
|
10974 | }
|
10975 | if (this.isEmpty && module.isIncluded()) {
|
10976 | this.isEmpty = false;
|
10977 | }
|
10978 | if (module.info.isEntry || outputOptions.preserveModules) {
|
10979 | this.entryModules.push(module);
|
10980 | }
|
10981 | for (const importer of module.includedDynamicImporters) {
|
10982 | if (!chunkModules.has(importer)) {
|
10983 | this.dynamicEntryModules.push(module);
|
10984 |
|
10985 | if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
|
10986 | includedNamespaces.add(module);
|
10987 | this.exports.add(module.namespace);
|
10988 | }
|
10989 | }
|
10990 | }
|
10991 | if (module.implicitlyLoadedAfter.size > 0) {
|
10992 | this.implicitEntryModules.push(module);
|
10993 | }
|
10994 | }
|
10995 | this.suggestedVariableName = makeLegal(this.generateVariableName());
|
10996 | }
|
10997 | static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
|
10998 | const chunk = new Chunk$1([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
|
10999 | chunk.assignFacadeName(facadeName, facadedModule);
|
11000 | if (!facadeChunkByModule.has(facadedModule)) {
|
11001 | facadeChunkByModule.set(facadedModule, chunk);
|
11002 | }
|
11003 | for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
|
11004 | chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
|
11005 | }
|
11006 | if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
|
11007 | facadedModule.info.hasModuleSideEffects &&
|
11008 | facadedModule.hasEffects()) {
|
11009 | chunk.dependencies.add(chunkByModule.get(facadedModule));
|
11010 | }
|
11011 | chunk.ensureReexportsAreAvailableForModule(facadedModule);
|
11012 | chunk.facadeModule = facadedModule;
|
11013 | chunk.strictFacade = true;
|
11014 | return chunk;
|
11015 | }
|
11016 | canModuleBeFacade(module, exposedVariables) {
|
11017 | const moduleExportNamesByVariable = module.getExportNamesByVariable();
|
11018 | for (const exposedVariable of this.exports) {
|
11019 | if (!moduleExportNamesByVariable.has(exposedVariable)) {
|
11020 | if (moduleExportNamesByVariable.size === 0 &&
|
11021 | module.isUserDefinedEntryPoint &&
|
11022 | module.preserveSignature === 'strict' &&
|
11023 | this.unsetOptions.has('preserveEntrySignatures')) {
|
11024 | this.inputOptions.onwarn({
|
11025 | code: 'EMPTY_FACADE',
|
11026 | id: module.id,
|
11027 | 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.`,
|
11028 | url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
|
11029 | });
|
11030 | }
|
11031 | return false;
|
11032 | }
|
11033 | }
|
11034 | for (const exposedVariable of exposedVariables) {
|
11035 | if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
|
11036 | return false;
|
11037 | }
|
11038 | }
|
11039 | return true;
|
11040 | }
|
11041 | generateExports() {
|
11042 | this.sortedExportNames = null;
|
11043 | const remainingExports = new Set(this.exports);
|
11044 | if (this.facadeModule !== null &&
|
11045 | (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
|
11046 | const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
|
11047 | for (const [variable, exportNames] of exportNamesByVariable) {
|
11048 | this.exportNamesByVariable.set(variable, [...exportNames]);
|
11049 | for (const exportName of exportNames) {
|
11050 | this.exportsByName[exportName] = variable;
|
11051 | }
|
11052 | remainingExports.delete(variable);
|
11053 | }
|
11054 | }
|
11055 | if (this.outputOptions.minifyInternalExports) {
|
11056 | assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
|
11057 | }
|
11058 | else {
|
11059 | assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
|
11060 | }
|
11061 | if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
|
11062 | this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
|
11063 | }
|
11064 | generateFacades() {
|
11065 | var _a;
|
11066 | const facades = [];
|
11067 | const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
|
11068 | const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
|
11069 | for (const module of entryModules) {
|
11070 | if (module.preserveSignature) {
|
11071 | for (const exportedVariable of module.getExportNamesByVariable().keys()) {
|
11072 | exposedVariables.add(exportedVariable);
|
11073 | }
|
11074 | }
|
11075 | }
|
11076 | for (const module of entryModules) {
|
11077 | const requiredFacades = Array.from(module.userChunkNames, name => ({
|
11078 | name
|
11079 | }));
|
11080 | if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
|
11081 | requiredFacades.push({});
|
11082 | }
|
11083 | requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
|
11084 | if (requiredFacades.length === 0) {
|
11085 | requiredFacades.push({});
|
11086 | }
|
11087 | if (!this.facadeModule) {
|
11088 | const needsStrictFacade = module.preserveSignature === 'strict' ||
|
11089 | (module.preserveSignature === 'exports-only' &&
|
11090 | module.getExportNamesByVariable().size !== 0);
|
11091 | if (!needsStrictFacade ||
|
11092 | this.outputOptions.preserveModules ||
|
11093 | this.canModuleBeFacade(module, exposedVariables)) {
|
11094 | this.facadeModule = module;
|
11095 | this.facadeChunkByModule.set(module, this);
|
11096 | if (module.preserveSignature) {
|
11097 | this.strictFacade = needsStrictFacade;
|
11098 | this.ensureReexportsAreAvailableForModule(module);
|
11099 | }
|
11100 | this.assignFacadeName(requiredFacades.shift(), module);
|
11101 | }
|
11102 | }
|
11103 | for (const facadeName of requiredFacades) {
|
11104 | facades.push(Chunk$1.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
|
11105 | }
|
11106 | }
|
11107 | for (const module of this.dynamicEntryModules) {
|
11108 | if (module.info.syntheticNamedExports)
|
11109 | continue;
|
11110 | if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
|
11111 | this.facadeModule = module;
|
11112 | this.facadeChunkByModule.set(module, this);
|
11113 | this.strictFacade = true;
|
11114 | this.assignFacadeName({}, module);
|
11115 | }
|
11116 | else if (this.facadeModule === module &&
|
11117 | !this.strictFacade &&
|
11118 | this.canModuleBeFacade(module, exposedVariables)) {
|
11119 | this.strictFacade = true;
|
11120 | }
|
11121 | else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
|
11122 | this.includedNamespaces.add(module);
|
11123 | this.exports.add(module.namespace);
|
11124 | }
|
11125 | }
|
11126 | return facades;
|
11127 | }
|
11128 | generateId(addons, options, existingNames, includeHash) {
|
11129 | if (this.fileName !== null) {
|
11130 | return this.fileName;
|
11131 | }
|
11132 | const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
|
11133 | ? [options.entryFileNames, 'output.entryFileNames']
|
11134 | : [options.chunkFileNames, 'output.chunkFileNames'];
|
11135 | return makeUnique(renderNamePattern(pattern, patternName, {
|
11136 | format: () => options.format,
|
11137 | hash: () => includeHash
|
11138 | ? this.computeContentHashWithDependencies(addons, options, existingNames)
|
11139 | : '[hash]',
|
11140 | name: () => this.getChunkName()
|
11141 | }, this.getChunkInfo.bind(this)), existingNames);
|
11142 | }
|
11143 | generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
|
11144 | const id = this.orderedModules[0].id;
|
11145 | const sanitizedId = sanitizeFileName(id);
|
11146 | let path;
|
11147 | if (isAbsolute(id)) {
|
11148 | const extension = sysPath.extname(id);
|
11149 | const pattern = unsetOptions.has('entryFileNames')
|
11150 | ? NON_ASSET_EXTENSIONS.includes(extension)
|
11151 | ? '[name].js'
|
11152 | : '[name][extname].js'
|
11153 | : options.entryFileNames;
|
11154 | const currentDir = sysPath.dirname(sanitizedId);
|
11155 | const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
|
11156 | ext: () => extension.substr(1),
|
11157 | extname: () => extension,
|
11158 | format: () => options.format,
|
11159 | name: () => this.getChunkName()
|
11160 | }, this.getChunkInfo.bind(this));
|
11161 | const currentPath = `${currentDir}/${fileName}`;
|
11162 | const { preserveModulesRoot } = options;
|
11163 | if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
|
11164 | path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
|
11165 | }
|
11166 | else {
|
11167 | path = relative(preserveModulesRelativeDir, currentPath);
|
11168 | }
|
11169 | }
|
11170 | else {
|
11171 | path = `_virtual/${sysPath.basename(sanitizedId)}`;
|
11172 | }
|
11173 | return makeUnique(normalize(path), existingNames);
|
11174 | }
|
11175 | getChunkInfo() {
|
11176 | const facadeModule = this.facadeModule;
|
11177 | const getChunkName = this.getChunkName.bind(this);
|
11178 | return {
|
11179 | exports: this.getExportNames(),
|
11180 | facadeModuleId: facadeModule && facadeModule.id,
|
11181 | isDynamicEntry: this.dynamicEntryModules.length > 0,
|
11182 | isEntry: facadeModule !== null && facadeModule.info.isEntry,
|
11183 | isImplicitEntry: this.implicitEntryModules.length > 0,
|
11184 | modules: this.renderedModules,
|
11185 | get name() {
|
11186 | return getChunkName();
|
11187 | },
|
11188 | type: 'chunk'
|
11189 | };
|
11190 | }
|
11191 | getChunkInfoWithFileNames() {
|
11192 | return Object.assign(this.getChunkInfo(), {
|
11193 | code: undefined,
|
11194 | dynamicImports: Array.from(this.dynamicDependencies, getId),
|
11195 | fileName: this.id,
|
11196 | implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
|
11197 | importedBindings: this.getImportedBindingsPerDependency(),
|
11198 | imports: Array.from(this.dependencies, getId),
|
11199 | map: undefined,
|
11200 | referencedFiles: this.getReferencedFiles()
|
11201 | });
|
11202 | }
|
11203 | getChunkName() {
|
11204 | return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
|
11205 | }
|
11206 | getExportNames() {
|
11207 | return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
|
11208 | }
|
11209 | getRenderedHash() {
|
11210 | if (this.renderedHash)
|
11211 | return this.renderedHash;
|
11212 | const hash = createHash();
|
11213 | const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
|
11214 | if (pluginHash) {
|
11215 | augmentation += pluginHash;
|
11216 | }
|
11217 | return augmentation;
|
11218 | });
|
11219 | hash.update(hashAugmentation);
|
11220 | hash.update(this.renderedSource.toString());
|
11221 | hash.update(this.getExportNames()
|
11222 | .map(exportName => {
|
11223 | const variable = this.exportsByName[exportName];
|
11224 | return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
|
11225 | })
|
11226 | .join(','));
|
11227 | return (this.renderedHash = hash.digest('hex'));
|
11228 | }
|
11229 | getVariableExportName(variable) {
|
11230 | if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
|
11231 | return '*';
|
11232 | }
|
11233 | return this.exportNamesByVariable.get(variable)[0];
|
11234 | }
|
11235 | link() {
|
11236 | for (const module of this.orderedModules) {
|
11237 | this.addDependenciesToChunk(module.getDependenciesToBeIncluded(), this.dependencies);
|
11238 | this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
|
11239 | this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
|
11240 | this.setUpChunkImportsAndExportsForModule(module);
|
11241 | }
|
11242 | }
|
11243 |
|
11244 | preRender(options, inputBase) {
|
11245 | const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
|
11246 | this.usedModules = [];
|
11247 | this.indentString = getIndentString(this.orderedModules, options);
|
11248 | const n = options.compact ? '' : '\n';
|
11249 | const _ = options.compact ? '' : ' ';
|
11250 | const renderOptions = {
|
11251 | compact: options.compact,
|
11252 | dynamicImportFunction: options.dynamicImportFunction,
|
11253 | exportNamesByVariable: this.exportNamesByVariable,
|
11254 | format: options.format,
|
11255 | freeze: options.freeze,
|
11256 | indent: this.indentString,
|
11257 | namespaceToStringTag: options.namespaceToStringTag,
|
11258 | outputPluginDriver: this.pluginDriver,
|
11259 | varOrConst: options.preferConst ? 'const' : 'var'
|
11260 | };
|
11261 |
|
11262 | if (options.hoistTransitiveImports &&
|
11263 | !this.outputOptions.preserveModules &&
|
11264 | this.facadeModule !== null) {
|
11265 | for (const dep of this.dependencies) {
|
11266 | if (dep instanceof Chunk$1)
|
11267 | this.inlineChunkDependencies(dep);
|
11268 | }
|
11269 | }
|
11270 | const sortedDependencies = [...this.dependencies];
|
11271 | sortByExecutionOrder(sortedDependencies);
|
11272 | this.dependencies = new Set(sortedDependencies);
|
11273 | this.prepareDynamicImportsAndImportMetas();
|
11274 | this.setIdentifierRenderResolutions(options);
|
11275 | let hoistedSource = '';
|
11276 | const renderedModules = this.renderedModules;
|
11277 | for (const module of this.orderedModules) {
|
11278 | let renderedLength = 0;
|
11279 | if (module.isIncluded() || this.includedNamespaces.has(module)) {
|
11280 | const source = module.render(renderOptions).trim();
|
11281 | renderedLength = source.length();
|
11282 | if (renderedLength) {
|
11283 | if (options.compact && source.lastLine().indexOf('//') !== -1)
|
11284 | source.append('\n');
|
11285 | this.renderedModuleSources.set(module, source);
|
11286 | magicString.addSource(source);
|
11287 | this.usedModules.push(module);
|
11288 | }
|
11289 | const namespace = module.namespace;
|
11290 | if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
|
11291 | const rendered = namespace.renderBlock(renderOptions);
|
11292 | if (namespace.renderFirst())
|
11293 | hoistedSource += n + rendered;
|
11294 | else
|
11295 | magicString.addSource(new MagicString(rendered));
|
11296 | }
|
11297 | }
|
11298 | const { renderedExports, removedExports } = module.getRenderedExports();
|
11299 | renderedModules[module.id] = {
|
11300 | originalLength: module.originalCode.length,
|
11301 | removedExports,
|
11302 | renderedExports,
|
11303 | renderedLength
|
11304 | };
|
11305 | }
|
11306 | if (hoistedSource)
|
11307 | magicString.prepend(hoistedSource + n + n);
|
11308 | if (this.needsExportsShim) {
|
11309 | magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
|
11310 | }
|
11311 | if (options.compact) {
|
11312 | this.renderedSource = magicString;
|
11313 | }
|
11314 | else {
|
11315 | this.renderedSource = magicString.trim();
|
11316 | }
|
11317 | this.renderedHash = undefined;
|
11318 | if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
|
11319 | const chunkName = this.getChunkName();
|
11320 | this.inputOptions.onwarn({
|
11321 | chunkName,
|
11322 | code: 'EMPTY_BUNDLE',
|
11323 | message: `Generated an empty chunk: "${chunkName}"`
|
11324 | });
|
11325 | }
|
11326 | this.setExternalRenderPaths(options, inputBase);
|
11327 | this.renderedDependencies = this.getChunkDependencyDeclarations(options);
|
11328 | this.renderedExports =
|
11329 | this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
|
11330 | }
|
11331 | async render(options, addons, outputChunk) {
|
11332 | timeStart('render format', 2);
|
11333 | const format = options.format;
|
11334 | const finalise = finalisers[format];
|
11335 | if (options.dynamicImportFunction && format !== 'es') {
|
11336 | this.inputOptions.onwarn({
|
11337 | code: 'INVALID_OPTION',
|
11338 | message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
|
11339 | });
|
11340 | }
|
11341 |
|
11342 |
|
11343 | for (const dependency of this.dependencies) {
|
11344 | const renderedDependency = this.renderedDependencies.get(dependency);
|
11345 | if (dependency instanceof ExternalModule) {
|
11346 | const originalId = dependency.renderPath;
|
11347 | renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
|
11348 | }
|
11349 | else {
|
11350 | renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
|
11351 | renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
|
11352 | }
|
11353 | }
|
11354 | this.finaliseDynamicImports(options);
|
11355 | this.finaliseImportMetas(format);
|
11356 | const hasExports = this.renderedExports.length !== 0 ||
|
11357 | [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
|
11358 | let usesTopLevelAwait = false;
|
11359 | const accessedGlobals = new Set();
|
11360 | for (const module of this.orderedModules) {
|
11361 | if (module.usesTopLevelAwait) {
|
11362 | usesTopLevelAwait = true;
|
11363 | }
|
11364 | const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
|
11365 | if (accessedGlobalVariables) {
|
11366 | for (const name of accessedGlobalVariables) {
|
11367 | accessedGlobals.add(name);
|
11368 | }
|
11369 | }
|
11370 | }
|
11371 | if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
|
11372 | return error({
|
11373 | code: 'INVALID_TLA_FORMAT',
|
11374 | message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
|
11375 | });
|
11376 | }
|
11377 | const magicString = finalise(this.renderedSource, {
|
11378 | accessedGlobals,
|
11379 | dependencies: [...this.renderedDependencies.values()],
|
11380 | exports: this.renderedExports,
|
11381 | hasExports,
|
11382 | indentString: this.indentString,
|
11383 | intro: addons.intro,
|
11384 | isEntryFacade: this.outputOptions.preserveModules ||
|
11385 | (this.facadeModule !== null && this.facadeModule.info.isEntry),
|
11386 | isModuleFacade: this.facadeModule !== null,
|
11387 | namedExportsMode: this.exportMode !== 'default',
|
11388 | outro: addons.outro,
|
11389 | usesTopLevelAwait,
|
11390 | varOrConst: options.preferConst ? 'const' : 'var',
|
11391 | warn: this.inputOptions.onwarn
|
11392 | }, options);
|
11393 | if (addons.banner)
|
11394 | magicString.prepend(addons.banner);
|
11395 | if (addons.footer)
|
11396 | magicString.append(addons.footer);
|
11397 | const prevCode = magicString.toString();
|
11398 | timeEnd('render format', 2);
|
11399 | let map = null;
|
11400 | const chunkSourcemapChain = [];
|
11401 | let code = await renderChunk({
|
11402 | code: prevCode,
|
11403 | options,
|
11404 | outputPluginDriver: this.pluginDriver,
|
11405 | renderChunk: outputChunk,
|
11406 | sourcemapChain: chunkSourcemapChain
|
11407 | });
|
11408 | if (options.sourcemap) {
|
11409 | timeStart('sourcemap', 2);
|
11410 | let file;
|
11411 | if (options.file)
|
11412 | file = sysPath.resolve(options.sourcemapFile || options.file);
|
11413 | else if (options.dir)
|
11414 | file = sysPath.resolve(options.dir, this.id);
|
11415 | else
|
11416 | file = sysPath.resolve(this.id);
|
11417 | const decodedMap = magicString.generateDecodedMap({});
|
11418 | map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
|
11419 | map.sources = map.sources
|
11420 | .map(sourcePath => {
|
11421 | const { sourcemapPathTransform } = options;
|
11422 | if (sourcemapPathTransform) {
|
11423 | const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
|
11424 | if (typeof newSourcePath !== 'string') {
|
11425 | error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
|
11426 | }
|
11427 | return newSourcePath;
|
11428 | }
|
11429 | return sourcePath;
|
11430 | })
|
11431 | .map(normalize);
|
11432 | timeEnd('sourcemap', 2);
|
11433 | }
|
11434 | if (!options.compact && code[code.length - 1] !== '\n')
|
11435 | code += '\n';
|
11436 | return { code, map };
|
11437 | }
|
11438 | addDependenciesToChunk(moduleDependencies, chunkDependencies) {
|
11439 | for (const module of moduleDependencies) {
|
11440 | if (module instanceof Module) {
|
11441 | const chunk = this.chunkByModule.get(module);
|
11442 | if (chunk && chunk !== this) {
|
11443 | chunkDependencies.add(chunk);
|
11444 | }
|
11445 | }
|
11446 | else {
|
11447 | chunkDependencies.add(module);
|
11448 | }
|
11449 | }
|
11450 | }
|
11451 | assignFacadeName({ fileName, name }, facadedModule) {
|
11452 | if (fileName) {
|
11453 | this.fileName = fileName;
|
11454 | }
|
11455 | else {
|
11456 | this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
|
11457 | }
|
11458 | }
|
11459 | computeContentHashWithDependencies(addons, options, existingNames) {
|
11460 | const hash = createHash();
|
11461 | hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
|
11462 | hash.update(options.format);
|
11463 | const dependenciesForHashing = new Set([this]);
|
11464 | for (const current of dependenciesForHashing) {
|
11465 | if (current instanceof ExternalModule) {
|
11466 | hash.update(':' + current.renderPath);
|
11467 | }
|
11468 | else {
|
11469 | hash.update(current.getRenderedHash());
|
11470 | hash.update(current.generateId(addons, options, existingNames, false));
|
11471 | }
|
11472 | if (current instanceof ExternalModule)
|
11473 | continue;
|
11474 | for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
|
11475 | dependenciesForHashing.add(dependency);
|
11476 | }
|
11477 | }
|
11478 | return hash.digest('hex').substr(0, 8);
|
11479 | }
|
11480 | ensureReexportsAreAvailableForModule(module) {
|
11481 | const map = module.getExportNamesByVariable();
|
11482 | for (const exportedVariable of map.keys()) {
|
11483 | const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
|
11484 | const importedVariable = isSynthetic
|
11485 | ? exportedVariable.getBaseVariable()
|
11486 | : exportedVariable;
|
11487 | if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
|
11488 | const exportingModule = importedVariable.module;
|
11489 | if (exportingModule instanceof Module) {
|
11490 | const chunk = this.chunkByModule.get(exportingModule);
|
11491 | if (chunk && chunk !== this) {
|
11492 | chunk.exports.add(importedVariable);
|
11493 | if (isSynthetic) {
|
11494 | this.imports.add(importedVariable);
|
11495 | }
|
11496 | }
|
11497 | }
|
11498 | }
|
11499 | }
|
11500 | }
|
11501 | finaliseDynamicImports(options) {
|
11502 | const stripKnownJsExtensions = options.format === 'amd';
|
11503 | for (const [module, code] of this.renderedModuleSources) {
|
11504 | for (const { node, resolution } of module.dynamicImports) {
|
11505 | const chunk = this.chunkByModule.get(resolution);
|
11506 | const facadeChunk = this.facadeChunkByModule.get(resolution);
|
11507 | if (!resolution || !node.included || chunk === this) {
|
11508 | continue;
|
11509 | }
|
11510 | const renderedResolution = resolution instanceof Module
|
11511 | ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
|
11512 | : resolution instanceof ExternalModule
|
11513 | ? `'${resolution.renormalizeRenderPath
|
11514 | ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
|
11515 | : resolution.renderPath}'`
|
11516 | : resolution;
|
11517 | node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
|
11518 | !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
|
11519 | chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
|
11520 | }
|
11521 | }
|
11522 | }
|
11523 | finaliseImportMetas(format) {
|
11524 | for (const [module, code] of this.renderedModuleSources) {
|
11525 | for (const importMeta of module.importMetas) {
|
11526 | importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
|
11527 | }
|
11528 | }
|
11529 | }
|
11530 | generateVariableName() {
|
11531 | if (this.manualChunkAlias) {
|
11532 | return this.manualChunkAlias;
|
11533 | }
|
11534 | const moduleForNaming = this.entryModules[0] ||
|
11535 | this.implicitEntryModules[0] ||
|
11536 | this.dynamicEntryModules[0] ||
|
11537 | this.orderedModules[this.orderedModules.length - 1];
|
11538 | if (moduleForNaming) {
|
11539 | return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
|
11540 | }
|
11541 | return 'chunk';
|
11542 | }
|
11543 | getChunkDependencyDeclarations(options) {
|
11544 | const importSpecifiers = this.getImportSpecifiers();
|
11545 | const reexportSpecifiers = this.getReexportSpecifiers();
|
11546 | const dependencyDeclaration = new Map();
|
11547 | for (const dep of this.dependencies) {
|
11548 | const imports = importSpecifiers.get(dep) || null;
|
11549 | const reexports = reexportSpecifiers.get(dep) || null;
|
11550 | const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
|
11551 | dependencyDeclaration.set(dep, {
|
11552 | defaultVariableName: dep.defaultVariableName,
|
11553 | globalName: (dep instanceof ExternalModule &&
|
11554 | (options.format === 'umd' || options.format === 'iife') &&
|
11555 | getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
|
11556 | id: undefined,
|
11557 | imports,
|
11558 | isChunk: dep instanceof Chunk$1,
|
11559 | name: dep.variableName,
|
11560 | namedExportsMode,
|
11561 | namespaceVariableName: dep.namespaceVariableName,
|
11562 | reexports
|
11563 | });
|
11564 | }
|
11565 | return dependencyDeclaration;
|
11566 | }
|
11567 | getChunkExportDeclarations(format) {
|
11568 | const exports = [];
|
11569 | for (const exportName of this.getExportNames()) {
|
11570 | if (exportName[0] === '*')
|
11571 | continue;
|
11572 | const variable = this.exportsByName[exportName];
|
11573 | if (!(variable instanceof SyntheticNamedExportVariable)) {
|
11574 | const module = variable.module;
|
11575 | if (module && this.chunkByModule.get(module) !== this)
|
11576 | continue;
|
11577 | }
|
11578 | let expression = null;
|
11579 | let hoisted = false;
|
11580 | let uninitialized = false;
|
11581 | let local = variable.getName();
|
11582 | if (variable instanceof LocalVariable) {
|
11583 | if (variable.init === UNDEFINED_EXPRESSION) {
|
11584 | uninitialized = true;
|
11585 | }
|
11586 | for (const declaration of variable.declarations) {
|
11587 | if (declaration.parent instanceof FunctionDeclaration ||
|
11588 | (declaration instanceof ExportDefaultDeclaration &&
|
11589 | declaration.declaration instanceof FunctionDeclaration)) {
|
11590 | hoisted = true;
|
11591 | break;
|
11592 | }
|
11593 | }
|
11594 | }
|
11595 | else if (variable instanceof SyntheticNamedExportVariable) {
|
11596 | expression = local;
|
11597 | if (format === 'es' && exportName !== 'default') {
|
11598 | local = variable.renderName;
|
11599 | }
|
11600 | }
|
11601 | exports.push({
|
11602 | exported: exportName,
|
11603 | expression,
|
11604 | hoisted,
|
11605 | local,
|
11606 | uninitialized
|
11607 | });
|
11608 | }
|
11609 | return exports;
|
11610 | }
|
11611 | getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
|
11612 | const dependencies = new Set();
|
11613 | const deconflictedDefault = new Set();
|
11614 | const deconflictedNamespace = new Set();
|
11615 | for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
|
11616 | if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
|
11617 | const module = variable.module;
|
11618 | if (module instanceof ExternalModule) {
|
11619 | dependencies.add(module);
|
11620 | if (addNonNamespacesAndInteropHelpers) {
|
11621 | if (variable.name === 'default') {
|
11622 | if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
|
11623 | deconflictedDefault.add(module);
|
11624 | }
|
11625 | }
|
11626 | else if (variable.name === '*') {
|
11627 | if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
|
11628 | deconflictedNamespace.add(module);
|
11629 | }
|
11630 | }
|
11631 | }
|
11632 | }
|
11633 | else {
|
11634 | const chunk = this.chunkByModule.get(module);
|
11635 | if (chunk !== this) {
|
11636 | dependencies.add(chunk);
|
11637 | if (addNonNamespacesAndInteropHelpers &&
|
11638 | chunk.exportMode === 'default' &&
|
11639 | variable.isNamespace) {
|
11640 | deconflictedNamespace.add(chunk);
|
11641 | }
|
11642 | }
|
11643 | }
|
11644 | }
|
11645 | }
|
11646 | if (addDependenciesWithoutBindings) {
|
11647 | for (const dependency of this.dependencies) {
|
11648 | dependencies.add(dependency);
|
11649 | }
|
11650 | }
|
11651 | return { deconflictedDefault, deconflictedNamespace, dependencies };
|
11652 | }
|
11653 | getFallbackChunkName() {
|
11654 | if (this.manualChunkAlias) {
|
11655 | return this.manualChunkAlias;
|
11656 | }
|
11657 | if (this.fileName) {
|
11658 | return getAliasName(this.fileName);
|
11659 | }
|
11660 | return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
|
11661 | }
|
11662 | getImportedBindingsPerDependency() {
|
11663 | const importSpecifiers = {};
|
11664 | for (const [dependency, declaration] of this.renderedDependencies) {
|
11665 | const specifiers = new Set();
|
11666 | if (declaration.imports) {
|
11667 | for (const { imported } of declaration.imports) {
|
11668 | specifiers.add(imported);
|
11669 | }
|
11670 | }
|
11671 | if (declaration.reexports) {
|
11672 | for (const { imported } of declaration.reexports) {
|
11673 | specifiers.add(imported);
|
11674 | }
|
11675 | }
|
11676 | importSpecifiers[dependency.id] = [...specifiers];
|
11677 | }
|
11678 | return importSpecifiers;
|
11679 | }
|
11680 | getImportSpecifiers() {
|
11681 | const { interop } = this.outputOptions;
|
11682 | const importsByDependency = new Map();
|
11683 | for (const variable of this.imports) {
|
11684 | const module = variable.module;
|
11685 | let dependency;
|
11686 | let imported;
|
11687 | if (module instanceof ExternalModule) {
|
11688 | dependency = module;
|
11689 | imported = variable.name;
|
11690 | if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
|
11691 | return error(errUnexpectedNamedImport(module.id, imported, false));
|
11692 | }
|
11693 | }
|
11694 | else {
|
11695 | dependency = this.chunkByModule.get(module);
|
11696 | imported = dependency.getVariableExportName(variable);
|
11697 | }
|
11698 | getOrCreate(importsByDependency, dependency, () => []).push({
|
11699 | imported,
|
11700 | local: variable.getName()
|
11701 | });
|
11702 | }
|
11703 | return importsByDependency;
|
11704 | }
|
11705 | getReexportSpecifiers() {
|
11706 | const { externalLiveBindings, interop } = this.outputOptions;
|
11707 | const reexportSpecifiers = new Map();
|
11708 | for (let exportName of this.getExportNames()) {
|
11709 | let dependency;
|
11710 | let imported;
|
11711 | let needsLiveBinding = false;
|
11712 | if (exportName[0] === '*') {
|
11713 | const id = exportName.substr(1);
|
11714 | if (interop(id) === 'defaultOnly') {
|
11715 | this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
|
11716 | }
|
11717 | needsLiveBinding = externalLiveBindings;
|
11718 | dependency = this.modulesById.get(id);
|
11719 | imported = exportName = '*';
|
11720 | }
|
11721 | else {
|
11722 | const variable = this.exportsByName[exportName];
|
11723 | if (variable instanceof SyntheticNamedExportVariable)
|
11724 | continue;
|
11725 | const module = variable.module;
|
11726 | if (module instanceof Module) {
|
11727 | dependency = this.chunkByModule.get(module);
|
11728 | if (dependency === this)
|
11729 | continue;
|
11730 | imported = dependency.getVariableExportName(variable);
|
11731 | needsLiveBinding = variable.isReassigned;
|
11732 | }
|
11733 | else {
|
11734 | dependency = module;
|
11735 | imported = variable.name;
|
11736 | if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
|
11737 | return error(errUnexpectedNamedImport(module.id, imported, true));
|
11738 | }
|
11739 | needsLiveBinding =
|
11740 | externalLiveBindings &&
|
11741 | (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
|
11742 | }
|
11743 | }
|
11744 | getOrCreate(reexportSpecifiers, dependency, () => []).push({
|
11745 | imported,
|
11746 | needsLiveBinding,
|
11747 | reexported: exportName
|
11748 | });
|
11749 | }
|
11750 | return reexportSpecifiers;
|
11751 | }
|
11752 | getReferencedFiles() {
|
11753 | const referencedFiles = [];
|
11754 | for (const module of this.orderedModules) {
|
11755 | for (const meta of module.importMetas) {
|
11756 | const fileName = meta.getReferencedFileName(this.pluginDriver);
|
11757 | if (fileName) {
|
11758 | referencedFiles.push(fileName);
|
11759 | }
|
11760 | }
|
11761 | }
|
11762 | return referencedFiles;
|
11763 | }
|
11764 | getRelativePath(targetPath, stripJsExtension) {
|
11765 | let relativePath = normalize(relative(sysPath.dirname(this.id), targetPath));
|
11766 | if (stripJsExtension && relativePath.endsWith('.js')) {
|
11767 | relativePath = relativePath.slice(0, -3);
|
11768 | }
|
11769 | if (relativePath === '..')
|
11770 | return '../../' + sysPath.basename(targetPath);
|
11771 | if (relativePath === '')
|
11772 | return '../' + sysPath.basename(targetPath);
|
11773 | return relativePath.startsWith('../') ? relativePath : './' + relativePath;
|
11774 | }
|
11775 | inlineChunkDependencies(chunk) {
|
11776 | for (const dep of chunk.dependencies) {
|
11777 | if (this.dependencies.has(dep))
|
11778 | continue;
|
11779 | this.dependencies.add(dep);
|
11780 | if (dep instanceof Chunk$1) {
|
11781 | this.inlineChunkDependencies(dep);
|
11782 | }
|
11783 | }
|
11784 | }
|
11785 | prepareDynamicImportsAndImportMetas() {
|
11786 | var _a;
|
11787 | const accessedGlobalsByScope = this.accessedGlobalsByScope;
|
11788 | for (const module of this.orderedModules) {
|
11789 | for (const { node, resolution } of module.dynamicImports) {
|
11790 | if (node.included) {
|
11791 | if (resolution instanceof Module) {
|
11792 | const chunk = this.chunkByModule.get(resolution);
|
11793 | if (chunk === this) {
|
11794 | node.setInternalResolution(resolution.namespace);
|
11795 | }
|
11796 | else {
|
11797 | node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
|
11798 | }
|
11799 | }
|
11800 | else {
|
11801 | node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
|
11802 | }
|
11803 | }
|
11804 | }
|
11805 | for (const importMeta of module.importMetas) {
|
11806 | importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
|
11807 | }
|
11808 | }
|
11809 | }
|
11810 | setExternalRenderPaths(options, inputBase) {
|
11811 | for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
|
11812 | if (dependency instanceof ExternalModule) {
|
11813 | dependency.setRenderPath(options, inputBase);
|
11814 | }
|
11815 | }
|
11816 | }
|
11817 | setIdentifierRenderResolutions({ format, interop }) {
|
11818 | const syntheticExports = new Set();
|
11819 | for (const exportName of this.getExportNames()) {
|
11820 | const exportVariable = this.exportsByName[exportName];
|
11821 | if (exportVariable instanceof ExportShimVariable) {
|
11822 | this.needsExportsShim = true;
|
11823 | }
|
11824 | if (format !== 'es' &&
|
11825 | format !== 'system' &&
|
11826 | exportVariable.isReassigned &&
|
11827 | !exportVariable.isId) {
|
11828 | exportVariable.setRenderNames('exports', exportName);
|
11829 | }
|
11830 | else if (exportVariable instanceof SyntheticNamedExportVariable) {
|
11831 | syntheticExports.add(exportVariable);
|
11832 | }
|
11833 | else {
|
11834 | exportVariable.setRenderNames(null, null);
|
11835 | }
|
11836 | }
|
11837 | const usedNames = new Set();
|
11838 | if (this.needsExportsShim) {
|
11839 | usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
|
11840 | }
|
11841 | switch (format) {
|
11842 | case 'system':
|
11843 | usedNames.add('module').add('exports');
|
11844 | break;
|
11845 | case 'es':
|
11846 | break;
|
11847 | case 'cjs':
|
11848 | usedNames.add('module').add('require').add('__filename').add('__dirname');
|
11849 |
|
11850 | default:
|
11851 | usedNames.add('exports');
|
11852 | for (const helper of HELPER_NAMES) {
|
11853 | usedNames.add(helper);
|
11854 | }
|
11855 | }
|
11856 | 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);
|
11857 | }
|
11858 | setUpChunkImportsAndExportsForModule(module) {
|
11859 | const moduleImports = new Set(module.imports);
|
11860 |
|
11861 |
|
11862 | if (!this.outputOptions.preserveModules) {
|
11863 | if (this.includedNamespaces.has(module)) {
|
11864 | const memberVariables = module.namespace.getMemberVariables();
|
11865 | for (const name of Object.keys(memberVariables)) {
|
11866 | moduleImports.add(memberVariables[name]);
|
11867 | }
|
11868 | }
|
11869 | }
|
11870 | for (let variable of moduleImports) {
|
11871 | if (variable instanceof ExportDefaultVariable) {
|
11872 | variable = variable.getOriginalVariable();
|
11873 | }
|
11874 | if (variable instanceof SyntheticNamedExportVariable) {
|
11875 | variable = variable.getBaseVariable();
|
11876 | }
|
11877 | const chunk = this.chunkByModule.get(variable.module);
|
11878 | if (chunk !== this) {
|
11879 | this.imports.add(variable);
|
11880 | if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
|
11881 | variable.module instanceof Module) {
|
11882 | chunk.exports.add(variable);
|
11883 | }
|
11884 | }
|
11885 | }
|
11886 | if (this.includedNamespaces.has(module) ||
|
11887 | (module.info.isEntry && module.preserveSignature !== false) ||
|
11888 | module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
|
11889 | this.ensureReexportsAreAvailableForModule(module);
|
11890 | }
|
11891 | for (const { node, resolution } of module.dynamicImports) {
|
11892 | if (node.included &&
|
11893 | resolution instanceof Module &&
|
11894 | this.chunkByModule.get(resolution) === this &&
|
11895 | !this.includedNamespaces.has(resolution)) {
|
11896 | this.includedNamespaces.add(resolution);
|
11897 | this.ensureReexportsAreAvailableForModule(resolution);
|
11898 | }
|
11899 | }
|
11900 | }
|
11901 | }
|
11902 |
|
11903 | const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
|
11904 | const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
|
11905 | async function createAddons(options, outputPluginDriver) {
|
11906 | try {
|
11907 | let [banner, footer, intro, outro] = await Promise.all([
|
11908 | outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
|
11909 | outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
|
11910 | outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
|
11911 | outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
|
11912 | ]);
|
11913 | if (intro)
|
11914 | intro += '\n\n';
|
11915 | if (outro)
|
11916 | outro = `\n\n${outro}`;
|
11917 | if (banner.length)
|
11918 | banner += '\n';
|
11919 | if (footer.length)
|
11920 | footer = '\n' + footer;
|
11921 | return { intro, outro, banner, footer };
|
11922 | }
|
11923 | catch (err) {
|
11924 | return error({
|
11925 | code: 'ADDON_ERROR',
|
11926 | message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
|
11927 | \tError Message: ${err.message}`
|
11928 | });
|
11929 | }
|
11930 | }
|
11931 |
|
11932 | function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
|
11933 | const chunkDefinitions = [];
|
11934 | const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
|
11935 | const manualChunkModulesByAlias = Object.create(null);
|
11936 | for (const [entry, alias] of manualChunkAliasByEntry) {
|
11937 | const chunkModules = (manualChunkModulesByAlias[alias] =
|
11938 | manualChunkModulesByAlias[alias] || []);
|
11939 | addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
|
11940 | }
|
11941 | for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
|
11942 | chunkDefinitions.push({ alias, modules });
|
11943 | }
|
11944 | const assignedEntryPointsByModule = new Map();
|
11945 | const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
|
11946 | const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
|
11947 | const staticEntries = new Set(entryModules);
|
11948 | function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
|
11949 | const modulesToHandle = new Set([entry]);
|
11950 | for (const module of modulesToHandle) {
|
11951 | const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
|
11952 | if (dynamicDependentEntryPoints &&
|
11953 | areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
|
11954 | continue;
|
11955 | }
|
11956 | else {
|
11957 | assignedEntryPoints.add(entry);
|
11958 | }
|
11959 | for (const dependency of module.getDependenciesToBeIncluded()) {
|
11960 | if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
|
11961 | modulesToHandle.add(dependency);
|
11962 | }
|
11963 | }
|
11964 | }
|
11965 | }
|
11966 | function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
|
11967 | const entriesToCheck = new Set(entryPoints);
|
11968 | for (const entry of entriesToCheck) {
|
11969 | if (!containedIn.has(entry)) {
|
11970 | if (staticEntries.has(entry))
|
11971 | return false;
|
11972 | const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
|
11973 | for (const dependentEntry of dynamicallyDependentEntryPoints) {
|
11974 | entriesToCheck.add(dependentEntry);
|
11975 | }
|
11976 | }
|
11977 | }
|
11978 | return true;
|
11979 | }
|
11980 | for (const entry of entryModules) {
|
11981 | if (!modulesInManualChunks.has(entry)) {
|
11982 | assignEntryToStaticDependencies(entry, null);
|
11983 | }
|
11984 | }
|
11985 | for (const entry of dynamicEntryModules) {
|
11986 | if (!modulesInManualChunks.has(entry)) {
|
11987 | assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
|
11988 | }
|
11989 | }
|
11990 | chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
|
11991 | return chunkDefinitions;
|
11992 | }
|
11993 | function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
|
11994 | const modulesToHandle = new Set([entry]);
|
11995 | for (const module of modulesToHandle) {
|
11996 | modulesInManualChunks.add(module);
|
11997 | manualChunkModules.push(module);
|
11998 | for (const dependency of module.dependencies) {
|
11999 | if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
|
12000 | modulesToHandle.add(dependency);
|
12001 | }
|
12002 | }
|
12003 | }
|
12004 | }
|
12005 | function analyzeModuleGraph(entryModules) {
|
12006 | const dynamicEntryModules = new Set();
|
12007 | const dependentEntryPointsByModule = new Map();
|
12008 | const entriesToHandle = new Set(entryModules);
|
12009 | for (const currentEntry of entriesToHandle) {
|
12010 | const modulesToHandle = new Set([currentEntry]);
|
12011 | for (const module of modulesToHandle) {
|
12012 | getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
|
12013 | for (const dependency of module.getDependenciesToBeIncluded()) {
|
12014 | if (!(dependency instanceof ExternalModule)) {
|
12015 | modulesToHandle.add(dependency);
|
12016 | }
|
12017 | }
|
12018 | for (const { resolution } of module.dynamicImports) {
|
12019 | if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
|
12020 | dynamicEntryModules.add(resolution);
|
12021 | entriesToHandle.add(resolution);
|
12022 | }
|
12023 | }
|
12024 | for (const dependency of module.implicitlyLoadedBefore) {
|
12025 | dynamicEntryModules.add(dependency);
|
12026 | entriesToHandle.add(dependency);
|
12027 | }
|
12028 | }
|
12029 | }
|
12030 | return { dependentEntryPointsByModule, dynamicEntryModules };
|
12031 | }
|
12032 | function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
|
12033 | const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
|
12034 | for (const dynamicEntry of dynamicEntryModules) {
|
12035 | const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
|
12036 | for (const importer of [
|
12037 | ...dynamicEntry.includedDynamicImporters,
|
12038 | ...dynamicEntry.implicitlyLoadedAfter
|
12039 | ]) {
|
12040 | for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
|
12041 | dynamicDependentEntryPoints.add(entryPoint);
|
12042 | }
|
12043 | }
|
12044 | }
|
12045 | return dynamicallyDependentEntryPointsByDynamicEntry;
|
12046 | }
|
12047 | function createChunks(allEntryPoints, assignedEntryPointsByModule) {
|
12048 | const chunkModules = Object.create(null);
|
12049 | for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
|
12050 | let chunkSignature = '';
|
12051 | for (const entry of allEntryPoints) {
|
12052 | chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
|
12053 | }
|
12054 | const chunk = chunkModules[chunkSignature];
|
12055 | if (chunk) {
|
12056 | chunk.push(module);
|
12057 | }
|
12058 | else {
|
12059 | chunkModules[chunkSignature] = [module];
|
12060 | }
|
12061 | }
|
12062 | return Object.keys(chunkModules).map(chunkSignature => ({
|
12063 | alias: null,
|
12064 | modules: chunkModules[chunkSignature]
|
12065 | }));
|
12066 | }
|
12067 |
|
12068 |
|
12069 | function commondir(files) {
|
12070 | if (files.length === 0)
|
12071 | return '/';
|
12072 | if (files.length === 1)
|
12073 | return sysPath.dirname(files[0]);
|
12074 | const commonSegments = files.slice(1).reduce((commonSegments, file) => {
|
12075 | const pathSegements = file.split(/\/+|\\+/);
|
12076 | let i;
|
12077 | for (i = 0; commonSegments[i] === pathSegements[i] &&
|
12078 | i < Math.min(commonSegments.length, pathSegements.length); i++)
|
12079 | ;
|
12080 | return commonSegments.slice(0, i);
|
12081 | }, files[0].split(/\/+|\\+/));
|
12082 |
|
12083 | return commonSegments.length > 1 ? commonSegments.join('/') : '/';
|
12084 | }
|
12085 |
|
12086 | var BuildPhase;
|
12087 | (function (BuildPhase) {
|
12088 | BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
|
12089 | BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
|
12090 | BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
|
12091 | })(BuildPhase || (BuildPhase = {}));
|
12092 |
|
12093 | function generateAssetFileName(name, source, output) {
|
12094 | const emittedName = name || 'asset';
|
12095 | return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
|
12096 | hash() {
|
12097 | const hash = createHash();
|
12098 | hash.update(emittedName);
|
12099 | hash.update(':');
|
12100 | hash.update(source);
|
12101 | return hash.digest('hex').substr(0, 8);
|
12102 | },
|
12103 | ext: () => sysPath.extname(emittedName).substr(1),
|
12104 | extname: () => sysPath.extname(emittedName),
|
12105 | name: () => emittedName.substr(0, emittedName.length - sysPath.extname(emittedName).length)
|
12106 | }, () => ({ name, source, type: 'asset' })), output.bundle);
|
12107 | }
|
12108 | function reserveFileNameInBundle(fileName, bundle, warn) {
|
12109 | if (fileName in bundle) {
|
12110 | warn(errFileNameConflict(fileName));
|
12111 | }
|
12112 | bundle[fileName] = FILE_PLACEHOLDER;
|
12113 | }
|
12114 | const FILE_PLACEHOLDER = {
|
12115 | type: 'placeholder'
|
12116 | };
|
12117 | function hasValidType(emittedFile) {
|
12118 | return (emittedFile &&
|
12119 | (emittedFile.type === 'asset' ||
|
12120 | emittedFile.type === 'chunk'));
|
12121 | }
|
12122 | function hasValidName(emittedFile) {
|
12123 | const validatedName = emittedFile.fileName || emittedFile.name;
|
12124 | return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
|
12125 | }
|
12126 | function getValidSource(source, emittedFile, fileReferenceId) {
|
12127 | if (!(typeof source === 'string' || source instanceof Uint8Array)) {
|
12128 | const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
|
12129 | 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.`));
|
12130 | }
|
12131 | return source;
|
12132 | }
|
12133 | function getAssetFileName(file, referenceId) {
|
12134 | if (typeof file.fileName !== 'string') {
|
12135 | return error(errAssetNotFinalisedForFileName(file.name || referenceId));
|
12136 | }
|
12137 | return file.fileName;
|
12138 | }
|
12139 | function getChunkFileName(file, facadeChunkByModule) {
|
12140 | var _a;
|
12141 | 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));
|
12142 | if (!fileName)
|
12143 | return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
|
12144 | return fileName;
|
12145 | }
|
12146 | class FileEmitter {
|
12147 | constructor(graph, options, baseFileEmitter) {
|
12148 | this.graph = graph;
|
12149 | this.options = options;
|
12150 | this.facadeChunkByModule = null;
|
12151 | this.output = null;
|
12152 | this.assertAssetsFinalized = () => {
|
12153 | for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
|
12154 | if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
|
12155 | return error(errNoAssetSourceSet(emittedFile.name || referenceId));
|
12156 | }
|
12157 | };
|
12158 | this.emitFile = (emittedFile) => {
|
12159 | if (!hasValidType(emittedFile)) {
|
12160 | return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
|
12161 | }
|
12162 | if (!hasValidName(emittedFile)) {
|
12163 | return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || emittedFile.name}".`));
|
12164 | }
|
12165 | if (emittedFile.type === 'chunk') {
|
12166 | return this.emitChunk(emittedFile);
|
12167 | }
|
12168 | else {
|
12169 | return this.emitAsset(emittedFile);
|
12170 | }
|
12171 | };
|
12172 | this.getFileName = (fileReferenceId) => {
|
12173 | const emittedFile = this.filesByReferenceId.get(fileReferenceId);
|
12174 | if (!emittedFile)
|
12175 | return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
|
12176 | if (emittedFile.type === 'chunk') {
|
12177 | return getChunkFileName(emittedFile, this.facadeChunkByModule);
|
12178 | }
|
12179 | else {
|
12180 | return getAssetFileName(emittedFile, fileReferenceId);
|
12181 | }
|
12182 | };
|
12183 | this.setAssetSource = (referenceId, requestedSource) => {
|
12184 | const consumedFile = this.filesByReferenceId.get(referenceId);
|
12185 | if (!consumedFile)
|
12186 | return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
|
12187 | if (consumedFile.type !== 'asset') {
|
12188 | return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
|
12189 | }
|
12190 | if (consumedFile.source !== undefined) {
|
12191 | return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
|
12192 | }
|
12193 | const source = getValidSource(requestedSource, consumedFile, referenceId);
|
12194 | if (this.output) {
|
12195 | this.finalizeAsset(consumedFile, source, referenceId, this.output);
|
12196 | }
|
12197 | else {
|
12198 | consumedFile.source = source;
|
12199 | }
|
12200 | };
|
12201 | this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
|
12202 | this.output = {
|
12203 | assetFileNames,
|
12204 | bundle: outputBundle
|
12205 | };
|
12206 | this.facadeChunkByModule = facadeChunkByModule;
|
12207 | for (const emittedFile of this.filesByReferenceId.values()) {
|
12208 | if (emittedFile.fileName) {
|
12209 | reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
|
12210 | }
|
12211 | }
|
12212 | for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
|
12213 | if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
|
12214 | this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
|
12215 | }
|
12216 | }
|
12217 | };
|
12218 | this.filesByReferenceId = baseFileEmitter
|
12219 | ? new Map(baseFileEmitter.filesByReferenceId)
|
12220 | : new Map();
|
12221 | }
|
12222 | assignReferenceId(file, idBase) {
|
12223 | let referenceId;
|
12224 | do {
|
12225 | const hash = createHash();
|
12226 | if (referenceId) {
|
12227 | hash.update(referenceId);
|
12228 | }
|
12229 | else {
|
12230 | hash.update(idBase);
|
12231 | }
|
12232 | referenceId = hash.digest('hex').substr(0, 8);
|
12233 | } while (this.filesByReferenceId.has(referenceId));
|
12234 | this.filesByReferenceId.set(referenceId, file);
|
12235 | return referenceId;
|
12236 | }
|
12237 | emitAsset(emittedAsset) {
|
12238 | const source = typeof emittedAsset.source !== 'undefined'
|
12239 | ? getValidSource(emittedAsset.source, emittedAsset, null)
|
12240 | : undefined;
|
12241 | const consumedAsset = {
|
12242 | fileName: emittedAsset.fileName,
|
12243 | name: emittedAsset.name,
|
12244 | source,
|
12245 | type: 'asset'
|
12246 | };
|
12247 | const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
|
12248 | if (this.output) {
|
12249 | if (emittedAsset.fileName) {
|
12250 | reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
|
12251 | }
|
12252 | if (source !== undefined) {
|
12253 | this.finalizeAsset(consumedAsset, source, referenceId, this.output);
|
12254 | }
|
12255 | }
|
12256 | return referenceId;
|
12257 | }
|
12258 | emitChunk(emittedChunk) {
|
12259 | if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
|
12260 | return error(errInvalidRollupPhaseForChunkEmission());
|
12261 | }
|
12262 | if (typeof emittedChunk.id !== 'string') {
|
12263 | return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
|
12264 | }
|
12265 | const consumedChunk = {
|
12266 | fileName: emittedChunk.fileName,
|
12267 | module: null,
|
12268 | name: emittedChunk.name || emittedChunk.id,
|
12269 | type: 'chunk'
|
12270 | };
|
12271 | this.graph.moduleLoader
|
12272 | .emitChunk(emittedChunk)
|
12273 | .then(module => (consumedChunk.module = module))
|
12274 | .catch(() => {
|
12275 |
|
12276 |
|
12277 | });
|
12278 | return this.assignReferenceId(consumedChunk, emittedChunk.id);
|
12279 | }
|
12280 | finalizeAsset(consumedFile, source, referenceId, output) {
|
12281 | const fileName = consumedFile.fileName ||
|
12282 | findExistingAssetFileNameWithSource(output.bundle, source) ||
|
12283 | generateAssetFileName(consumedFile.name, source, output);
|
12284 |
|
12285 | const assetWithFileName = { ...consumedFile, source, fileName };
|
12286 | this.filesByReferenceId.set(referenceId, assetWithFileName);
|
12287 | const options = this.options;
|
12288 | output.bundle[fileName] = {
|
12289 | fileName,
|
12290 | name: consumedFile.name,
|
12291 | get isAsset() {
|
12292 | warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
|
12293 | return true;
|
12294 | },
|
12295 | source,
|
12296 | type: 'asset'
|
12297 | };
|
12298 | }
|
12299 | }
|
12300 | function findExistingAssetFileNameWithSource(bundle, source) {
|
12301 | for (const fileName of Object.keys(bundle)) {
|
12302 | const outputFile = bundle[fileName];
|
12303 | if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
|
12304 | return fileName;
|
12305 | }
|
12306 | return null;
|
12307 | }
|
12308 | function areSourcesEqual(sourceA, sourceB) {
|
12309 | if (typeof sourceA === 'string') {
|
12310 | return sourceA === sourceB;
|
12311 | }
|
12312 | if (typeof sourceB === 'string') {
|
12313 | return false;
|
12314 | }
|
12315 | if ('equals' in sourceA) {
|
12316 | return sourceA.equals(sourceB);
|
12317 | }
|
12318 | if (sourceA.length !== sourceB.length) {
|
12319 | return false;
|
12320 | }
|
12321 | for (let index = 0; index < sourceA.length; index++) {
|
12322 | if (sourceA[index] !== sourceB[index]) {
|
12323 | return false;
|
12324 | }
|
12325 | }
|
12326 | return true;
|
12327 | }
|
12328 |
|
12329 | class Bundle$1 {
|
12330 | constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
|
12331 | this.outputOptions = outputOptions;
|
12332 | this.unsetOptions = unsetOptions;
|
12333 | this.inputOptions = inputOptions;
|
12334 | this.pluginDriver = pluginDriver;
|
12335 | this.graph = graph;
|
12336 | this.facadeChunkByModule = new Map();
|
12337 | this.includedNamespaces = new Set();
|
12338 | }
|
12339 | async generate(isWrite) {
|
12340 | timeStart('GENERATE', 1);
|
12341 | const outputBundle = Object.create(null);
|
12342 | this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
|
12343 | try {
|
12344 | await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
|
12345 | timeStart('generate chunks', 2);
|
12346 | const chunks = await this.generateChunks();
|
12347 | if (chunks.length > 1) {
|
12348 | validateOptionsForMultiChunkOutput(this.outputOptions);
|
12349 | }
|
12350 | const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
|
12351 | timeEnd('generate chunks', 2);
|
12352 | timeStart('render modules', 2);
|
12353 |
|
12354 |
|
12355 | const addons = await createAddons(this.outputOptions, this.pluginDriver);
|
12356 | this.prerenderChunks(chunks, inputBase);
|
12357 | timeEnd('render modules', 2);
|
12358 | await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
|
12359 | }
|
12360 | catch (error) {
|
12361 | await this.pluginDriver.hookParallel('renderError', [error]);
|
12362 | throw error;
|
12363 | }
|
12364 | await this.pluginDriver.hookSeq('generateBundle', [
|
12365 | this.outputOptions,
|
12366 | outputBundle,
|
12367 | isWrite
|
12368 | ]);
|
12369 | this.finaliseAssets(outputBundle);
|
12370 | timeEnd('GENERATE', 1);
|
12371 | return outputBundle;
|
12372 | }
|
12373 | async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
|
12374 | this.assignChunkIds(chunks, inputBase, addons, outputBundle);
|
12375 | for (const chunk of chunks) {
|
12376 | outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
|
12377 | }
|
12378 | await Promise.all(chunks.map(async (chunk) => {
|
12379 | const outputChunk = outputBundle[chunk.id];
|
12380 | Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
|
12381 | }));
|
12382 | }
|
12383 | async addManualChunks(manualChunks) {
|
12384 | const manualChunkAliasByEntry = new Map();
|
12385 | const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
|
12386 | alias,
|
12387 | entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
|
12388 | })));
|
12389 | for (const { alias, entries } of chunkEntries) {
|
12390 | for (const entry of entries) {
|
12391 | addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
|
12392 | }
|
12393 | }
|
12394 | return manualChunkAliasByEntry;
|
12395 | }
|
12396 | assignChunkIds(chunks, inputBase, addons, bundle) {
|
12397 | const entryChunks = [];
|
12398 | const otherChunks = [];
|
12399 | for (const chunk of chunks) {
|
12400 | (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
|
12401 | ? entryChunks
|
12402 | : otherChunks).push(chunk);
|
12403 | }
|
12404 |
|
12405 | const chunksForNaming = entryChunks.concat(otherChunks);
|
12406 | for (const chunk of chunksForNaming) {
|
12407 | if (this.outputOptions.file) {
|
12408 | chunk.id = sysPath.basename(this.outputOptions.file);
|
12409 | }
|
12410 | else if (this.outputOptions.preserveModules) {
|
12411 | chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
|
12412 | }
|
12413 | else {
|
12414 | chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
|
12415 | }
|
12416 | bundle[chunk.id] = FILE_PLACEHOLDER;
|
12417 | }
|
12418 | }
|
12419 | assignManualChunks(getManualChunk) {
|
12420 | const manualChunkAliasByEntry = new Map();
|
12421 | const manualChunksApi = {
|
12422 | getModuleIds: () => this.graph.modulesById.keys(),
|
12423 | getModuleInfo: this.graph.getModuleInfo
|
12424 | };
|
12425 | for (const module of this.graph.modulesById.values()) {
|
12426 | if (module instanceof Module) {
|
12427 | const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
|
12428 | if (typeof manualChunkAlias === 'string') {
|
12429 | addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
|
12430 | }
|
12431 | }
|
12432 | }
|
12433 | return manualChunkAliasByEntry;
|
12434 | }
|
12435 | finaliseAssets(outputBundle) {
|
12436 | for (const key of Object.keys(outputBundle)) {
|
12437 | const file = outputBundle[key];
|
12438 | if (!file.type) {
|
12439 | 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);
|
12440 | file.type = 'asset';
|
12441 | }
|
12442 | }
|
12443 | this.pluginDriver.finaliseAssets();
|
12444 | }
|
12445 | async generateChunks() {
|
12446 | const { manualChunks } = this.outputOptions;
|
12447 | const manualChunkAliasByEntry = typeof manualChunks === 'object'
|
12448 | ? await this.addManualChunks(manualChunks)
|
12449 | : this.assignManualChunks(manualChunks);
|
12450 | const chunks = [];
|
12451 | const chunkByModule = new Map();
|
12452 | for (const { alias, modules } of this.outputOptions.inlineDynamicImports
|
12453 | ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
|
12454 | : this.outputOptions.preserveModules
|
12455 | ? getIncludedModules(this.graph.modulesById).map(module => ({
|
12456 | alias: null,
|
12457 | modules: [module]
|
12458 | }))
|
12459 | : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
|
12460 | sortByExecutionOrder(modules);
|
12461 | const chunk = new Chunk$1(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
|
12462 | chunks.push(chunk);
|
12463 | for (const module of modules) {
|
12464 | chunkByModule.set(module, chunk);
|
12465 | }
|
12466 | }
|
12467 | for (const chunk of chunks) {
|
12468 | chunk.link();
|
12469 | }
|
12470 | const facades = [];
|
12471 | for (const chunk of chunks) {
|
12472 | facades.push(...chunk.generateFacades());
|
12473 | }
|
12474 | return [...chunks, ...facades];
|
12475 | }
|
12476 | prerenderChunks(chunks, inputBase) {
|
12477 | for (const chunk of chunks) {
|
12478 | chunk.generateExports();
|
12479 | }
|
12480 | for (const chunk of chunks) {
|
12481 | chunk.preRender(this.outputOptions, inputBase);
|
12482 | }
|
12483 | }
|
12484 | }
|
12485 | function getAbsoluteEntryModulePaths(chunks) {
|
12486 | const absoluteEntryModulePaths = [];
|
12487 | for (const chunk of chunks) {
|
12488 | for (const entryModule of chunk.entryModules) {
|
12489 | if (isAbsolute(entryModule.id)) {
|
12490 | absoluteEntryModulePaths.push(entryModule.id);
|
12491 | }
|
12492 | }
|
12493 | }
|
12494 | return absoluteEntryModulePaths;
|
12495 | }
|
12496 | function validateOptionsForMultiChunkOutput(outputOptions) {
|
12497 | if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
|
12498 | return error({
|
12499 | code: 'INVALID_OPTION',
|
12500 | message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
|
12501 | });
|
12502 | if (typeof outputOptions.file === 'string')
|
12503 | return error({
|
12504 | code: 'INVALID_OPTION',
|
12505 | message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
|
12506 | 'To inline dynamic imports, set the "inlineDynamicImports" option.'
|
12507 | });
|
12508 | if (outputOptions.sourcemapFile)
|
12509 | return error({
|
12510 | code: 'INVALID_OPTION',
|
12511 | message: '"output.sourcemapFile" is only supported for single-file builds.'
|
12512 | });
|
12513 | }
|
12514 | function getIncludedModules(modulesById) {
|
12515 | return [...modulesById.values()].filter(module => module instanceof Module &&
|
12516 | (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
|
12517 | }
|
12518 | function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
|
12519 | const existingAlias = manualChunkAliasByEntry.get(module);
|
12520 | if (typeof existingAlias === 'string' && existingAlias !== alias) {
|
12521 | return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
|
12522 | }
|
12523 | manualChunkAliasByEntry.set(module, alias);
|
12524 | }
|
12525 |
|
12526 |
|
12527 |
|
12528 | var reservedWords$1 = {
|
12529 | 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",
|
12530 | 5: "class enum extends super const export import",
|
12531 | 6: "enum",
|
12532 | strict: "implements interface let package private protected public static yield",
|
12533 | strictBind: "eval arguments"
|
12534 | };
|
12535 |
|
12536 |
|
12537 |
|
12538 | var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
|
12539 |
|
12540 | var keywords = {
|
12541 | 5: ecma5AndLessKeywords,
|
12542 | "5module": ecma5AndLessKeywords + " export import",
|
12543 | 6: ecma5AndLessKeywords + " const class extends export import super"
|
12544 | };
|
12545 |
|
12546 | var keywordRelationalOperator = /^in(stanceof)?$/;
|
12547 |
|
12548 |
|
12549 |
|
12550 |
|
12551 |
|
12552 |
|
12553 |
|
12554 |
|
12555 | var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
|
12556 | var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
|
12557 |
|
12558 | var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
|
12559 | var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
|
12560 |
|
12561 | nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
|
12562 |
|
12563 |
|
12564 |
|
12565 |
|
12566 |
|
12567 |
|
12568 |
|
12569 |
|
12570 | var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
|
12571 |
|
12572 |
|
12573 | var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
|
12574 |
|
12575 |
|
12576 |
|
12577 |
|
12578 | function isInAstralSet(code, set) {
|
12579 | var pos = 0x10000;
|
12580 | for (var i = 0; i < set.length; i += 2) {
|
12581 | pos += set[i];
|
12582 | if (pos > code) { return false }
|
12583 | pos += set[i + 1];
|
12584 | if (pos >= code) { return true }
|
12585 | }
|
12586 | }
|
12587 |
|
12588 |
|
12589 |
|
12590 | function isIdentifierStart(code, astral) {
|
12591 | if (code < 65) { return code === 36 }
|
12592 | if (code < 91) { return true }
|
12593 | if (code < 97) { return code === 95 }
|
12594 | if (code < 123) { return true }
|
12595 | if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
|
12596 | if (astral === false) { return false }
|
12597 | return isInAstralSet(code, astralIdentifierStartCodes)
|
12598 | }
|
12599 |
|
12600 |
|
12601 |
|
12602 | function isIdentifierChar(code, astral) {
|
12603 | if (code < 48) { return code === 36 }
|
12604 | if (code < 58) { return true }
|
12605 | if (code < 65) { return false }
|
12606 | if (code < 91) { return true }
|
12607 | if (code < 97) { return code === 95 }
|
12608 | if (code < 123) { return true }
|
12609 | if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
|
12610 | if (astral === false) { return false }
|
12611 | return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
|
12612 | }
|
12613 |
|
12614 |
|
12615 |
|
12616 |
|
12617 |
|
12618 |
|
12619 |
|
12620 |
|
12621 |
|
12622 |
|
12623 |
|
12624 |
|
12625 |
|
12626 |
|
12627 |
|
12628 |
|
12629 |
|
12630 |
|
12631 |
|
12632 |
|
12633 |
|
12634 |
|
12635 |
|
12636 |
|
12637 | var TokenType = function TokenType(label, conf) {
|
12638 | if ( conf === void 0 ) conf = {};
|
12639 |
|
12640 | this.label = label;
|
12641 | this.keyword = conf.keyword;
|
12642 | this.beforeExpr = !!conf.beforeExpr;
|
12643 | this.startsExpr = !!conf.startsExpr;
|
12644 | this.isLoop = !!conf.isLoop;
|
12645 | this.isAssign = !!conf.isAssign;
|
12646 | this.prefix = !!conf.prefix;
|
12647 | this.postfix = !!conf.postfix;
|
12648 | this.binop = conf.binop || null;
|
12649 | this.updateContext = null;
|
12650 | };
|
12651 |
|
12652 | function binop(name, prec) {
|
12653 | return new TokenType(name, {beforeExpr: true, binop: prec})
|
12654 | }
|
12655 | var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
|
12656 |
|
12657 |
|
12658 |
|
12659 | var keywords$1 = {};
|
12660 |
|
12661 |
|
12662 | function kw(name, options) {
|
12663 | if ( options === void 0 ) options = {};
|
12664 |
|
12665 | options.keyword = name;
|
12666 | return keywords$1[name] = new TokenType(name, options)
|
12667 | }
|
12668 |
|
12669 | var types = {
|
12670 | num: new TokenType("num", startsExpr),
|
12671 | regexp: new TokenType("regexp", startsExpr),
|
12672 | string: new TokenType("string", startsExpr),
|
12673 | name: new TokenType("name", startsExpr),
|
12674 | eof: new TokenType("eof"),
|
12675 |
|
12676 |
|
12677 | bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
|
12678 | bracketR: new TokenType("]"),
|
12679 | braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
|
12680 | braceR: new TokenType("}"),
|
12681 | parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
|
12682 | parenR: new TokenType(")"),
|
12683 | comma: new TokenType(",", beforeExpr),
|
12684 | semi: new TokenType(";", beforeExpr),
|
12685 | colon: new TokenType(":", beforeExpr),
|
12686 | dot: new TokenType("."),
|
12687 | question: new TokenType("?", beforeExpr),
|
12688 | questionDot: new TokenType("?."),
|
12689 | arrow: new TokenType("=>", beforeExpr),
|
12690 | template: new TokenType("template"),
|
12691 | invalidTemplate: new TokenType("invalidTemplate"),
|
12692 | ellipsis: new TokenType("...", beforeExpr),
|
12693 | backQuote: new TokenType("`", startsExpr),
|
12694 | dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
|
12695 |
|
12696 |
|
12697 |
|
12698 |
|
12699 |
|
12700 |
|
12701 |
|
12702 |
|
12703 |
|
12704 |
|
12705 |
|
12706 |
|
12707 |
|
12708 |
|
12709 |
|
12710 | eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
|
12711 | assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
|
12712 | incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
|
12713 | prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
|
12714 | logicalOR: binop("||", 1),
|
12715 | logicalAND: binop("&&", 2),
|
12716 | bitwiseOR: binop("|", 3),
|
12717 | bitwiseXOR: binop("^", 4),
|
12718 | bitwiseAND: binop("&", 5),
|
12719 | equality: binop("==/!=/===/!==", 6),
|
12720 | relational: binop("</>/<=/>=", 7),
|
12721 | bitShift: binop("<</>>/>>>", 8),
|
12722 | plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
|
12723 | modulo: binop("%", 10),
|
12724 | star: binop("*", 10),
|
12725 | slash: binop("/", 10),
|
12726 | starstar: new TokenType("**", {beforeExpr: true}),
|
12727 | coalesce: binop("??", 1),
|
12728 |
|
12729 |
|
12730 | _break: kw("break"),
|
12731 | _case: kw("case", beforeExpr),
|
12732 | _catch: kw("catch"),
|
12733 | _continue: kw("continue"),
|
12734 | _debugger: kw("debugger"),
|
12735 | _default: kw("default", beforeExpr),
|
12736 | _do: kw("do", {isLoop: true, beforeExpr: true}),
|
12737 | _else: kw("else", beforeExpr),
|
12738 | _finally: kw("finally"),
|
12739 | _for: kw("for", {isLoop: true}),
|
12740 | _function: kw("function", startsExpr),
|
12741 | _if: kw("if"),
|
12742 | _return: kw("return", beforeExpr),
|
12743 | _switch: kw("switch"),
|
12744 | _throw: kw("throw", beforeExpr),
|
12745 | _try: kw("try"),
|
12746 | _var: kw("var"),
|
12747 | _const: kw("const"),
|
12748 | _while: kw("while", {isLoop: true}),
|
12749 | _with: kw("with"),
|
12750 | _new: kw("new", {beforeExpr: true, startsExpr: true}),
|
12751 | _this: kw("this", startsExpr),
|
12752 | _super: kw("super", startsExpr),
|
12753 | _class: kw("class", startsExpr),
|
12754 | _extends: kw("extends", beforeExpr),
|
12755 | _export: kw("export"),
|
12756 | _import: kw("import", startsExpr),
|
12757 | _null: kw("null", startsExpr),
|
12758 | _true: kw("true", startsExpr),
|
12759 | _false: kw("false", startsExpr),
|
12760 | _in: kw("in", {beforeExpr: true, binop: 7}),
|
12761 | _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
|
12762 | _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
|
12763 | _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
|
12764 | _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
|
12765 | };
|
12766 |
|
12767 |
|
12768 |
|
12769 |
|
12770 | var lineBreak = /\r\n?|\n|\u2028|\u2029/;
|
12771 | var lineBreakG = new RegExp(lineBreak.source, "g");
|
12772 |
|
12773 | function isNewLine(code, ecma2019String) {
|
12774 | return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
|
12775 | }
|
12776 |
|
12777 | var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
|
12778 |
|
12779 | var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
|
12780 |
|
12781 | var ref = Object.prototype;
|
12782 | var hasOwnProperty = ref.hasOwnProperty;
|
12783 | var toString$1 = ref.toString;
|
12784 |
|
12785 |
|
12786 |
|
12787 | function has(obj, propName) {
|
12788 | return hasOwnProperty.call(obj, propName)
|
12789 | }
|
12790 |
|
12791 | var isArray = Array.isArray || (function (obj) { return (
|
12792 | toString$1.call(obj) === "[object Array]"
|
12793 | ); });
|
12794 |
|
12795 | function wordsRegexp(words) {
|
12796 | return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
|
12797 | }
|
12798 |
|
12799 |
|
12800 |
|
12801 |
|
12802 | var Position = function Position(line, col) {
|
12803 | this.line = line;
|
12804 | this.column = col;
|
12805 | };
|
12806 |
|
12807 | Position.prototype.offset = function offset (n) {
|
12808 | return new Position(this.line, this.column + n)
|
12809 | };
|
12810 |
|
12811 | var SourceLocation = function SourceLocation(p, start, end) {
|
12812 | this.start = start;
|
12813 | this.end = end;
|
12814 | if (p.sourceFile !== null) { this.source = p.sourceFile; }
|
12815 | };
|
12816 |
|
12817 |
|
12818 |
|
12819 |
|
12820 |
|
12821 |
|
12822 |
|
12823 | function getLineInfo(input, offset) {
|
12824 | for (var line = 1, cur = 0;;) {
|
12825 | lineBreakG.lastIndex = cur;
|
12826 | var match = lineBreakG.exec(input);
|
12827 | if (match && match.index < offset) {
|
12828 | ++line;
|
12829 | cur = match.index + match[0].length;
|
12830 | } else {
|
12831 | return new Position(line, offset - cur)
|
12832 | }
|
12833 | }
|
12834 | }
|
12835 |
|
12836 |
|
12837 |
|
12838 |
|
12839 | var defaultOptions = {
|
12840 |
|
12841 |
|
12842 |
|
12843 |
|
12844 |
|
12845 | ecmaVersion: null,
|
12846 |
|
12847 |
|
12848 |
|
12849 | sourceType: "script",
|
12850 |
|
12851 |
|
12852 |
|
12853 |
|
12854 |
|
12855 | onInsertedSemicolon: null,
|
12856 |
|
12857 |
|
12858 | onTrailingComma: null,
|
12859 |
|
12860 |
|
12861 |
|
12862 |
|
12863 | allowReserved: null,
|
12864 |
|
12865 |
|
12866 | allowReturnOutsideFunction: false,
|
12867 |
|
12868 |
|
12869 | allowImportExportEverywhere: false,
|
12870 |
|
12871 |
|
12872 | allowAwaitOutsideFunction: false,
|
12873 |
|
12874 |
|
12875 | allowHashBang: false,
|
12876 |
|
12877 |
|
12878 |
|
12879 |
|
12880 | locations: false,
|
12881 |
|
12882 |
|
12883 |
|
12884 |
|
12885 |
|
12886 | onToken: null,
|
12887 |
|
12888 |
|
12889 |
|
12890 |
|
12891 |
|
12892 |
|
12893 |
|
12894 |
|
12895 |
|
12896 |
|
12897 | onComment: null,
|
12898 |
|
12899 |
|
12900 |
|
12901 |
|
12902 |
|
12903 |
|
12904 |
|
12905 |
|
12906 | ranges: false,
|
12907 |
|
12908 |
|
12909 |
|
12910 |
|
12911 |
|
12912 | program: null,
|
12913 |
|
12914 |
|
12915 | sourceFile: null,
|
12916 |
|
12917 |
|
12918 | directSourceFile: null,
|
12919 |
|
12920 |
|
12921 | preserveParens: false
|
12922 | };
|
12923 |
|
12924 |
|
12925 |
|
12926 | var warnedAboutEcmaVersion = false;
|
12927 |
|
12928 | function getOptions(opts) {
|
12929 | var options = {};
|
12930 |
|
12931 | for (var opt in defaultOptions)
|
12932 | { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
|
12933 |
|
12934 | if (options.ecmaVersion === "latest") {
|
12935 | options.ecmaVersion = 1e8;
|
12936 | } else if (options.ecmaVersion == null) {
|
12937 | if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
|
12938 | warnedAboutEcmaVersion = true;
|
12939 | console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
|
12940 | }
|
12941 | options.ecmaVersion = 11;
|
12942 | } else if (options.ecmaVersion >= 2015) {
|
12943 | options.ecmaVersion -= 2009;
|
12944 | }
|
12945 |
|
12946 | if (options.allowReserved == null)
|
12947 | { options.allowReserved = options.ecmaVersion < 5; }
|
12948 |
|
12949 | if (isArray(options.onToken)) {
|
12950 | var tokens = options.onToken;
|
12951 | options.onToken = function (token) { return tokens.push(token); };
|
12952 | }
|
12953 | if (isArray(options.onComment))
|
12954 | { options.onComment = pushComment(options, options.onComment); }
|
12955 |
|
12956 | return options
|
12957 | }
|
12958 |
|
12959 | function pushComment(options, array) {
|
12960 | return function(block, text, start, end, startLoc, endLoc) {
|
12961 | var comment = {
|
12962 | type: block ? "Block" : "Line",
|
12963 | value: text,
|
12964 | start: start,
|
12965 | end: end
|
12966 | };
|
12967 | if (options.locations)
|
12968 | { comment.loc = new SourceLocation(this, startLoc, endLoc); }
|
12969 | if (options.ranges)
|
12970 | { comment.range = [start, end]; }
|
12971 | array.push(comment);
|
12972 | }
|
12973 | }
|
12974 |
|
12975 |
|
12976 | var
|
12977 | SCOPE_TOP = 1,
|
12978 | SCOPE_FUNCTION = 2,
|
12979 | SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
|
12980 | SCOPE_ASYNC = 4,
|
12981 | SCOPE_GENERATOR = 8,
|
12982 | SCOPE_ARROW = 16,
|
12983 | SCOPE_SIMPLE_CATCH = 32,
|
12984 | SCOPE_SUPER = 64,
|
12985 | SCOPE_DIRECT_SUPER = 128;
|
12986 |
|
12987 | function functionFlags(async, generator) {
|
12988 | return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
|
12989 | }
|
12990 |
|
12991 |
|
12992 | var
|
12993 | BIND_NONE = 0,
|
12994 | BIND_VAR = 1,
|
12995 | BIND_LEXICAL = 2,
|
12996 | BIND_FUNCTION = 3,
|
12997 | BIND_SIMPLE_CATCH = 4,
|
12998 | BIND_OUTSIDE = 5;
|
12999 |
|
13000 | var Parser = function Parser(options, input, startPos) {
|
13001 | this.options = options = getOptions(options);
|
13002 | this.sourceFile = options.sourceFile;
|
13003 | this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
|
13004 | var reserved = "";
|
13005 | if (options.allowReserved !== true) {
|
13006 | reserved = reservedWords$1[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
|
13007 | if (options.sourceType === "module") { reserved += " await"; }
|
13008 | }
|
13009 | this.reservedWords = wordsRegexp(reserved);
|
13010 | var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
|
13011 | this.reservedWordsStrict = wordsRegexp(reservedStrict);
|
13012 | this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords$1.strictBind);
|
13013 | this.input = String(input);
|
13014 |
|
13015 |
|
13016 |
|
13017 |
|
13018 | this.containsEsc = false;
|
13019 |
|
13020 |
|
13021 |
|
13022 |
|
13023 | if (startPos) {
|
13024 | this.pos = startPos;
|
13025 | this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
|
13026 | this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
|
13027 | } else {
|
13028 | this.pos = this.lineStart = 0;
|
13029 | this.curLine = 1;
|
13030 | }
|
13031 |
|
13032 |
|
13033 |
|
13034 | this.type = types.eof;
|
13035 |
|
13036 | this.value = null;
|
13037 |
|
13038 | this.start = this.end = this.pos;
|
13039 |
|
13040 |
|
13041 | this.startLoc = this.endLoc = this.curPosition();
|
13042 |
|
13043 |
|
13044 | this.lastTokEndLoc = this.lastTokStartLoc = null;
|
13045 | this.lastTokStart = this.lastTokEnd = this.pos;
|
13046 |
|
13047 |
|
13048 |
|
13049 |
|
13050 | this.context = this.initialContext();
|
13051 | this.exprAllowed = true;
|
13052 |
|
13053 |
|
13054 | this.inModule = options.sourceType === "module";
|
13055 | this.strict = this.inModule || this.strictDirective(this.pos);
|
13056 |
|
13057 |
|
13058 | this.potentialArrowAt = -1;
|
13059 |
|
13060 |
|
13061 | this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
|
13062 |
|
13063 | this.labels = [];
|
13064 |
|
13065 | this.undefinedExports = {};
|
13066 |
|
13067 |
|
13068 | if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
|
13069 | { this.skipLineComment(2); }
|
13070 |
|
13071 |
|
13072 | this.scopeStack = [];
|
13073 | this.enterScope(SCOPE_TOP);
|
13074 |
|
13075 |
|
13076 | this.regexpState = null;
|
13077 | };
|
13078 |
|
13079 | var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
|
13080 |
|
13081 | Parser.prototype.parse = function parse () {
|
13082 | var node = this.options.program || this.startNode();
|
13083 | this.nextToken();
|
13084 | return this.parseTopLevel(node)
|
13085 | };
|
13086 |
|
13087 | prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
|
13088 | prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
|
13089 | prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
|
13090 | prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
|
13091 | prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
|
13092 | prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
|
13093 | prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
|
13094 |
|
13095 | Parser.extend = function extend () {
|
13096 | var plugins = [], len = arguments.length;
|
13097 | while ( len-- ) plugins[ len ] = arguments[ len ];
|
13098 |
|
13099 | var cls = this;
|
13100 | for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
|
13101 | return cls
|
13102 | };
|
13103 |
|
13104 | Parser.parse = function parse (input, options) {
|
13105 | return new this(options, input).parse()
|
13106 | };
|
13107 |
|
13108 | Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
|
13109 | var parser = new this(options, input, pos);
|
13110 | parser.nextToken();
|
13111 | return parser.parseExpression()
|
13112 | };
|
13113 |
|
13114 | Parser.tokenizer = function tokenizer (input, options) {
|
13115 | return new this(options, input)
|
13116 | };
|
13117 |
|
13118 | Object.defineProperties( Parser.prototype, prototypeAccessors );
|
13119 |
|
13120 | var pp = Parser.prototype;
|
13121 |
|
13122 |
|
13123 |
|
13124 | var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
|
13125 | pp.strictDirective = function(start) {
|
13126 | for (;;) {
|
13127 |
|
13128 | skipWhiteSpace.lastIndex = start;
|
13129 | start += skipWhiteSpace.exec(this.input)[0].length;
|
13130 | var match = literal.exec(this.input.slice(start));
|
13131 | if (!match) { return false }
|
13132 | if ((match[1] || match[2]) === "use strict") {
|
13133 | skipWhiteSpace.lastIndex = start + match[0].length;
|
13134 | var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
|
13135 | var next = this.input.charAt(end);
|
13136 | return next === ";" || next === "}" ||
|
13137 | (lineBreak.test(spaceAfter[0]) &&
|
13138 | !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
|
13139 | }
|
13140 | start += match[0].length;
|
13141 |
|
13142 |
|
13143 | skipWhiteSpace.lastIndex = start;
|
13144 | start += skipWhiteSpace.exec(this.input)[0].length;
|
13145 | if (this.input[start] === ";")
|
13146 | { start++; }
|
13147 | }
|
13148 | };
|
13149 |
|
13150 |
|
13151 |
|
13152 |
|
13153 | pp.eat = function(type) {
|
13154 | if (this.type === type) {
|
13155 | this.next();
|
13156 | return true
|
13157 | } else {
|
13158 | return false
|
13159 | }
|
13160 | };
|
13161 |
|
13162 |
|
13163 |
|
13164 | pp.isContextual = function(name) {
|
13165 | return this.type === types.name && this.value === name && !this.containsEsc
|
13166 | };
|
13167 |
|
13168 |
|
13169 |
|
13170 | pp.eatContextual = function(name) {
|
13171 | if (!this.isContextual(name)) { return false }
|
13172 | this.next();
|
13173 | return true
|
13174 | };
|
13175 |
|
13176 |
|
13177 |
|
13178 | pp.expectContextual = function(name) {
|
13179 | if (!this.eatContextual(name)) { this.unexpected(); }
|
13180 | };
|
13181 |
|
13182 |
|
13183 |
|
13184 | pp.canInsertSemicolon = function() {
|
13185 | return this.type === types.eof ||
|
13186 | this.type === types.braceR ||
|
13187 | lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
|
13188 | };
|
13189 |
|
13190 | pp.insertSemicolon = function() {
|
13191 | if (this.canInsertSemicolon()) {
|
13192 | if (this.options.onInsertedSemicolon)
|
13193 | { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
|
13194 | return true
|
13195 | }
|
13196 | };
|
13197 |
|
13198 |
|
13199 |
|
13200 |
|
13201 | pp.semicolon = function() {
|
13202 | if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
|
13203 | };
|
13204 |
|
13205 | pp.afterTrailingComma = function(tokType, notNext) {
|
13206 | if (this.type === tokType) {
|
13207 | if (this.options.onTrailingComma)
|
13208 | { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
|
13209 | if (!notNext)
|
13210 | { this.next(); }
|
13211 | return true
|
13212 | }
|
13213 | };
|
13214 |
|
13215 |
|
13216 |
|
13217 |
|
13218 | pp.expect = function(type) {
|
13219 | this.eat(type) || this.unexpected();
|
13220 | };
|
13221 |
|
13222 |
|
13223 |
|
13224 | pp.unexpected = function(pos) {
|
13225 | this.raise(pos != null ? pos : this.start, "Unexpected token");
|
13226 | };
|
13227 |
|
13228 | function DestructuringErrors() {
|
13229 | this.shorthandAssign =
|
13230 | this.trailingComma =
|
13231 | this.parenthesizedAssign =
|
13232 | this.parenthesizedBind =
|
13233 | this.doubleProto =
|
13234 | -1;
|
13235 | }
|
13236 |
|
13237 | pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
|
13238 | if (!refDestructuringErrors) { return }
|
13239 | if (refDestructuringErrors.trailingComma > -1)
|
13240 | { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
|
13241 | var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
|
13242 | if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
|
13243 | };
|
13244 |
|
13245 | pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
|
13246 | if (!refDestructuringErrors) { return false }
|
13247 | var shorthandAssign = refDestructuringErrors.shorthandAssign;
|
13248 | var doubleProto = refDestructuringErrors.doubleProto;
|
13249 | if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
|
13250 | if (shorthandAssign >= 0)
|
13251 | { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
|
13252 | if (doubleProto >= 0)
|
13253 | { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
|
13254 | };
|
13255 |
|
13256 | pp.checkYieldAwaitInDefaultParams = function() {
|
13257 | if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
|
13258 | { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
|
13259 | if (this.awaitPos)
|
13260 | { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
|
13261 | };
|
13262 |
|
13263 | pp.isSimpleAssignTarget = function(expr) {
|
13264 | if (expr.type === "ParenthesizedExpression")
|
13265 | { return this.isSimpleAssignTarget(expr.expression) }
|
13266 | return expr.type === "Identifier" || expr.type === "MemberExpression"
|
13267 | };
|
13268 |
|
13269 | var pp$1 = Parser.prototype;
|
13270 |
|
13271 |
|
13272 |
|
13273 |
|
13274 |
|
13275 |
|
13276 |
|
13277 |
|
13278 | pp$1.parseTopLevel = function(node) {
|
13279 | var exports = {};
|
13280 | if (!node.body) { node.body = []; }
|
13281 | while (this.type !== types.eof) {
|
13282 | var stmt = this.parseStatement(null, true, exports);
|
13283 | node.body.push(stmt);
|
13284 | }
|
13285 | if (this.inModule)
|
13286 | { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
|
13287 | {
|
13288 | var name = list[i];
|
13289 |
|
13290 | this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
|
13291 | } }
|
13292 | this.adaptDirectivePrologue(node.body);
|
13293 | this.next();
|
13294 | node.sourceType = this.options.sourceType;
|
13295 | return this.finishNode(node, "Program")
|
13296 | };
|
13297 |
|
13298 | var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
|
13299 |
|
13300 | pp$1.isLet = function(context) {
|
13301 | if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
|
13302 | skipWhiteSpace.lastIndex = this.pos;
|
13303 | var skip = skipWhiteSpace.exec(this.input);
|
13304 | var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
|
13305 |
|
13306 |
|
13307 |
|
13308 |
|
13309 | if (nextCh === 91) { return true }
|
13310 | if (context) { return false }
|
13311 |
|
13312 | if (nextCh === 123) { return true }
|
13313 | if (isIdentifierStart(nextCh, true)) {
|
13314 | var pos = next + 1;
|
13315 | while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
|
13316 | var ident = this.input.slice(next, pos);
|
13317 | if (!keywordRelationalOperator.test(ident)) { return true }
|
13318 | }
|
13319 | return false
|
13320 | };
|
13321 |
|
13322 |
|
13323 |
|
13324 |
|
13325 | pp$1.isAsyncFunction = function() {
|
13326 | if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
|
13327 | { return false }
|
13328 |
|
13329 | skipWhiteSpace.lastIndex = this.pos;
|
13330 | var skip = skipWhiteSpace.exec(this.input);
|
13331 | var next = this.pos + skip[0].length;
|
13332 | return !lineBreak.test(this.input.slice(this.pos, next)) &&
|
13333 | this.input.slice(next, next + 8) === "function" &&
|
13334 | (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
|
13335 | };
|
13336 |
|
13337 |
|
13338 |
|
13339 |
|
13340 |
|
13341 |
|
13342 |
|
13343 |
|
13344 | pp$1.parseStatement = function(context, topLevel, exports) {
|
13345 | var starttype = this.type, node = this.startNode(), kind;
|
13346 |
|
13347 | if (this.isLet(context)) {
|
13348 | starttype = types._var;
|
13349 | kind = "let";
|
13350 | }
|
13351 |
|
13352 |
|
13353 |
|
13354 |
|
13355 |
|
13356 | switch (starttype) {
|
13357 | case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
|
13358 | case types._debugger: return this.parseDebuggerStatement(node)
|
13359 | case types._do: return this.parseDoStatement(node)
|
13360 | case types._for: return this.parseForStatement(node)
|
13361 | case types._function:
|
13362 |
|
13363 |
|
13364 |
|
13365 | if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
|
13366 | return this.parseFunctionStatement(node, false, !context)
|
13367 | case types._class:
|
13368 | if (context) { this.unexpected(); }
|
13369 | return this.parseClass(node, true)
|
13370 | case types._if: return this.parseIfStatement(node)
|
13371 | case types._return: return this.parseReturnStatement(node)
|
13372 | case types._switch: return this.parseSwitchStatement(node)
|
13373 | case types._throw: return this.parseThrowStatement(node)
|
13374 | case types._try: return this.parseTryStatement(node)
|
13375 | case types._const: case types._var:
|
13376 | kind = kind || this.value;
|
13377 | if (context && kind !== "var") { this.unexpected(); }
|
13378 | return this.parseVarStatement(node, kind)
|
13379 | case types._while: return this.parseWhileStatement(node)
|
13380 | case types._with: return this.parseWithStatement(node)
|
13381 | case types.braceL: return this.parseBlock(true, node)
|
13382 | case types.semi: return this.parseEmptyStatement(node)
|
13383 | case types._export:
|
13384 | case types._import:
|
13385 | if (this.options.ecmaVersion > 10 && starttype === types._import) {
|
13386 | skipWhiteSpace.lastIndex = this.pos;
|
13387 | var skip = skipWhiteSpace.exec(this.input);
|
13388 | var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
|
13389 | if (nextCh === 40 || nextCh === 46)
|
13390 | { return this.parseExpressionStatement(node, this.parseExpression()) }
|
13391 | }
|
13392 |
|
13393 | if (!this.options.allowImportExportEverywhere) {
|
13394 | if (!topLevel)
|
13395 | { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
|
13396 | if (!this.inModule)
|
13397 | { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
|
13398 | }
|
13399 | return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
|
13400 |
|
13401 |
|
13402 |
|
13403 |
|
13404 |
|
13405 |
|
13406 | default:
|
13407 | if (this.isAsyncFunction()) {
|
13408 | if (context) { this.unexpected(); }
|
13409 | this.next();
|
13410 | return this.parseFunctionStatement(node, true, !context)
|
13411 | }
|
13412 |
|
13413 | var maybeName = this.value, expr = this.parseExpression();
|
13414 | if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
|
13415 | { return this.parseLabeledStatement(node, maybeName, expr, context) }
|
13416 | else { return this.parseExpressionStatement(node, expr) }
|
13417 | }
|
13418 | };
|
13419 |
|
13420 | pp$1.parseBreakContinueStatement = function(node, keyword) {
|
13421 | var isBreak = keyword === "break";
|
13422 | this.next();
|
13423 | if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
|
13424 | else if (this.type !== types.name) { this.unexpected(); }
|
13425 | else {
|
13426 | node.label = this.parseIdent();
|
13427 | this.semicolon();
|
13428 | }
|
13429 |
|
13430 |
|
13431 |
|
13432 | var i = 0;
|
13433 | for (; i < this.labels.length; ++i) {
|
13434 | var lab = this.labels[i];
|
13435 | if (node.label == null || lab.name === node.label.name) {
|
13436 | if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
|
13437 | if (node.label && isBreak) { break }
|
13438 | }
|
13439 | }
|
13440 | if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
|
13441 | return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
|
13442 | };
|
13443 |
|
13444 | pp$1.parseDebuggerStatement = function(node) {
|
13445 | this.next();
|
13446 | this.semicolon();
|
13447 | return this.finishNode(node, "DebuggerStatement")
|
13448 | };
|
13449 |
|
13450 | pp$1.parseDoStatement = function(node) {
|
13451 | this.next();
|
13452 | this.labels.push(loopLabel);
|
13453 | node.body = this.parseStatement("do");
|
13454 | this.labels.pop();
|
13455 | this.expect(types._while);
|
13456 | node.test = this.parseParenExpression();
|
13457 | if (this.options.ecmaVersion >= 6)
|
13458 | { this.eat(types.semi); }
|
13459 | else
|
13460 | { this.semicolon(); }
|
13461 | return this.finishNode(node, "DoWhileStatement")
|
13462 | };
|
13463 |
|
13464 |
|
13465 |
|
13466 |
|
13467 |
|
13468 |
|
13469 |
|
13470 |
|
13471 |
|
13472 | pp$1.parseForStatement = function(node) {
|
13473 | this.next();
|
13474 | var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
|
13475 | this.labels.push(loopLabel);
|
13476 | this.enterScope(0);
|
13477 | this.expect(types.parenL);
|
13478 | if (this.type === types.semi) {
|
13479 | if (awaitAt > -1) { this.unexpected(awaitAt); }
|
13480 | return this.parseFor(node, null)
|
13481 | }
|
13482 | var isLet = this.isLet();
|
13483 | if (this.type === types._var || this.type === types._const || isLet) {
|
13484 | var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
|
13485 | this.next();
|
13486 | this.parseVar(init$1, true, kind);
|
13487 | this.finishNode(init$1, "VariableDeclaration");
|
13488 | if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
|
13489 | if (this.options.ecmaVersion >= 9) {
|
13490 | if (this.type === types._in) {
|
13491 | if (awaitAt > -1) { this.unexpected(awaitAt); }
|
13492 | } else { node.await = awaitAt > -1; }
|
13493 | }
|
13494 | return this.parseForIn(node, init$1)
|
13495 | }
|
13496 | if (awaitAt > -1) { this.unexpected(awaitAt); }
|
13497 | return this.parseFor(node, init$1)
|
13498 | }
|
13499 | var refDestructuringErrors = new DestructuringErrors;
|
13500 | var init = this.parseExpression(true, refDestructuringErrors);
|
13501 | if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
|
13502 | if (this.options.ecmaVersion >= 9) {
|
13503 | if (this.type === types._in) {
|
13504 | if (awaitAt > -1) { this.unexpected(awaitAt); }
|
13505 | } else { node.await = awaitAt > -1; }
|
13506 | }
|
13507 | this.toAssignable(init, false, refDestructuringErrors);
|
13508 | this.checkLValPattern(init);
|
13509 | return this.parseForIn(node, init)
|
13510 | } else {
|
13511 | this.checkExpressionErrors(refDestructuringErrors, true);
|
13512 | }
|
13513 | if (awaitAt > -1) { this.unexpected(awaitAt); }
|
13514 | return this.parseFor(node, init)
|
13515 | };
|
13516 |
|
13517 | pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
|
13518 | this.next();
|
13519 | return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
|
13520 | };
|
13521 |
|
13522 | pp$1.parseIfStatement = function(node) {
|
13523 | this.next();
|
13524 | node.test = this.parseParenExpression();
|
13525 |
|
13526 | node.consequent = this.parseStatement("if");
|
13527 | node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
|
13528 | return this.finishNode(node, "IfStatement")
|
13529 | };
|
13530 |
|
13531 | pp$1.parseReturnStatement = function(node) {
|
13532 | if (!this.inFunction && !this.options.allowReturnOutsideFunction)
|
13533 | { this.raise(this.start, "'return' outside of function"); }
|
13534 | this.next();
|
13535 |
|
13536 |
|
13537 |
|
13538 |
|
13539 |
|
13540 | if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
|
13541 | else { node.argument = this.parseExpression(); this.semicolon(); }
|
13542 | return this.finishNode(node, "ReturnStatement")
|
13543 | };
|
13544 |
|
13545 | pp$1.parseSwitchStatement = function(node) {
|
13546 | this.next();
|
13547 | node.discriminant = this.parseParenExpression();
|
13548 | node.cases = [];
|
13549 | this.expect(types.braceL);
|
13550 | this.labels.push(switchLabel);
|
13551 | this.enterScope(0);
|
13552 |
|
13553 |
|
13554 |
|
13555 |
|
13556 |
|
13557 | var cur;
|
13558 | for (var sawDefault = false; this.type !== types.braceR;) {
|
13559 | if (this.type === types._case || this.type === types._default) {
|
13560 | var isCase = this.type === types._case;
|
13561 | if (cur) { this.finishNode(cur, "SwitchCase"); }
|
13562 | node.cases.push(cur = this.startNode());
|
13563 | cur.consequent = [];
|
13564 | this.next();
|
13565 | if (isCase) {
|
13566 | cur.test = this.parseExpression();
|
13567 | } else {
|
13568 | if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
|
13569 | sawDefault = true;
|
13570 | cur.test = null;
|
13571 | }
|
13572 | this.expect(types.colon);
|
13573 | } else {
|
13574 | if (!cur) { this.unexpected(); }
|
13575 | cur.consequent.push(this.parseStatement(null));
|
13576 | }
|
13577 | }
|
13578 | this.exitScope();
|
13579 | if (cur) { this.finishNode(cur, "SwitchCase"); }
|
13580 | this.next();
|
13581 | this.labels.pop();
|
13582 | return this.finishNode(node, "SwitchStatement")
|
13583 | };
|
13584 |
|
13585 | pp$1.parseThrowStatement = function(node) {
|
13586 | this.next();
|
13587 | if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
|
13588 | { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
|
13589 | node.argument = this.parseExpression();
|
13590 | this.semicolon();
|
13591 | return this.finishNode(node, "ThrowStatement")
|
13592 | };
|
13593 |
|
13594 |
|
13595 |
|
13596 | var empty = [];
|
13597 |
|
13598 | pp$1.parseTryStatement = function(node) {
|
13599 | this.next();
|
13600 | node.block = this.parseBlock();
|
13601 | node.handler = null;
|
13602 | if (this.type === types._catch) {
|
13603 | var clause = this.startNode();
|
13604 | this.next();
|
13605 | if (this.eat(types.parenL)) {
|
13606 | clause.param = this.parseBindingAtom();
|
13607 | var simple = clause.param.type === "Identifier";
|
13608 | this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
|
13609 | this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
|
13610 | this.expect(types.parenR);
|
13611 | } else {
|
13612 | if (this.options.ecmaVersion < 10) { this.unexpected(); }
|
13613 | clause.param = null;
|
13614 | this.enterScope(0);
|
13615 | }
|
13616 | clause.body = this.parseBlock(false);
|
13617 | this.exitScope();
|
13618 | node.handler = this.finishNode(clause, "CatchClause");
|
13619 | }
|
13620 | node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
|
13621 | if (!node.handler && !node.finalizer)
|
13622 | { this.raise(node.start, "Missing catch or finally clause"); }
|
13623 | return this.finishNode(node, "TryStatement")
|
13624 | };
|
13625 |
|
13626 | pp$1.parseVarStatement = function(node, kind) {
|
13627 | this.next();
|
13628 | this.parseVar(node, false, kind);
|
13629 | this.semicolon();
|
13630 | return this.finishNode(node, "VariableDeclaration")
|
13631 | };
|
13632 |
|
13633 | pp$1.parseWhileStatement = function(node) {
|
13634 | this.next();
|
13635 | node.test = this.parseParenExpression();
|
13636 | this.labels.push(loopLabel);
|
13637 | node.body = this.parseStatement("while");
|
13638 | this.labels.pop();
|
13639 | return this.finishNode(node, "WhileStatement")
|
13640 | };
|
13641 |
|
13642 | pp$1.parseWithStatement = function(node) {
|
13643 | if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
|
13644 | this.next();
|
13645 | node.object = this.parseParenExpression();
|
13646 | node.body = this.parseStatement("with");
|
13647 | return this.finishNode(node, "WithStatement")
|
13648 | };
|
13649 |
|
13650 | pp$1.parseEmptyStatement = function(node) {
|
13651 | this.next();
|
13652 | return this.finishNode(node, "EmptyStatement")
|
13653 | };
|
13654 |
|
13655 | pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
|
13656 | for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
|
13657 | {
|
13658 | var label = list[i$1];
|
13659 |
|
13660 | if (label.name === maybeName)
|
13661 | { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
|
13662 | } }
|
13663 | var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
|
13664 | for (var i = this.labels.length - 1; i >= 0; i--) {
|
13665 | var label$1 = this.labels[i];
|
13666 | if (label$1.statementStart === node.start) {
|
13667 |
|
13668 | label$1.statementStart = this.start;
|
13669 | label$1.kind = kind;
|
13670 | } else { break }
|
13671 | }
|
13672 | this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
|
13673 | node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
|
13674 | this.labels.pop();
|
13675 | node.label = expr;
|
13676 | return this.finishNode(node, "LabeledStatement")
|
13677 | };
|
13678 |
|
13679 | pp$1.parseExpressionStatement = function(node, expr) {
|
13680 | node.expression = expr;
|
13681 | this.semicolon();
|
13682 | return this.finishNode(node, "ExpressionStatement")
|
13683 | };
|
13684 |
|
13685 |
|
13686 |
|
13687 |
|
13688 |
|
13689 | pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
|
13690 | if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
|
13691 | if ( node === void 0 ) node = this.startNode();
|
13692 |
|
13693 | node.body = [];
|
13694 | this.expect(types.braceL);
|
13695 | if (createNewLexicalScope) { this.enterScope(0); }
|
13696 | while (this.type !== types.braceR) {
|
13697 | var stmt = this.parseStatement(null);
|
13698 | node.body.push(stmt);
|
13699 | }
|
13700 | if (exitStrict) { this.strict = false; }
|
13701 | this.next();
|
13702 | if (createNewLexicalScope) { this.exitScope(); }
|
13703 | return this.finishNode(node, "BlockStatement")
|
13704 | };
|
13705 |
|
13706 |
|
13707 |
|
13708 |
|
13709 |
|
13710 | pp$1.parseFor = function(node, init) {
|
13711 | node.init = init;
|
13712 | this.expect(types.semi);
|
13713 | node.test = this.type === types.semi ? null : this.parseExpression();
|
13714 | this.expect(types.semi);
|
13715 | node.update = this.type === types.parenR ? null : this.parseExpression();
|
13716 | this.expect(types.parenR);
|
13717 | node.body = this.parseStatement("for");
|
13718 | this.exitScope();
|
13719 | this.labels.pop();
|
13720 | return this.finishNode(node, "ForStatement")
|
13721 | };
|
13722 |
|
13723 |
|
13724 |
|
13725 |
|
13726 | pp$1.parseForIn = function(node, init) {
|
13727 | var isForIn = this.type === types._in;
|
13728 | this.next();
|
13729 |
|
13730 | if (
|
13731 | init.type === "VariableDeclaration" &&
|
13732 | init.declarations[0].init != null &&
|
13733 | (
|
13734 | !isForIn ||
|
13735 | this.options.ecmaVersion < 8 ||
|
13736 | this.strict ||
|
13737 | init.kind !== "var" ||
|
13738 | init.declarations[0].id.type !== "Identifier"
|
13739 | )
|
13740 | ) {
|
13741 | this.raise(
|
13742 | init.start,
|
13743 | ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
|
13744 | );
|
13745 | }
|
13746 | node.left = init;
|
13747 | node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
|
13748 | this.expect(types.parenR);
|
13749 | node.body = this.parseStatement("for");
|
13750 | this.exitScope();
|
13751 | this.labels.pop();
|
13752 | return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
|
13753 | };
|
13754 |
|
13755 |
|
13756 |
|
13757 | pp$1.parseVar = function(node, isFor, kind) {
|
13758 | node.declarations = [];
|
13759 | node.kind = kind;
|
13760 | for (;;) {
|
13761 | var decl = this.startNode();
|
13762 | this.parseVarId(decl, kind);
|
13763 | if (this.eat(types.eq)) {
|
13764 | decl.init = this.parseMaybeAssign(isFor);
|
13765 | } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
|
13766 | this.unexpected();
|
13767 | } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
|
13768 | this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
|
13769 | } else {
|
13770 | decl.init = null;
|
13771 | }
|
13772 | node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
|
13773 | if (!this.eat(types.comma)) { break }
|
13774 | }
|
13775 | return node
|
13776 | };
|
13777 |
|
13778 | pp$1.parseVarId = function(decl, kind) {
|
13779 | decl.id = this.parseBindingAtom();
|
13780 | this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
|
13781 | };
|
13782 |
|
13783 | var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
|
13784 |
|
13785 |
|
13786 |
|
13787 |
|
13788 |
|
13789 | pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
|
13790 | this.initFunction(node);
|
13791 | if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
|
13792 | if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
|
13793 | { this.unexpected(); }
|
13794 | node.generator = this.eat(types.star);
|
13795 | }
|
13796 | if (this.options.ecmaVersion >= 8)
|
13797 | { node.async = !!isAsync; }
|
13798 |
|
13799 | if (statement & FUNC_STATEMENT) {
|
13800 | node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
|
13801 | if (node.id && !(statement & FUNC_HANGING_STATEMENT))
|
13802 |
|
13803 |
|
13804 |
|
13805 |
|
13806 | { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
|
13807 | }
|
13808 |
|
13809 | var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
|
13810 | this.yieldPos = 0;
|
13811 | this.awaitPos = 0;
|
13812 | this.awaitIdentPos = 0;
|
13813 | this.enterScope(functionFlags(node.async, node.generator));
|
13814 |
|
13815 | if (!(statement & FUNC_STATEMENT))
|
13816 | { node.id = this.type === types.name ? this.parseIdent() : null; }
|
13817 |
|
13818 | this.parseFunctionParams(node);
|
13819 | this.parseFunctionBody(node, allowExpressionBody, false);
|
13820 |
|
13821 | this.yieldPos = oldYieldPos;
|
13822 | this.awaitPos = oldAwaitPos;
|
13823 | this.awaitIdentPos = oldAwaitIdentPos;
|
13824 | return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
|
13825 | };
|
13826 |
|
13827 | pp$1.parseFunctionParams = function(node) {
|
13828 | this.expect(types.parenL);
|
13829 | node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
|
13830 | this.checkYieldAwaitInDefaultParams();
|
13831 | };
|
13832 |
|
13833 |
|
13834 |
|
13835 |
|
13836 | pp$1.parseClass = function(node, isStatement) {
|
13837 | this.next();
|
13838 |
|
13839 |
|
13840 |
|
13841 | var oldStrict = this.strict;
|
13842 | this.strict = true;
|
13843 |
|
13844 | this.parseClassId(node, isStatement);
|
13845 | this.parseClassSuper(node);
|
13846 | var classBody = this.startNode();
|
13847 | var hadConstructor = false;
|
13848 | classBody.body = [];
|
13849 | this.expect(types.braceL);
|
13850 | while (this.type !== types.braceR) {
|
13851 | var element = this.parseClassElement(node.superClass !== null);
|
13852 | if (element) {
|
13853 | classBody.body.push(element);
|
13854 | if (element.type === "MethodDefinition" && element.kind === "constructor") {
|
13855 | if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
|
13856 | hadConstructor = true;
|
13857 | }
|
13858 | }
|
13859 | }
|
13860 | this.strict = oldStrict;
|
13861 | this.next();
|
13862 | node.body = this.finishNode(classBody, "ClassBody");
|
13863 | return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
|
13864 | };
|
13865 |
|
13866 | pp$1.parseClassElement = function(constructorAllowsSuper) {
|
13867 | var this$1 = this;
|
13868 |
|
13869 | if (this.eat(types.semi)) { return null }
|
13870 |
|
13871 | var method = this.startNode();
|
13872 | var tryContextual = function (k, noLineBreak) {
|
13873 | if ( noLineBreak === void 0 ) noLineBreak = false;
|
13874 |
|
13875 | var start = this$1.start, startLoc = this$1.startLoc;
|
13876 | if (!this$1.eatContextual(k)) { return false }
|
13877 | if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
|
13878 | if (method.key) { this$1.unexpected(); }
|
13879 | method.computed = false;
|
13880 | method.key = this$1.startNodeAt(start, startLoc);
|
13881 | method.key.name = k;
|
13882 | this$1.finishNode(method.key, "Identifier");
|
13883 | return false
|
13884 | };
|
13885 |
|
13886 | method.kind = "method";
|
13887 | method.static = tryContextual("static");
|
13888 | var isGenerator = this.eat(types.star);
|
13889 | var isAsync = false;
|
13890 | if (!isGenerator) {
|
13891 | if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
|
13892 | isAsync = true;
|
13893 | isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
|
13894 | } else if (tryContextual("get")) {
|
13895 | method.kind = "get";
|
13896 | } else if (tryContextual("set")) {
|
13897 | method.kind = "set";
|
13898 | }
|
13899 | }
|
13900 | if (!method.key) { this.parsePropertyName(method); }
|
13901 | var key = method.key;
|
13902 | var allowsDirectSuper = false;
|
13903 | if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
|
13904 | key.type === "Literal" && key.value === "constructor")) {
|
13905 | if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
|
13906 | if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
|
13907 | if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
|
13908 | method.kind = "constructor";
|
13909 | allowsDirectSuper = constructorAllowsSuper;
|
13910 | } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
|
13911 | this.raise(key.start, "Classes may not have a static property named prototype");
|
13912 | }
|
13913 | this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
|
13914 | if (method.kind === "get" && method.value.params.length !== 0)
|
13915 | { this.raiseRecoverable(method.value.start, "getter should have no params"); }
|
13916 | if (method.kind === "set" && method.value.params.length !== 1)
|
13917 | { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
|
13918 | if (method.kind === "set" && method.value.params[0].type === "RestElement")
|
13919 | { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
|
13920 | return method
|
13921 | };
|
13922 |
|
13923 | pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
|
13924 | method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
|
13925 | return this.finishNode(method, "MethodDefinition")
|
13926 | };
|
13927 |
|
13928 | pp$1.parseClassId = function(node, isStatement) {
|
13929 | if (this.type === types.name) {
|
13930 | node.id = this.parseIdent();
|
13931 | if (isStatement)
|
13932 | { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
|
13933 | } else {
|
13934 | if (isStatement === true)
|
13935 | { this.unexpected(); }
|
13936 | node.id = null;
|
13937 | }
|
13938 | };
|
13939 |
|
13940 | pp$1.parseClassSuper = function(node) {
|
13941 | node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
|
13942 | };
|
13943 |
|
13944 |
|
13945 |
|
13946 | pp$1.parseExport = function(node, exports) {
|
13947 | this.next();
|
13948 |
|
13949 | if (this.eat(types.star)) {
|
13950 | if (this.options.ecmaVersion >= 11) {
|
13951 | if (this.eatContextual("as")) {
|
13952 | node.exported = this.parseIdent(true);
|
13953 | this.checkExport(exports, node.exported.name, this.lastTokStart);
|
13954 | } else {
|
13955 | node.exported = null;
|
13956 | }
|
13957 | }
|
13958 | this.expectContextual("from");
|
13959 | if (this.type !== types.string) { this.unexpected(); }
|
13960 | node.source = this.parseExprAtom();
|
13961 | this.semicolon();
|
13962 | return this.finishNode(node, "ExportAllDeclaration")
|
13963 | }
|
13964 | if (this.eat(types._default)) {
|
13965 | this.checkExport(exports, "default", this.lastTokStart);
|
13966 | var isAsync;
|
13967 | if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
|
13968 | var fNode = this.startNode();
|
13969 | this.next();
|
13970 | if (isAsync) { this.next(); }
|
13971 | node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
|
13972 | } else if (this.type === types._class) {
|
13973 | var cNode = this.startNode();
|
13974 | node.declaration = this.parseClass(cNode, "nullableID");
|
13975 | } else {
|
13976 | node.declaration = this.parseMaybeAssign();
|
13977 | this.semicolon();
|
13978 | }
|
13979 | return this.finishNode(node, "ExportDefaultDeclaration")
|
13980 | }
|
13981 |
|
13982 | if (this.shouldParseExportStatement()) {
|
13983 | node.declaration = this.parseStatement(null);
|
13984 | if (node.declaration.type === "VariableDeclaration")
|
13985 | { this.checkVariableExport(exports, node.declaration.declarations); }
|
13986 | else
|
13987 | { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
|
13988 | node.specifiers = [];
|
13989 | node.source = null;
|
13990 | } else {
|
13991 | node.declaration = null;
|
13992 | node.specifiers = this.parseExportSpecifiers(exports);
|
13993 | if (this.eatContextual("from")) {
|
13994 | if (this.type !== types.string) { this.unexpected(); }
|
13995 | node.source = this.parseExprAtom();
|
13996 | } else {
|
13997 | for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
|
13998 |
|
13999 | var spec = list[i];
|
14000 |
|
14001 | this.checkUnreserved(spec.local);
|
14002 |
|
14003 | this.checkLocalExport(spec.local);
|
14004 | }
|
14005 |
|
14006 | node.source = null;
|
14007 | }
|
14008 | this.semicolon();
|
14009 | }
|
14010 | return this.finishNode(node, "ExportNamedDeclaration")
|
14011 | };
|
14012 |
|
14013 | pp$1.checkExport = function(exports, name, pos) {
|
14014 | if (!exports) { return }
|
14015 | if (has(exports, name))
|
14016 | { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
|
14017 | exports[name] = true;
|
14018 | };
|
14019 |
|
14020 | pp$1.checkPatternExport = function(exports, pat) {
|
14021 | var type = pat.type;
|
14022 | if (type === "Identifier")
|
14023 | { this.checkExport(exports, pat.name, pat.start); }
|
14024 | else if (type === "ObjectPattern")
|
14025 | { for (var i = 0, list = pat.properties; i < list.length; i += 1)
|
14026 | {
|
14027 | var prop = list[i];
|
14028 |
|
14029 | this.checkPatternExport(exports, prop);
|
14030 | } }
|
14031 | else if (type === "ArrayPattern")
|
14032 | { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
|
14033 | var elt = list$1[i$1];
|
14034 |
|
14035 | if (elt) { this.checkPatternExport(exports, elt); }
|
14036 | } }
|
14037 | else if (type === "Property")
|
14038 | { this.checkPatternExport(exports, pat.value); }
|
14039 | else if (type === "AssignmentPattern")
|
14040 | { this.checkPatternExport(exports, pat.left); }
|
14041 | else if (type === "RestElement")
|
14042 | { this.checkPatternExport(exports, pat.argument); }
|
14043 | else if (type === "ParenthesizedExpression")
|
14044 | { this.checkPatternExport(exports, pat.expression); }
|
14045 | };
|
14046 |
|
14047 | pp$1.checkVariableExport = function(exports, decls) {
|
14048 | if (!exports) { return }
|
14049 | for (var i = 0, list = decls; i < list.length; i += 1)
|
14050 | {
|
14051 | var decl = list[i];
|
14052 |
|
14053 | this.checkPatternExport(exports, decl.id);
|
14054 | }
|
14055 | };
|
14056 |
|
14057 | pp$1.shouldParseExportStatement = function() {
|
14058 | return this.type.keyword === "var" ||
|
14059 | this.type.keyword === "const" ||
|
14060 | this.type.keyword === "class" ||
|
14061 | this.type.keyword === "function" ||
|
14062 | this.isLet() ||
|
14063 | this.isAsyncFunction()
|
14064 | };
|
14065 |
|
14066 |
|
14067 |
|
14068 | pp$1.parseExportSpecifiers = function(exports) {
|
14069 | var nodes = [], first = true;
|
14070 |
|
14071 | this.expect(types.braceL);
|
14072 | while (!this.eat(types.braceR)) {
|
14073 | if (!first) {
|
14074 | this.expect(types.comma);
|
14075 | if (this.afterTrailingComma(types.braceR)) { break }
|
14076 | } else { first = false; }
|
14077 |
|
14078 | var node = this.startNode();
|
14079 | node.local = this.parseIdent(true);
|
14080 | node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
|
14081 | this.checkExport(exports, node.exported.name, node.exported.start);
|
14082 | nodes.push(this.finishNode(node, "ExportSpecifier"));
|
14083 | }
|
14084 | return nodes
|
14085 | };
|
14086 |
|
14087 |
|
14088 |
|
14089 | pp$1.parseImport = function(node) {
|
14090 | this.next();
|
14091 |
|
14092 | if (this.type === types.string) {
|
14093 | node.specifiers = empty;
|
14094 | node.source = this.parseExprAtom();
|
14095 | } else {
|
14096 | node.specifiers = this.parseImportSpecifiers();
|
14097 | this.expectContextual("from");
|
14098 | node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
|
14099 | }
|
14100 | this.semicolon();
|
14101 | return this.finishNode(node, "ImportDeclaration")
|
14102 | };
|
14103 |
|
14104 |
|
14105 |
|
14106 | pp$1.parseImportSpecifiers = function() {
|
14107 | var nodes = [], first = true;
|
14108 | if (this.type === types.name) {
|
14109 |
|
14110 | var node = this.startNode();
|
14111 | node.local = this.parseIdent();
|
14112 | this.checkLValSimple(node.local, BIND_LEXICAL);
|
14113 | nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
|
14114 | if (!this.eat(types.comma)) { return nodes }
|
14115 | }
|
14116 | if (this.type === types.star) {
|
14117 | var node$1 = this.startNode();
|
14118 | this.next();
|
14119 | this.expectContextual("as");
|
14120 | node$1.local = this.parseIdent();
|
14121 | this.checkLValSimple(node$1.local, BIND_LEXICAL);
|
14122 | nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
|
14123 | return nodes
|
14124 | }
|
14125 | this.expect(types.braceL);
|
14126 | while (!this.eat(types.braceR)) {
|
14127 | if (!first) {
|
14128 | this.expect(types.comma);
|
14129 | if (this.afterTrailingComma(types.braceR)) { break }
|
14130 | } else { first = false; }
|
14131 |
|
14132 | var node$2 = this.startNode();
|
14133 | node$2.imported = this.parseIdent(true);
|
14134 | if (this.eatContextual("as")) {
|
14135 | node$2.local = this.parseIdent();
|
14136 | } else {
|
14137 | this.checkUnreserved(node$2.imported);
|
14138 | node$2.local = node$2.imported;
|
14139 | }
|
14140 | this.checkLValSimple(node$2.local, BIND_LEXICAL);
|
14141 | nodes.push(this.finishNode(node$2, "ImportSpecifier"));
|
14142 | }
|
14143 | return nodes
|
14144 | };
|
14145 |
|
14146 |
|
14147 | pp$1.adaptDirectivePrologue = function(statements) {
|
14148 | for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
|
14149 | statements[i].directive = statements[i].expression.raw.slice(1, -1);
|
14150 | }
|
14151 | };
|
14152 | pp$1.isDirectiveCandidate = function(statement) {
|
14153 | return (
|
14154 | statement.type === "ExpressionStatement" &&
|
14155 | statement.expression.type === "Literal" &&
|
14156 | typeof statement.expression.value === "string" &&
|
14157 |
|
14158 | (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
|
14159 | )
|
14160 | };
|
14161 |
|
14162 | var pp$2 = Parser.prototype;
|
14163 |
|
14164 |
|
14165 |
|
14166 |
|
14167 | pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
|
14168 | if (this.options.ecmaVersion >= 6 && node) {
|
14169 | switch (node.type) {
|
14170 | case "Identifier":
|
14171 | if (this.inAsync && node.name === "await")
|
14172 | { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
|
14173 | break
|
14174 |
|
14175 | case "ObjectPattern":
|
14176 | case "ArrayPattern":
|
14177 | case "AssignmentPattern":
|
14178 | case "RestElement":
|
14179 | break
|
14180 |
|
14181 | case "ObjectExpression":
|
14182 | node.type = "ObjectPattern";
|
14183 | if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
|
14184 | for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
14185 | var prop = list[i];
|
14186 |
|
14187 | this.toAssignable(prop, isBinding);
|
14188 |
|
14189 |
|
14190 |
|
14191 |
|
14192 |
|
14193 | if (
|
14194 | prop.type === "RestElement" &&
|
14195 | (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
|
14196 | ) {
|
14197 | this.raise(prop.argument.start, "Unexpected token");
|
14198 | }
|
14199 | }
|
14200 | break
|
14201 |
|
14202 | case "Property":
|
14203 |
|
14204 | if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
|
14205 | this.toAssignable(node.value, isBinding);
|
14206 | break
|
14207 |
|
14208 | case "ArrayExpression":
|
14209 | node.type = "ArrayPattern";
|
14210 | if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
|
14211 | this.toAssignableList(node.elements, isBinding);
|
14212 | break
|
14213 |
|
14214 | case "SpreadElement":
|
14215 | node.type = "RestElement";
|
14216 | this.toAssignable(node.argument, isBinding);
|
14217 | if (node.argument.type === "AssignmentPattern")
|
14218 | { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
|
14219 | break
|
14220 |
|
14221 | case "AssignmentExpression":
|
14222 | if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
|
14223 | node.type = "AssignmentPattern";
|
14224 | delete node.operator;
|
14225 | this.toAssignable(node.left, isBinding);
|
14226 | break
|
14227 |
|
14228 | case "ParenthesizedExpression":
|
14229 | this.toAssignable(node.expression, isBinding, refDestructuringErrors);
|
14230 | break
|
14231 |
|
14232 | case "ChainExpression":
|
14233 | this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
|
14234 | break
|
14235 |
|
14236 | case "MemberExpression":
|
14237 | if (!isBinding) { break }
|
14238 |
|
14239 | default:
|
14240 | this.raise(node.start, "Assigning to rvalue");
|
14241 | }
|
14242 | } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
|
14243 | return node
|
14244 | };
|
14245 |
|
14246 |
|
14247 |
|
14248 | pp$2.toAssignableList = function(exprList, isBinding) {
|
14249 | var end = exprList.length;
|
14250 | for (var i = 0; i < end; i++) {
|
14251 | var elt = exprList[i];
|
14252 | if (elt) { this.toAssignable(elt, isBinding); }
|
14253 | }
|
14254 | if (end) {
|
14255 | var last = exprList[end - 1];
|
14256 | if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
|
14257 | { this.unexpected(last.argument.start); }
|
14258 | }
|
14259 | return exprList
|
14260 | };
|
14261 |
|
14262 |
|
14263 |
|
14264 | pp$2.parseSpread = function(refDestructuringErrors) {
|
14265 | var node = this.startNode();
|
14266 | this.next();
|
14267 | node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
|
14268 | return this.finishNode(node, "SpreadElement")
|
14269 | };
|
14270 |
|
14271 | pp$2.parseRestBinding = function() {
|
14272 | var node = this.startNode();
|
14273 | this.next();
|
14274 |
|
14275 |
|
14276 | if (this.options.ecmaVersion === 6 && this.type !== types.name)
|
14277 | { this.unexpected(); }
|
14278 |
|
14279 | node.argument = this.parseBindingAtom();
|
14280 |
|
14281 | return this.finishNode(node, "RestElement")
|
14282 | };
|
14283 |
|
14284 |
|
14285 |
|
14286 | pp$2.parseBindingAtom = function() {
|
14287 | if (this.options.ecmaVersion >= 6) {
|
14288 | switch (this.type) {
|
14289 | case types.bracketL:
|
14290 | var node = this.startNode();
|
14291 | this.next();
|
14292 | node.elements = this.parseBindingList(types.bracketR, true, true);
|
14293 | return this.finishNode(node, "ArrayPattern")
|
14294 |
|
14295 | case types.braceL:
|
14296 | return this.parseObj(true)
|
14297 | }
|
14298 | }
|
14299 | return this.parseIdent()
|
14300 | };
|
14301 |
|
14302 | pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
|
14303 | var elts = [], first = true;
|
14304 | while (!this.eat(close)) {
|
14305 | if (first) { first = false; }
|
14306 | else { this.expect(types.comma); }
|
14307 | if (allowEmpty && this.type === types.comma) {
|
14308 | elts.push(null);
|
14309 | } else if (allowTrailingComma && this.afterTrailingComma(close)) {
|
14310 | break
|
14311 | } else if (this.type === types.ellipsis) {
|
14312 | var rest = this.parseRestBinding();
|
14313 | this.parseBindingListItem(rest);
|
14314 | elts.push(rest);
|
14315 | if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
|
14316 | this.expect(close);
|
14317 | break
|
14318 | } else {
|
14319 | var elem = this.parseMaybeDefault(this.start, this.startLoc);
|
14320 | this.parseBindingListItem(elem);
|
14321 | elts.push(elem);
|
14322 | }
|
14323 | }
|
14324 | return elts
|
14325 | };
|
14326 |
|
14327 | pp$2.parseBindingListItem = function(param) {
|
14328 | return param
|
14329 | };
|
14330 |
|
14331 |
|
14332 |
|
14333 | pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
|
14334 | left = left || this.parseBindingAtom();
|
14335 | if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
|
14336 | var node = this.startNodeAt(startPos, startLoc);
|
14337 | node.left = left;
|
14338 | node.right = this.parseMaybeAssign();
|
14339 | return this.finishNode(node, "AssignmentPattern")
|
14340 | };
|
14341 |
|
14342 |
|
14343 |
|
14344 |
|
14345 |
|
14346 |
|
14347 |
|
14348 |
|
14349 |
|
14350 |
|
14351 |
|
14352 |
|
14353 |
|
14354 |
|
14355 |
|
14356 |
|
14357 |
|
14358 |
|
14359 |
|
14360 |
|
14361 |
|
14362 |
|
14363 |
|
14364 |
|
14365 |
|
14366 |
|
14367 |
|
14368 |
|
14369 |
|
14370 |
|
14371 |
|
14372 |
|
14373 |
|
14374 |
|
14375 |
|
14376 |
|
14377 |
|
14378 |
|
14379 |
|
14380 |
|
14381 |
|
14382 |
|
14383 |
|
14384 |
|
14385 |
|
14386 |
|
14387 |
|
14388 |
|
14389 |
|
14390 |
|
14391 |
|
14392 |
|
14393 |
|
14394 |
|
14395 |
|
14396 |
|
14397 |
|
14398 |
|
14399 |
|
14400 |
|
14401 |
|
14402 |
|
14403 |
|
14404 |
|
14405 |
|
14406 | pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
|
14407 | if ( bindingType === void 0 ) bindingType = BIND_NONE;
|
14408 |
|
14409 | var isBind = bindingType !== BIND_NONE;
|
14410 |
|
14411 | switch (expr.type) {
|
14412 | case "Identifier":
|
14413 | if (this.strict && this.reservedWordsStrictBind.test(expr.name))
|
14414 | { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
|
14415 | if (isBind) {
|
14416 | if (bindingType === BIND_LEXICAL && expr.name === "let")
|
14417 | { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
|
14418 | if (checkClashes) {
|
14419 | if (has(checkClashes, expr.name))
|
14420 | { this.raiseRecoverable(expr.start, "Argument name clash"); }
|
14421 | checkClashes[expr.name] = true;
|
14422 | }
|
14423 | if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
|
14424 | }
|
14425 | break
|
14426 |
|
14427 | case "ChainExpression":
|
14428 | this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
|
14429 | break
|
14430 |
|
14431 | case "MemberExpression":
|
14432 | if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
|
14433 | break
|
14434 |
|
14435 | case "ParenthesizedExpression":
|
14436 | if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
|
14437 | return this.checkLValSimple(expr.expression, bindingType, checkClashes)
|
14438 |
|
14439 | default:
|
14440 | this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
|
14441 | }
|
14442 | };
|
14443 |
|
14444 | pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
|
14445 | if ( bindingType === void 0 ) bindingType = BIND_NONE;
|
14446 |
|
14447 | switch (expr.type) {
|
14448 | case "ObjectPattern":
|
14449 | for (var i = 0, list = expr.properties; i < list.length; i += 1) {
|
14450 | var prop = list[i];
|
14451 |
|
14452 | this.checkLValInnerPattern(prop, bindingType, checkClashes);
|
14453 | }
|
14454 | break
|
14455 |
|
14456 | case "ArrayPattern":
|
14457 | for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
|
14458 | var elem = list$1[i$1];
|
14459 |
|
14460 | if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
|
14461 | }
|
14462 | break
|
14463 |
|
14464 | default:
|
14465 | this.checkLValSimple(expr, bindingType, checkClashes);
|
14466 | }
|
14467 | };
|
14468 |
|
14469 | pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
|
14470 | if ( bindingType === void 0 ) bindingType = BIND_NONE;
|
14471 |
|
14472 | switch (expr.type) {
|
14473 | case "Property":
|
14474 |
|
14475 | this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
|
14476 | break
|
14477 |
|
14478 | case "AssignmentPattern":
|
14479 | this.checkLValPattern(expr.left, bindingType, checkClashes);
|
14480 | break
|
14481 |
|
14482 | case "RestElement":
|
14483 | this.checkLValPattern(expr.argument, bindingType, checkClashes);
|
14484 | break
|
14485 |
|
14486 | default:
|
14487 | this.checkLValPattern(expr, bindingType, checkClashes);
|
14488 | }
|
14489 | };
|
14490 |
|
14491 |
|
14492 |
|
14493 | var pp$3 = Parser.prototype;
|
14494 |
|
14495 |
|
14496 |
|
14497 |
|
14498 |
|
14499 |
|
14500 | pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
|
14501 | if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
|
14502 | { return }
|
14503 | if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
|
14504 | { return }
|
14505 | var key = prop.key;
|
14506 | var name;
|
14507 | switch (key.type) {
|
14508 | case "Identifier": name = key.name; break
|
14509 | case "Literal": name = String(key.value); break
|
14510 | default: return
|
14511 | }
|
14512 | var kind = prop.kind;
|
14513 | if (this.options.ecmaVersion >= 6) {
|
14514 | if (name === "__proto__" && kind === "init") {
|
14515 | if (propHash.proto) {
|
14516 | if (refDestructuringErrors) {
|
14517 | if (refDestructuringErrors.doubleProto < 0)
|
14518 | { refDestructuringErrors.doubleProto = key.start; }
|
14519 |
|
14520 | } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
|
14521 | }
|
14522 | propHash.proto = true;
|
14523 | }
|
14524 | return
|
14525 | }
|
14526 | name = "$" + name;
|
14527 | var other = propHash[name];
|
14528 | if (other) {
|
14529 | var redefinition;
|
14530 | if (kind === "init") {
|
14531 | redefinition = this.strict && other.init || other.get || other.set;
|
14532 | } else {
|
14533 | redefinition = other.init || other[kind];
|
14534 | }
|
14535 | if (redefinition)
|
14536 | { this.raiseRecoverable(key.start, "Redefinition of property"); }
|
14537 | } else {
|
14538 | other = propHash[name] = {
|
14539 | init: false,
|
14540 | get: false,
|
14541 | set: false
|
14542 | };
|
14543 | }
|
14544 | other[kind] = true;
|
14545 | };
|
14546 |
|
14547 | // ### Expression parsing
|
14548 |
|
14549 | // These nest, from the most general expression type at the top to
|
14550 | // 'atomic', nondivisible expression types at the bottom. Most of
|
14551 | // the functions will simply let the function(s) below them parse,
|
14552 | // and, *if* the syntactic construct they handle is present, wrap
|
14553 | // the AST node that the inner parser gave them in another node.
|
14554 |
|
14555 | // Parse a full expression. The optional arguments are used to
|
14556 | // forbid the `in` operator (in for loops initalization expressions)
|
14557 | // and provide reference for storing '=' operator inside shorthand
|
14558 | // property assignment in contexts where both object expression
|
14559 | // and object pattern might appear (so it's possible to raise
|
14560 | // delayed syntax error at correct position).
|
14561 |
|
14562 | pp$3.parseExpression = function(noIn, refDestructuringErrors) {
|
14563 | var startPos = this.start, startLoc = this.startLoc;
|
14564 | var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
|
14565 | if (this.type === types.comma) {
|
14566 | var node = this.startNodeAt(startPos, startLoc);
|
14567 | node.expressions = [expr];
|
14568 | while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
|
14569 | return this.finishNode(node, "SequenceExpression")
|
14570 | }
|
14571 | return expr
|
14572 | };
|
14573 |
|
14574 |
|
14575 |
|
14576 |
|
14577 | pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
|
14578 | if (this.isContextual("yield")) {
|
14579 | if (this.inGenerator) { return this.parseYield(noIn) }
|
14580 |
|
14581 |
|
14582 | else { this.exprAllowed = false; }
|
14583 | }
|
14584 |
|
14585 | var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
|
14586 | if (refDestructuringErrors) {
|
14587 | oldParenAssign = refDestructuringErrors.parenthesizedAssign;
|
14588 | oldTrailingComma = refDestructuringErrors.trailingComma;
|
14589 | refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
|
14590 | } else {
|
14591 | refDestructuringErrors = new DestructuringErrors;
|
14592 | ownDestructuringErrors = true;
|
14593 | }
|
14594 |
|
14595 | var startPos = this.start, startLoc = this.startLoc;
|
14596 | if (this.type === types.parenL || this.type === types.name)
|
14597 | { this.potentialArrowAt = this.start; }
|
14598 | var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
|
14599 | if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
|
14600 | if (this.type.isAssign) {
|
14601 | var node = this.startNodeAt(startPos, startLoc);
|
14602 | node.operator = this.value;
|
14603 | if (this.type === types.eq)
|
14604 | { left = this.toAssignable(left, false, refDestructuringErrors); }
|
14605 | if (!ownDestructuringErrors) {
|
14606 | refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
|
14607 | }
|
14608 | if (refDestructuringErrors.shorthandAssign >= left.start)
|
14609 | { refDestructuringErrors.shorthandAssign = -1; }
|
14610 | if (this.type === types.eq)
|
14611 | { this.checkLValPattern(left); }
|
14612 | else
|
14613 | { this.checkLValSimple(left); }
|
14614 | node.left = left;
|
14615 | this.next();
|
14616 | node.right = this.parseMaybeAssign(noIn);
|
14617 | return this.finishNode(node, "AssignmentExpression")
|
14618 | } else {
|
14619 | if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
|
14620 | }
|
14621 | if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
|
14622 | if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
|
14623 | return left
|
14624 | };
|
14625 |
|
14626 |
|
14627 |
|
14628 | pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
|
14629 | var startPos = this.start, startLoc = this.startLoc;
|
14630 | var expr = this.parseExprOps(noIn, refDestructuringErrors);
|
14631 | if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
|
14632 | if (this.eat(types.question)) {
|
14633 | var node = this.startNodeAt(startPos, startLoc);
|
14634 | node.test = expr;
|
14635 | node.consequent = this.parseMaybeAssign();
|
14636 | this.expect(types.colon);
|
14637 | node.alternate = this.parseMaybeAssign(noIn);
|
14638 | return this.finishNode(node, "ConditionalExpression")
|
14639 | }
|
14640 | return expr
|
14641 | };
|
14642 |
|
14643 |
|
14644 |
|
14645 | pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
|
14646 | var startPos = this.start, startLoc = this.startLoc;
|
14647 | var expr = this.parseMaybeUnary(refDestructuringErrors, false);
|
14648 | if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
|
14649 | return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
|
14650 | };
|
14651 |
|
14652 |
|
14653 |
|
14654 |
|
14655 |
|
14656 |
|
14657 |
|
14658 | pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
|
14659 | var prec = this.type.binop;
|
14660 | if (prec != null && (!noIn || this.type !== types._in)) {
|
14661 | if (prec > minPrec) {
|
14662 | var logical = this.type === types.logicalOR || this.type === types.logicalAND;
|
14663 | var coalesce = this.type === types.coalesce;
|
14664 | if (coalesce) {
|
14665 |
|
14666 |
|
14667 | prec = types.logicalAND.binop;
|
14668 | }
|
14669 | var op = this.value;
|
14670 | this.next();
|
14671 | var startPos = this.start, startLoc = this.startLoc;
|
14672 | var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
|
14673 | var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
|
14674 | if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
|
14675 | this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
|
14676 | }
|
14677 | return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
|
14678 | }
|
14679 | }
|
14680 | return left
|
14681 | };
|
14682 |
|
14683 | pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
|
14684 | var node = this.startNodeAt(startPos, startLoc);
|
14685 | node.left = left;
|
14686 | node.operator = op;
|
14687 | node.right = right;
|
14688 | return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
|
14689 | };
|
14690 |
|
14691 |
|
14692 |
|
14693 | pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
|
14694 | var startPos = this.start, startLoc = this.startLoc, expr;
|
14695 | if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
|
14696 | expr = this.parseAwait();
|
14697 | sawUnary = true;
|
14698 | } else if (this.type.prefix) {
|
14699 | var node = this.startNode(), update = this.type === types.incDec;
|
14700 | node.operator = this.value;
|
14701 | node.prefix = true;
|
14702 | this.next();
|
14703 | node.argument = this.parseMaybeUnary(null, true);
|
14704 | this.checkExpressionErrors(refDestructuringErrors, true);
|
14705 | if (update) { this.checkLValSimple(node.argument); }
|
14706 | else if (this.strict && node.operator === "delete" &&
|
14707 | node.argument.type === "Identifier")
|
14708 | { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
|
14709 | else { sawUnary = true; }
|
14710 | expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
|
14711 | } else {
|
14712 | expr = this.parseExprSubscripts(refDestructuringErrors);
|
14713 | if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
|
14714 | while (this.type.postfix && !this.canInsertSemicolon()) {
|
14715 | var node$1 = this.startNodeAt(startPos, startLoc);
|
14716 | node$1.operator = this.value;
|
14717 | node$1.prefix = false;
|
14718 | node$1.argument = expr;
|
14719 | this.checkLValSimple(expr);
|
14720 | this.next();
|
14721 | expr = this.finishNode(node$1, "UpdateExpression");
|
14722 | }
|
14723 | }
|
14724 |
|
14725 | if (!sawUnary && this.eat(types.starstar))
|
14726 | { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
|
14727 | else
|
14728 | { return expr }
|
14729 | };
|
14730 |
|
14731 |
|
14732 |
|
14733 | pp$3.parseExprSubscripts = function(refDestructuringErrors) {
|
14734 | var startPos = this.start, startLoc = this.startLoc;
|
14735 | var expr = this.parseExprAtom(refDestructuringErrors);
|
14736 | if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
|
14737 | { return expr }
|
14738 | var result = this.parseSubscripts(expr, startPos, startLoc);
|
14739 | if (refDestructuringErrors && result.type === "MemberExpression") {
|
14740 | if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
|
14741 | if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
|
14742 | }
|
14743 | return result
|
14744 | };
|
14745 |
|
14746 | pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
|
14747 | var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
|
14748 | this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
|
14749 | this.potentialArrowAt === base.start;
|
14750 | var optionalChained = false;
|
14751 |
|
14752 | while (true) {
|
14753 | var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
|
14754 |
|
14755 | if (element.optional) { optionalChained = true; }
|
14756 | if (element === base || element.type === "ArrowFunctionExpression") {
|
14757 | if (optionalChained) {
|
14758 | var chainNode = this.startNodeAt(startPos, startLoc);
|
14759 | chainNode.expression = element;
|
14760 | element = this.finishNode(chainNode, "ChainExpression");
|
14761 | }
|
14762 | return element
|
14763 | }
|
14764 |
|
14765 | base = element;
|
14766 | }
|
14767 | };
|
14768 |
|
14769 | pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
|
14770 | var optionalSupported = this.options.ecmaVersion >= 11;
|
14771 | var optional = optionalSupported && this.eat(types.questionDot);
|
14772 | if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
|
14773 |
|
14774 | var computed = this.eat(types.bracketL);
|
14775 | if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
|
14776 | var node = this.startNodeAt(startPos, startLoc);
|
14777 | node.object = base;
|
14778 | node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
|
14779 | node.computed = !!computed;
|
14780 | if (computed) { this.expect(types.bracketR); }
|
14781 | if (optionalSupported) {
|
14782 | node.optional = optional;
|
14783 | }
|
14784 | base = this.finishNode(node, "MemberExpression");
|
14785 | } else if (!noCalls && this.eat(types.parenL)) {
|
14786 | var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
|
14787 | this.yieldPos = 0;
|
14788 | this.awaitPos = 0;
|
14789 | this.awaitIdentPos = 0;
|
14790 | var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
|
14791 | if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
|
14792 | this.checkPatternErrors(refDestructuringErrors, false);
|
14793 | this.checkYieldAwaitInDefaultParams();
|
14794 | if (this.awaitIdentPos > 0)
|
14795 | { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
|
14796 | this.yieldPos = oldYieldPos;
|
14797 | this.awaitPos = oldAwaitPos;
|
14798 | this.awaitIdentPos = oldAwaitIdentPos;
|
14799 | return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
|
14800 | }
|
14801 | this.checkExpressionErrors(refDestructuringErrors, true);
|
14802 | this.yieldPos = oldYieldPos || this.yieldPos;
|
14803 | this.awaitPos = oldAwaitPos || this.awaitPos;
|
14804 | this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
|
14805 | var node$1 = this.startNodeAt(startPos, startLoc);
|
14806 | node$1.callee = base;
|
14807 | node$1.arguments = exprList;
|
14808 | if (optionalSupported) {
|
14809 | node$1.optional = optional;
|
14810 | }
|
14811 | base = this.finishNode(node$1, "CallExpression");
|
14812 | } else if (this.type === types.backQuote) {
|
14813 | if (optional || optionalChained) {
|
14814 | this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
|
14815 | }
|
14816 | var node$2 = this.startNodeAt(startPos, startLoc);
|
14817 | node$2.tag = base;
|
14818 | node$2.quasi = this.parseTemplate({isTagged: true});
|
14819 | base = this.finishNode(node$2, "TaggedTemplateExpression");
|
14820 | }
|
14821 | return base
|
14822 | };
|
14823 |
|
14824 |
|
14825 |
|
14826 |
|
14827 |
|
14828 |
|
14829 | pp$3.parseExprAtom = function(refDestructuringErrors) {
|
14830 |
|
14831 |
|
14832 | if (this.type === types.slash) { this.readRegexp(); }
|
14833 |
|
14834 | var node, canBeArrow = this.potentialArrowAt === this.start;
|
14835 | switch (this.type) {
|
14836 | case types._super:
|
14837 | if (!this.allowSuper)
|
14838 | { this.raise(this.start, "'super' keyword outside a method"); }
|
14839 | node = this.startNode();
|
14840 | this.next();
|
14841 | if (this.type === types.parenL && !this.allowDirectSuper)
|
14842 | { this.raise(node.start, "super() call outside constructor of a subclass"); }
|
14843 |
|
14844 |
|
14845 |
|
14846 |
|
14847 |
|
14848 |
|
14849 | if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
|
14850 | { this.unexpected(); }
|
14851 | return this.finishNode(node, "Super")
|
14852 |
|
14853 | case types._this:
|
14854 | node = this.startNode();
|
14855 | this.next();
|
14856 | return this.finishNode(node, "ThisExpression")
|
14857 |
|
14858 | case types.name:
|
14859 | var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
|
14860 | var id = this.parseIdent(false);
|
14861 | if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
|
14862 | { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
|
14863 | if (canBeArrow && !this.canInsertSemicolon()) {
|
14864 | if (this.eat(types.arrow))
|
14865 | { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
|
14866 | if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
|
14867 | id = this.parseIdent(false);
|
14868 | if (this.canInsertSemicolon() || !this.eat(types.arrow))
|
14869 | { this.unexpected(); }
|
14870 | return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
|
14871 | }
|
14872 | }
|
14873 | return id
|
14874 |
|
14875 | case types.regexp:
|
14876 | var value = this.value;
|
14877 | node = this.parseLiteral(value.value);
|
14878 | node.regex = {pattern: value.pattern, flags: value.flags};
|
14879 | return node
|
14880 |
|
14881 | case types.num: case types.string:
|
14882 | return this.parseLiteral(this.value)
|
14883 |
|
14884 | case types._null: case types._true: case types._false:
|
14885 | node = this.startNode();
|
14886 | node.value = this.type === types._null ? null : this.type === types._true;
|
14887 | node.raw = this.type.keyword;
|
14888 | this.next();
|
14889 | return this.finishNode(node, "Literal")
|
14890 |
|
14891 | case types.parenL:
|
14892 | var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
|
14893 | if (refDestructuringErrors) {
|
14894 | if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
|
14895 | { refDestructuringErrors.parenthesizedAssign = start; }
|
14896 | if (refDestructuringErrors.parenthesizedBind < 0)
|
14897 | { refDestructuringErrors.parenthesizedBind = start; }
|
14898 | }
|
14899 | return expr
|
14900 |
|
14901 | case types.bracketL:
|
14902 | node = this.startNode();
|
14903 | this.next();
|
14904 | node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
|
14905 | return this.finishNode(node, "ArrayExpression")
|
14906 |
|
14907 | case types.braceL:
|
14908 | return this.parseObj(false, refDestructuringErrors)
|
14909 |
|
14910 | case types._function:
|
14911 | node = this.startNode();
|
14912 | this.next();
|
14913 | return this.parseFunction(node, 0)
|
14914 |
|
14915 | case types._class:
|
14916 | return this.parseClass(this.startNode(), false)
|
14917 |
|
14918 | case types._new:
|
14919 | return this.parseNew()
|
14920 |
|
14921 | case types.backQuote:
|
14922 | return this.parseTemplate()
|
14923 |
|
14924 | case types._import:
|
14925 | if (this.options.ecmaVersion >= 11) {
|
14926 | return this.parseExprImport()
|
14927 | } else {
|
14928 | return this.unexpected()
|
14929 | }
|
14930 |
|
14931 | default:
|
14932 | this.unexpected();
|
14933 | }
|
14934 | };
|
14935 |
|
14936 | pp$3.parseExprImport = function() {
|
14937 | var node = this.startNode();
|
14938 |
|
14939 |
|
14940 |
|
14941 | if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
|
14942 | var meta = this.parseIdent(true);
|
14943 |
|
14944 | switch (this.type) {
|
14945 | case types.parenL:
|
14946 | return this.parseDynamicImport(node)
|
14947 | case types.dot:
|
14948 | node.meta = meta;
|
14949 | return this.parseImportMeta(node)
|
14950 | default:
|
14951 | this.unexpected();
|
14952 | }
|
14953 | };
|
14954 |
|
14955 | pp$3.parseDynamicImport = function(node) {
|
14956 | this.next();
|
14957 |
|
14958 |
|
14959 | node.source = this.parseMaybeAssign();
|
14960 |
|
14961 |
|
14962 | if (!this.eat(types.parenR)) {
|
14963 | var errorPos = this.start;
|
14964 | if (this.eat(types.comma) && this.eat(types.parenR)) {
|
14965 | this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
|
14966 | } else {
|
14967 | this.unexpected(errorPos);
|
14968 | }
|
14969 | }
|
14970 |
|
14971 | return this.finishNode(node, "ImportExpression")
|
14972 | };
|
14973 |
|
14974 | pp$3.parseImportMeta = function(node) {
|
14975 | this.next();
|
14976 |
|
14977 | var containsEsc = this.containsEsc;
|
14978 | node.property = this.parseIdent(true);
|
14979 |
|
14980 | if (node.property.name !== "meta")
|
14981 | { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
|
14982 | if (containsEsc)
|
14983 | { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
|
14984 | if (this.options.sourceType !== "module")
|
14985 | { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
|
14986 |
|
14987 | return this.finishNode(node, "MetaProperty")
|
14988 | };
|
14989 |
|
14990 | pp$3.parseLiteral = function(value) {
|
14991 | var node = this.startNode();
|
14992 | node.value = value;
|
14993 | node.raw = this.input.slice(this.start, this.end);
|
14994 | if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
|
14995 | this.next();
|
14996 | return this.finishNode(node, "Literal")
|
14997 | };
|
14998 |
|
14999 | pp$3.parseParenExpression = function() {
|
15000 | this.expect(types.parenL);
|
15001 | var val = this.parseExpression();
|
15002 | this.expect(types.parenR);
|
15003 | return val
|
15004 | };
|
15005 |
|
15006 | pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
|
15007 | var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
|
15008 | if (this.options.ecmaVersion >= 6) {
|
15009 | this.next();
|
15010 |
|
15011 | var innerStartPos = this.start, innerStartLoc = this.startLoc;
|
15012 | var exprList = [], first = true, lastIsComma = false;
|
15013 | var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
|
15014 | this.yieldPos = 0;
|
15015 | this.awaitPos = 0;
|
15016 |
|
15017 | while (this.type !== types.parenR) {
|
15018 | first ? first = false : this.expect(types.comma);
|
15019 | if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
|
15020 | lastIsComma = true;
|
15021 | break
|
15022 | } else if (this.type === types.ellipsis) {
|
15023 | spreadStart = this.start;
|
15024 | exprList.push(this.parseParenItem(this.parseRestBinding()));
|
15025 | if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
|
15026 | break
|
15027 | } else {
|
15028 | exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
|
15029 | }
|
15030 | }
|
15031 | var innerEndPos = this.start, innerEndLoc = this.startLoc;
|
15032 | this.expect(types.parenR);
|
15033 |
|
15034 | if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
|
15035 | this.checkPatternErrors(refDestructuringErrors, false);
|
15036 | this.checkYieldAwaitInDefaultParams();
|
15037 | this.yieldPos = oldYieldPos;
|
15038 | this.awaitPos = oldAwaitPos;
|
15039 | return this.parseParenArrowList(startPos, startLoc, exprList)
|
15040 | }
|
15041 |
|
15042 | if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
|
15043 | if (spreadStart) { this.unexpected(spreadStart); }
|
15044 | this.checkExpressionErrors(refDestructuringErrors, true);
|
15045 | this.yieldPos = oldYieldPos || this.yieldPos;
|
15046 | this.awaitPos = oldAwaitPos || this.awaitPos;
|
15047 |
|
15048 | if (exprList.length > 1) {
|
15049 | val = this.startNodeAt(innerStartPos, innerStartLoc);
|
15050 | val.expressions = exprList;
|
15051 | this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
|
15052 | } else {
|
15053 | val = exprList[0];
|
15054 | }
|
15055 | } else {
|
15056 | val = this.parseParenExpression();
|
15057 | }
|
15058 |
|
15059 | if (this.options.preserveParens) {
|
15060 | var par = this.startNodeAt(startPos, startLoc);
|
15061 | par.expression = val;
|
15062 | return this.finishNode(par, "ParenthesizedExpression")
|
15063 | } else {
|
15064 | return val
|
15065 | }
|
15066 | };
|
15067 |
|
15068 | pp$3.parseParenItem = function(item) {
|
15069 | return item
|
15070 | };
|
15071 |
|
15072 | pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
|
15073 | return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
|
15074 | };
|
15075 |
|
15076 |
|
15077 |
|
15078 |
|
15079 |
|
15080 |
|
15081 |
|
15082 | var empty$1 = [];
|
15083 |
|
15084 | pp$3.parseNew = function() {
|
15085 | if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
|
15086 | var node = this.startNode();
|
15087 | var meta = this.parseIdent(true);
|
15088 | if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
|
15089 | node.meta = meta;
|
15090 | var containsEsc = this.containsEsc;
|
15091 | node.property = this.parseIdent(true);
|
15092 | if (node.property.name !== "target")
|
15093 | { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
|
15094 | if (containsEsc)
|
15095 | { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
|
15096 | if (!this.inNonArrowFunction)
|
15097 | { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
|
15098 | return this.finishNode(node, "MetaProperty")
|
15099 | }
|
15100 | var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
|
15101 | node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
|
15102 | if (isImport && node.callee.type === "ImportExpression") {
|
15103 | this.raise(startPos, "Cannot use new with import()");
|
15104 | }
|
15105 | if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
|
15106 | else { node.arguments = empty$1; }
|
15107 | return this.finishNode(node, "NewExpression")
|
15108 | };
|
15109 |
|
15110 |
|
15111 |
|
15112 | pp$3.parseTemplateElement = function(ref) {
|
15113 | var isTagged = ref.isTagged;
|
15114 |
|
15115 | var elem = this.startNode();
|
15116 | if (this.type === types.invalidTemplate) {
|
15117 | if (!isTagged) {
|
15118 | this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
|
15119 | }
|
15120 | elem.value = {
|
15121 | raw: this.value,
|
15122 | cooked: null
|
15123 | };
|
15124 | } else {
|
15125 | elem.value = {
|
15126 | raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
|
15127 | cooked: this.value
|
15128 | };
|
15129 | }
|
15130 | this.next();
|
15131 | elem.tail = this.type === types.backQuote;
|
15132 | return this.finishNode(elem, "TemplateElement")
|
15133 | };
|
15134 |
|
15135 | pp$3.parseTemplate = function(ref) {
|
15136 | if ( ref === void 0 ) ref = {};
|
15137 | var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
|
15138 |
|
15139 | var node = this.startNode();
|
15140 | this.next();
|
15141 | node.expressions = [];
|
15142 | var curElt = this.parseTemplateElement({isTagged: isTagged});
|
15143 | node.quasis = [curElt];
|
15144 | while (!curElt.tail) {
|
15145 | if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
|
15146 | this.expect(types.dollarBraceL);
|
15147 | node.expressions.push(this.parseExpression());
|
15148 | this.expect(types.braceR);
|
15149 | node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
|
15150 | }
|
15151 | this.next();
|
15152 | return this.finishNode(node, "TemplateLiteral")
|
15153 | };
|
15154 |
|
15155 | pp$3.isAsyncProp = function(prop) {
|
15156 | return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
|
15157 | (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
|
15158 | !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
|
15159 | };
|
15160 |
|
15161 |
|
15162 |
|
15163 | pp$3.parseObj = function(isPattern, refDestructuringErrors) {
|
15164 | var node = this.startNode(), first = true, propHash = {};
|
15165 | node.properties = [];
|
15166 | this.next();
|
15167 | while (!this.eat(types.braceR)) {
|
15168 | if (!first) {
|
15169 | this.expect(types.comma);
|
15170 | if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
|
15171 | } else { first = false; }
|
15172 |
|
15173 | var prop = this.parseProperty(isPattern, refDestructuringErrors);
|
15174 | if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
|
15175 | node.properties.push(prop);
|
15176 | }
|
15177 | return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
|
15178 | };
|
15179 |
|
15180 | pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
|
15181 | var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
|
15182 | if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
|
15183 | if (isPattern) {
|
15184 | prop.argument = this.parseIdent(false);
|
15185 | if (this.type === types.comma) {
|
15186 | this.raise(this.start, "Comma is not permitted after the rest element");
|
15187 | }
|
15188 | return this.finishNode(prop, "RestElement")
|
15189 | }
|
15190 |
|
15191 | if (this.type === types.parenL && refDestructuringErrors) {
|
15192 | if (refDestructuringErrors.parenthesizedAssign < 0) {
|
15193 | refDestructuringErrors.parenthesizedAssign = this.start;
|
15194 | }
|
15195 | if (refDestructuringErrors.parenthesizedBind < 0) {
|
15196 | refDestructuringErrors.parenthesizedBind = this.start;
|
15197 | }
|
15198 | }
|
15199 |
|
15200 | prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
|
15201 |
|
15202 | if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
|
15203 | refDestructuringErrors.trailingComma = this.start;
|
15204 | }
|
15205 |
|
15206 | return this.finishNode(prop, "SpreadElement")
|
15207 | }
|
15208 | if (this.options.ecmaVersion >= 6) {
|
15209 | prop.method = false;
|
15210 | prop.shorthand = false;
|
15211 | if (isPattern || refDestructuringErrors) {
|
15212 | startPos = this.start;
|
15213 | startLoc = this.startLoc;
|
15214 | }
|
15215 | if (!isPattern)
|
15216 | { isGenerator = this.eat(types.star); }
|
15217 | }
|
15218 | var containsEsc = this.containsEsc;
|
15219 | this.parsePropertyName(prop);
|
15220 | if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
|
15221 | isAsync = true;
|
15222 | isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
|
15223 | this.parsePropertyName(prop, refDestructuringErrors);
|
15224 | } else {
|
15225 | isAsync = false;
|
15226 | }
|
15227 | this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
|
15228 | return this.finishNode(prop, "Property")
|
15229 | };
|
15230 |
|
15231 | pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
|
15232 | if ((isGenerator || isAsync) && this.type === types.colon)
|
15233 | { this.unexpected(); }
|
15234 |
|
15235 | if (this.eat(types.colon)) {
|
15236 | prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
|
15237 | prop.kind = "init";
|
15238 | } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
|
15239 | if (isPattern) { this.unexpected(); }
|
15240 | prop.kind = "init";
|
15241 | prop.method = true;
|
15242 | prop.value = this.parseMethod(isGenerator, isAsync);
|
15243 | } else if (!isPattern && !containsEsc &&
|
15244 | this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
|
15245 | (prop.key.name === "get" || prop.key.name === "set") &&
|
15246 | (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
|
15247 | if (isGenerator || isAsync) { this.unexpected(); }
|
15248 | prop.kind = prop.key.name;
|
15249 | this.parsePropertyName(prop);
|
15250 | prop.value = this.parseMethod(false);
|
15251 | var paramCount = prop.kind === "get" ? 0 : 1;
|
15252 | if (prop.value.params.length !== paramCount) {
|
15253 | var start = prop.value.start;
|
15254 | if (prop.kind === "get")
|
15255 | { this.raiseRecoverable(start, "getter should have no params"); }
|
15256 | else
|
15257 | { this.raiseRecoverable(start, "setter should have exactly one param"); }
|
15258 | } else {
|
15259 | if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
|
15260 | { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
|
15261 | }
|
15262 | } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
|
15263 | if (isGenerator || isAsync) { this.unexpected(); }
|
15264 | this.checkUnreserved(prop.key);
|
15265 | if (prop.key.name === "await" && !this.awaitIdentPos)
|
15266 | { this.awaitIdentPos = startPos; }
|
15267 | prop.kind = "init";
|
15268 | if (isPattern) {
|
15269 | prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
|
15270 | } else if (this.type === types.eq && refDestructuringErrors) {
|
15271 | if (refDestructuringErrors.shorthandAssign < 0)
|
15272 | { refDestructuringErrors.shorthandAssign = this.start; }
|
15273 | prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
|
15274 | } else {
|
15275 | prop.value = this.copyNode(prop.key);
|
15276 | }
|
15277 | prop.shorthand = true;
|
15278 | } else { this.unexpected(); }
|
15279 | };
|
15280 |
|
15281 | pp$3.parsePropertyName = function(prop) {
|
15282 | if (this.options.ecmaVersion >= 6) {
|
15283 | if (this.eat(types.bracketL)) {
|
15284 | prop.computed = true;
|
15285 | prop.key = this.parseMaybeAssign();
|
15286 | this.expect(types.bracketR);
|
15287 | return prop.key
|
15288 | } else {
|
15289 | prop.computed = false;
|
15290 | }
|
15291 | }
|
15292 | return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
|
15293 | };
|
15294 |
|
15295 |
|
15296 |
|
15297 | pp$3.initFunction = function(node) {
|
15298 | node.id = null;
|
15299 | if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
|
15300 | if (this.options.ecmaVersion >= 8) { node.async = false; }
|
15301 | };
|
15302 |
|
15303 |
|
15304 |
|
15305 | pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
|
15306 | var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
|
15307 |
|
15308 | this.initFunction(node);
|
15309 | if (this.options.ecmaVersion >= 6)
|
15310 | { node.generator = isGenerator; }
|
15311 | if (this.options.ecmaVersion >= 8)
|
15312 | { node.async = !!isAsync; }
|
15313 |
|
15314 | this.yieldPos = 0;
|
15315 | this.awaitPos = 0;
|
15316 | this.awaitIdentPos = 0;
|
15317 | this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
|
15318 |
|
15319 | this.expect(types.parenL);
|
15320 | node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
|
15321 | this.checkYieldAwaitInDefaultParams();
|
15322 | this.parseFunctionBody(node, false, true);
|
15323 |
|
15324 | this.yieldPos = oldYieldPos;
|
15325 | this.awaitPos = oldAwaitPos;
|
15326 | this.awaitIdentPos = oldAwaitIdentPos;
|
15327 | return this.finishNode(node, "FunctionExpression")
|
15328 | };
|
15329 |
|
15330 |
|
15331 |
|
15332 | pp$3.parseArrowExpression = function(node, params, isAsync) {
|
15333 | var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
|
15334 |
|
15335 | this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
|
15336 | this.initFunction(node);
|
15337 | if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
|
15338 |
|
15339 | this.yieldPos = 0;
|
15340 | this.awaitPos = 0;
|
15341 | this.awaitIdentPos = 0;
|
15342 |
|
15343 | node.params = this.toAssignableList(params, true);
|
15344 | this.parseFunctionBody(node, true, false);
|
15345 |
|
15346 | this.yieldPos = oldYieldPos;
|
15347 | this.awaitPos = oldAwaitPos;
|
15348 | this.awaitIdentPos = oldAwaitIdentPos;
|
15349 | return this.finishNode(node, "ArrowFunctionExpression")
|
15350 | };
|
15351 |
|
15352 |
|
15353 |
|
15354 | pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
|
15355 | var isExpression = isArrowFunction && this.type !== types.braceL;
|
15356 | var oldStrict = this.strict, useStrict = false;
|
15357 |
|
15358 | if (isExpression) {
|
15359 | node.body = this.parseMaybeAssign();
|
15360 | node.expression = true;
|
15361 | this.checkParams(node, false);
|
15362 | } else {
|
15363 | var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
|
15364 | if (!oldStrict || nonSimple) {
|
15365 | useStrict = this.strictDirective(this.end);
|
15366 |
|
15367 |
|
15368 |
|
15369 | if (useStrict && nonSimple)
|
15370 | { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
|
15371 | }
|
15372 |
|
15373 |
|
15374 | var oldLabels = this.labels;
|
15375 | this.labels = [];
|
15376 | if (useStrict) { this.strict = true; }
|
15377 |
|
15378 |
|
15379 |
|
15380 | this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
|
15381 |
|
15382 | if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
|
15383 | node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
|
15384 | node.expression = false;
|
15385 | this.adaptDirectivePrologue(node.body.body);
|
15386 | this.labels = oldLabels;
|
15387 | }
|
15388 | this.exitScope();
|
15389 | };
|
15390 |
|
15391 | pp$3.isSimpleParamList = function(params) {
|
15392 | for (var i = 0, list = params; i < list.length; i += 1)
|
15393 | {
|
15394 | var param = list[i];
|
15395 |
|
15396 | if (param.type !== "Identifier") { return false
|
15397 | } }
|
15398 | return true
|
15399 | };
|
15400 |
|
15401 |
|
15402 |
|
15403 |
|
15404 | pp$3.checkParams = function(node, allowDuplicates) {
|
15405 | var nameHash = {};
|
15406 | for (var i = 0, list = node.params; i < list.length; i += 1)
|
15407 | {
|
15408 | var param = list[i];
|
15409 |
|
15410 | this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
|
15411 | }
|
15412 | };
|
15413 |
|
15414 |
|
15415 |
|
15416 |
|
15417 |
|
15418 |
|
15419 |
|
15420 | pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
|
15421 | var elts = [], first = true;
|
15422 | while (!this.eat(close)) {
|
15423 | if (!first) {
|
15424 | this.expect(types.comma);
|
15425 | if (allowTrailingComma && this.afterTrailingComma(close)) { break }
|
15426 | } else { first = false; }
|
15427 |
|
15428 | var elt = (void 0);
|
15429 | if (allowEmpty && this.type === types.comma)
|
15430 | { elt = null; }
|
15431 | else if (this.type === types.ellipsis) {
|
15432 | elt = this.parseSpread(refDestructuringErrors);
|
15433 | if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
|
15434 | { refDestructuringErrors.trailingComma = this.start; }
|
15435 | } else {
|
15436 | elt = this.parseMaybeAssign(false, refDestructuringErrors);
|
15437 | }
|
15438 | elts.push(elt);
|
15439 | }
|
15440 | return elts
|
15441 | };
|
15442 |
|
15443 | pp$3.checkUnreserved = function(ref) {
|
15444 | var start = ref.start;
|
15445 | var end = ref.end;
|
15446 | var name = ref.name;
|
15447 |
|
15448 | if (this.inGenerator && name === "yield")
|
15449 | { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
|
15450 | if (this.inAsync && name === "await")
|
15451 | { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
|
15452 | if (this.keywords.test(name))
|
15453 | { this.raise(start, ("Unexpected keyword '" + name + "'")); }
|
15454 | if (this.options.ecmaVersion < 6 &&
|
15455 | this.input.slice(start, end).indexOf("\\") !== -1) { return }
|
15456 | var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
|
15457 | if (re.test(name)) {
|
15458 | if (!this.inAsync && name === "await")
|
15459 | { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
|
15460 | this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
|
15461 | }
|
15462 | };
|
15463 |
|
15464 |
|
15465 |
|
15466 |
|
15467 |
|
15468 | pp$3.parseIdent = function(liberal, isBinding) {
|
15469 | var node = this.startNode();
|
15470 | if (this.type === types.name) {
|
15471 | node.name = this.value;
|
15472 | } else if (this.type.keyword) {
|
15473 | node.name = this.type.keyword;
|
15474 |
|
15475 |
|
15476 |
|
15477 |
|
15478 |
|
15479 | if ((node.name === "class" || node.name === "function") &&
|
15480 | (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
|
15481 | this.context.pop();
|
15482 | }
|
15483 | } else {
|
15484 | this.unexpected();
|
15485 | }
|
15486 | this.next(!!liberal);
|
15487 | this.finishNode(node, "Identifier");
|
15488 | if (!liberal) {
|
15489 | this.checkUnreserved(node);
|
15490 | if (node.name === "await" && !this.awaitIdentPos)
|
15491 | { this.awaitIdentPos = node.start; }
|
15492 | }
|
15493 | return node
|
15494 | };
|
15495 |
|
15496 |
|
15497 |
|
15498 | pp$3.parseYield = function(noIn) {
|
15499 | if (!this.yieldPos) { this.yieldPos = this.start; }
|
15500 |
|
15501 | var node = this.startNode();
|
15502 | this.next();
|
15503 | if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
|
15504 | node.delegate = false;
|
15505 | node.argument = null;
|
15506 | } else {
|
15507 | node.delegate = this.eat(types.star);
|
15508 | node.argument = this.parseMaybeAssign(noIn);
|
15509 | }
|
15510 | return this.finishNode(node, "YieldExpression")
|
15511 | };
|
15512 |
|
15513 | pp$3.parseAwait = function() {
|
15514 | if (!this.awaitPos) { this.awaitPos = this.start; }
|
15515 |
|
15516 | var node = this.startNode();
|
15517 | this.next();
|
15518 | node.argument = this.parseMaybeUnary(null, false);
|
15519 | return this.finishNode(node, "AwaitExpression")
|
15520 | };
|
15521 |
|
15522 | var pp$4 = Parser.prototype;
|
15523 |
|
15524 |
|
15525 |
|
15526 |
|
15527 |
|
15528 |
|
15529 |
|
15530 | pp$4.raise = function(pos, message) {
|
15531 | var loc = getLineInfo(this.input, pos);
|
15532 | message += " (" + loc.line + ":" + loc.column + ")";
|
15533 | var err = new SyntaxError(message);
|
15534 | err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
|
15535 | throw err
|
15536 | };
|
15537 |
|
15538 | pp$4.raiseRecoverable = pp$4.raise;
|
15539 |
|
15540 | pp$4.curPosition = function() {
|
15541 | if (this.options.locations) {
|
15542 | return new Position(this.curLine, this.pos - this.lineStart)
|
15543 | }
|
15544 | };
|
15545 |
|
15546 | var pp$5 = Parser.prototype;
|
15547 |
|
15548 | var Scope$1 = function Scope(flags) {
|
15549 | this.flags = flags;
|
15550 |
|
15551 | this.var = [];
|
15552 |
|
15553 | this.lexical = [];
|
15554 |
|
15555 | this.functions = [];
|
15556 | };
|
15557 |
|
15558 |
|
15559 |
|
15560 | pp$5.enterScope = function(flags) {
|
15561 | this.scopeStack.push(new Scope$1(flags));
|
15562 | };
|
15563 |
|
15564 | pp$5.exitScope = function() {
|
15565 | this.scopeStack.pop();
|
15566 | };
|
15567 |
|
15568 |
|
15569 |
|
15570 |
|
15571 | pp$5.treatFunctionsAsVarInScope = function(scope) {
|
15572 | return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
|
15573 | };
|
15574 |
|
15575 | pp$5.declareName = function(name, bindingType, pos) {
|
15576 | var redeclared = false;
|
15577 | if (bindingType === BIND_LEXICAL) {
|
15578 | var scope = this.currentScope();
|
15579 | redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
|
15580 | scope.lexical.push(name);
|
15581 | if (this.inModule && (scope.flags & SCOPE_TOP))
|
15582 | { delete this.undefinedExports[name]; }
|
15583 | } else if (bindingType === BIND_SIMPLE_CATCH) {
|
15584 | var scope$1 = this.currentScope();
|
15585 | scope$1.lexical.push(name);
|
15586 | } else if (bindingType === BIND_FUNCTION) {
|
15587 | var scope$2 = this.currentScope();
|
15588 | if (this.treatFunctionsAsVar)
|
15589 | { redeclared = scope$2.lexical.indexOf(name) > -1; }
|
15590 | else
|
15591 | { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
|
15592 | scope$2.functions.push(name);
|
15593 | } else {
|
15594 | for (var i = this.scopeStack.length - 1; i >= 0; --i) {
|
15595 | var scope$3 = this.scopeStack[i];
|
15596 | if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
|
15597 | !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
|
15598 | redeclared = true;
|
15599 | break
|
15600 | }
|
15601 | scope$3.var.push(name);
|
15602 | if (this.inModule && (scope$3.flags & SCOPE_TOP))
|
15603 | { delete this.undefinedExports[name]; }
|
15604 | if (scope$3.flags & SCOPE_VAR) { break }
|
15605 | }
|
15606 | }
|
15607 | if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
|
15608 | };
|
15609 |
|
15610 | pp$5.checkLocalExport = function(id) {
|
15611 |
|
15612 | if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
|
15613 | this.scopeStack[0].var.indexOf(id.name) === -1) {
|
15614 | this.undefinedExports[id.name] = id;
|
15615 | }
|
15616 | };
|
15617 |
|
15618 | pp$5.currentScope = function() {
|
15619 | return this.scopeStack[this.scopeStack.length - 1]
|
15620 | };
|
15621 |
|
15622 | pp$5.currentVarScope = function() {
|
15623 | for (var i = this.scopeStack.length - 1;; i--) {
|
15624 | var scope = this.scopeStack[i];
|
15625 | if (scope.flags & SCOPE_VAR) { return scope }
|
15626 | }
|
15627 | };
|
15628 |
|
15629 |
|
15630 | pp$5.currentThisScope = function() {
|
15631 | for (var i = this.scopeStack.length - 1;; i--) {
|
15632 | var scope = this.scopeStack[i];
|
15633 | if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
|
15634 | }
|
15635 | };
|
15636 |
|
15637 | var Node = function Node(parser, pos, loc) {
|
15638 | this.type = "";
|
15639 | this.start = pos;
|
15640 | this.end = 0;
|
15641 | if (parser.options.locations)
|
15642 | { this.loc = new SourceLocation(parser, loc); }
|
15643 | if (parser.options.directSourceFile)
|
15644 | { this.sourceFile = parser.options.directSourceFile; }
|
15645 | if (parser.options.ranges)
|
15646 | { this.range = [pos, 0]; }
|
15647 | };
|
15648 |
|
15649 |
|
15650 |
|
15651 | var pp$6 = Parser.prototype;
|
15652 |
|
15653 | pp$6.startNode = function() {
|
15654 | return new Node(this, this.start, this.startLoc)
|
15655 | };
|
15656 |
|
15657 | pp$6.startNodeAt = function(pos, loc) {
|
15658 | return new Node(this, pos, loc)
|
15659 | };
|
15660 |
|
15661 |
|
15662 |
|
15663 | function finishNodeAt(node, type, pos, loc) {
|
15664 | node.type = type;
|
15665 | node.end = pos;
|
15666 | if (this.options.locations)
|
15667 | { node.loc.end = loc; }
|
15668 | if (this.options.ranges)
|
15669 | { node.range[1] = pos; }
|
15670 | return node
|
15671 | }
|
15672 |
|
15673 | pp$6.finishNode = function(node, type) {
|
15674 | return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
|
15675 | };
|
15676 |
|
15677 |
|
15678 |
|
15679 | pp$6.finishNodeAt = function(node, type, pos, loc) {
|
15680 | return finishNodeAt.call(this, node, type, pos, loc)
|
15681 | };
|
15682 |
|
15683 | pp$6.copyNode = function(node) {
|
15684 | var newNode = new Node(this, node.start, this.startLoc);
|
15685 | for (var prop in node) { newNode[prop] = node[prop]; }
|
15686 | return newNode
|
15687 | };
|
15688 |
|
15689 |
|
15690 |
|
15691 | var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
|
15692 | this.token = token;
|
15693 | this.isExpr = !!isExpr;
|
15694 | this.preserveSpace = !!preserveSpace;
|
15695 | this.override = override;
|
15696 | this.generator = !!generator;
|
15697 | };
|
15698 |
|
15699 | var types$1 = {
|
15700 | b_stat: new TokContext("{", false),
|
15701 | b_expr: new TokContext("{", true),
|
15702 | b_tmpl: new TokContext("${", false),
|
15703 | p_stat: new TokContext("(", false),
|
15704 | p_expr: new TokContext("(", true),
|
15705 | q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
|
15706 | f_stat: new TokContext("function", false),
|
15707 | f_expr: new TokContext("function", true),
|
15708 | f_expr_gen: new TokContext("function", true, false, null, true),
|
15709 | f_gen: new TokContext("function", false, false, null, true)
|
15710 | };
|
15711 |
|
15712 | var pp$7 = Parser.prototype;
|
15713 |
|
15714 | pp$7.initialContext = function() {
|
15715 | return [types$1.b_stat]
|
15716 | };
|
15717 |
|
15718 | pp$7.braceIsBlock = function(prevType) {
|
15719 | var parent = this.curContext();
|
15720 | if (parent === types$1.f_expr || parent === types$1.f_stat)
|
15721 | { return true }
|
15722 | if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
|
15723 | { return !parent.isExpr }
|
15724 |
|
15725 |
|
15726 |
|
15727 |
|
15728 | if (prevType === types._return || prevType === types.name && this.exprAllowed)
|
15729 | { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
|
15730 | if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
|
15731 | { return true }
|
15732 | if (prevType === types.braceL)
|
15733 | { return parent === types$1.b_stat }
|
15734 | if (prevType === types._var || prevType === types._const || prevType === types.name)
|
15735 | { return false }
|
15736 | return !this.exprAllowed
|
15737 | };
|
15738 |
|
15739 | pp$7.inGeneratorContext = function() {
|
15740 | for (var i = this.context.length - 1; i >= 1; i--) {
|
15741 | var context = this.context[i];
|
15742 | if (context.token === "function")
|
15743 | { return context.generator }
|
15744 | }
|
15745 | return false
|
15746 | };
|
15747 |
|
15748 | pp$7.updateContext = function(prevType) {
|
15749 | var update, type = this.type;
|
15750 | if (type.keyword && prevType === types.dot)
|
15751 | { this.exprAllowed = false; }
|
15752 | else if (update = type.updateContext)
|
15753 | { update.call(this, prevType); }
|
15754 | else
|
15755 | { this.exprAllowed = type.beforeExpr; }
|
15756 | };
|
15757 |
|
15758 |
|
15759 |
|
15760 | types.parenR.updateContext = types.braceR.updateContext = function() {
|
15761 | if (this.context.length === 1) {
|
15762 | this.exprAllowed = true;
|
15763 | return
|
15764 | }
|
15765 | var out = this.context.pop();
|
15766 | if (out === types$1.b_stat && this.curContext().token === "function") {
|
15767 | out = this.context.pop();
|
15768 | }
|
15769 | this.exprAllowed = !out.isExpr;
|
15770 | };
|
15771 |
|
15772 | types.braceL.updateContext = function(prevType) {
|
15773 | this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
|
15774 | this.exprAllowed = true;
|
15775 | };
|
15776 |
|
15777 | types.dollarBraceL.updateContext = function() {
|
15778 | this.context.push(types$1.b_tmpl);
|
15779 | this.exprAllowed = true;
|
15780 | };
|
15781 |
|
15782 | types.parenL.updateContext = function(prevType) {
|
15783 | var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
|
15784 | this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
|
15785 | this.exprAllowed = true;
|
15786 | };
|
15787 |
|
15788 | types.incDec.updateContext = function() {
|
15789 |
|
15790 | };
|
15791 |
|
15792 | types._function.updateContext = types._class.updateContext = function(prevType) {
|
15793 | if (prevType.beforeExpr && prevType !== types._else &&
|
15794 | !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
|
15795 | !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
|
15796 | !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
|
15797 | { this.context.push(types$1.f_expr); }
|
15798 | else
|
15799 | { this.context.push(types$1.f_stat); }
|
15800 | this.exprAllowed = false;
|
15801 | };
|
15802 |
|
15803 | types.backQuote.updateContext = function() {
|
15804 | if (this.curContext() === types$1.q_tmpl)
|
15805 | { this.context.pop(); }
|
15806 | else
|
15807 | { this.context.push(types$1.q_tmpl); }
|
15808 | this.exprAllowed = false;
|
15809 | };
|
15810 |
|
15811 | types.star.updateContext = function(prevType) {
|
15812 | if (prevType === types._function) {
|
15813 | var index = this.context.length - 1;
|
15814 | if (this.context[index] === types$1.f_expr)
|
15815 | { this.context[index] = types$1.f_expr_gen; }
|
15816 | else
|
15817 | { this.context[index] = types$1.f_gen; }
|
15818 | }
|
15819 | this.exprAllowed = true;
|
15820 | };
|
15821 |
|
15822 | types.name.updateContext = function(prevType) {
|
15823 | var allowed = false;
|
15824 | if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
|
15825 | if (this.value === "of" && !this.exprAllowed ||
|
15826 | this.value === "yield" && this.inGeneratorContext())
|
15827 | { allowed = true; }
|
15828 | }
|
15829 | this.exprAllowed = allowed;
|
15830 | };
|
15831 |
|
15832 |
|
15833 |
|
15834 |
|
15835 |
|
15836 |
|
15837 | var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
|
15838 | var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
|
15839 | var ecma11BinaryProperties = ecma10BinaryProperties;
|
15840 | var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
|
15841 | var unicodeBinaryProperties = {
|
15842 | 9: ecma9BinaryProperties,
|
15843 | 10: ecma10BinaryProperties,
|
15844 | 11: ecma11BinaryProperties,
|
15845 | 12: ecma12BinaryProperties
|
15846 | };
|
15847 |
|
15848 |
|
15849 | var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
|
15850 |
|
15851 |
|
15852 | var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
|
15853 | var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
|
15854 | var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
|
15855 | var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
|
15856 | var unicodeScriptValues = {
|
15857 | 9: ecma9ScriptValues,
|
15858 | 10: ecma10ScriptValues,
|
15859 | 11: ecma11ScriptValues,
|
15860 | 12: ecma12ScriptValues
|
15861 | };
|
15862 |
|
15863 | var data = {};
|
15864 | function buildUnicodeData(ecmaVersion) {
|
15865 | var d = data[ecmaVersion] = {
|
15866 | binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
|
15867 | nonBinary: {
|
15868 | General_Category: wordsRegexp(unicodeGeneralCategoryValues),
|
15869 | Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
|
15870 | }
|
15871 | };
|
15872 | d.nonBinary.Script_Extensions = d.nonBinary.Script;
|
15873 |
|
15874 | d.nonBinary.gc = d.nonBinary.General_Category;
|
15875 | d.nonBinary.sc = d.nonBinary.Script;
|
15876 | d.nonBinary.scx = d.nonBinary.Script_Extensions;
|
15877 | }
|
15878 | buildUnicodeData(9);
|
15879 | buildUnicodeData(10);
|
15880 | buildUnicodeData(11);
|
15881 | buildUnicodeData(12);
|
15882 |
|
15883 | var pp$8 = Parser.prototype;
|
15884 |
|
15885 | var RegExpValidationState = function RegExpValidationState(parser) {
|
15886 | this.parser = parser;
|
15887 | this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
|
15888 | this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
|
15889 | this.source = "";
|
15890 | this.flags = "";
|
15891 | this.start = 0;
|
15892 | this.switchU = false;
|
15893 | this.switchN = false;
|
15894 | this.pos = 0;
|
15895 | this.lastIntValue = 0;
|
15896 | this.lastStringValue = "";
|
15897 | this.lastAssertionIsQuantifiable = false;
|
15898 | this.numCapturingParens = 0;
|
15899 | this.maxBackReference = 0;
|
15900 | this.groupNames = [];
|
15901 | this.backReferenceNames = [];
|
15902 | };
|
15903 |
|
15904 | RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
|
15905 | var unicode = flags.indexOf("u") !== -1;
|
15906 | this.start = start | 0;
|
15907 | this.source = pattern + "";
|
15908 | this.flags = flags;
|
15909 | this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
|
15910 | this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
|
15911 | };
|
15912 |
|
15913 | RegExpValidationState.prototype.raise = function raise (message) {
|
15914 | this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
|
15915 | };
|
15916 |
|
15917 |
|
15918 |
|
15919 | RegExpValidationState.prototype.at = function at (i, forceU) {
|
15920 | if ( forceU === void 0 ) forceU = false;
|
15921 |
|
15922 | var s = this.source;
|
15923 | var l = s.length;
|
15924 | if (i >= l) {
|
15925 | return -1
|
15926 | }
|
15927 | var c = s.charCodeAt(i);
|
15928 | if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
|
15929 | return c
|
15930 | }
|
15931 | var next = s.charCodeAt(i + 1);
|
15932 | return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
|
15933 | };
|
15934 |
|
15935 | RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
|
15936 | if ( forceU === void 0 ) forceU = false;
|
15937 |
|
15938 | var s = this.source;
|
15939 | var l = s.length;
|
15940 | if (i >= l) {
|
15941 | return l
|
15942 | }
|
15943 | var c = s.charCodeAt(i), next;
|
15944 | if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
|
15945 | (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
|
15946 | return i + 1
|
15947 | }
|
15948 | return i + 2
|
15949 | };
|
15950 |
|
15951 | RegExpValidationState.prototype.current = function current (forceU) {
|
15952 | if ( forceU === void 0 ) forceU = false;
|
15953 |
|
15954 | return this.at(this.pos, forceU)
|
15955 | };
|
15956 |
|
15957 | RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
|
15958 | if ( forceU === void 0 ) forceU = false;
|
15959 |
|
15960 | return this.at(this.nextIndex(this.pos, forceU), forceU)
|
15961 | };
|
15962 |
|
15963 | RegExpValidationState.prototype.advance = function advance (forceU) {
|
15964 | if ( forceU === void 0 ) forceU = false;
|
15965 |
|
15966 | this.pos = this.nextIndex(this.pos, forceU);
|
15967 | };
|
15968 |
|
15969 | RegExpValidationState.prototype.eat = function eat (ch, forceU) {
|
15970 | if ( forceU === void 0 ) forceU = false;
|
15971 |
|
15972 | if (this.current(forceU) === ch) {
|
15973 | this.advance(forceU);
|
15974 | return true
|
15975 | }
|
15976 | return false
|
15977 | };
|
15978 |
|
15979 | function codePointToString(ch) {
|
15980 | if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
|
15981 | ch -= 0x10000;
|
15982 | return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
|
15983 | }
|
15984 |
|
15985 |
|
15986 |
|
15987 |
|
15988 |
|
15989 |
|
15990 |
|
15991 | pp$8.validateRegExpFlags = function(state) {
|
15992 | var validFlags = state.validFlags;
|
15993 | var flags = state.flags;
|
15994 |
|
15995 | for (var i = 0; i < flags.length; i++) {
|
15996 | var flag = flags.charAt(i);
|
15997 | if (validFlags.indexOf(flag) === -1) {
|
15998 | this.raise(state.start, "Invalid regular expression flag");
|
15999 | }
|
16000 | if (flags.indexOf(flag, i + 1) > -1) {
|
16001 | this.raise(state.start, "Duplicate regular expression flag");
|
16002 | }
|
16003 | }
|
16004 | };
|
16005 |
|
16006 |
|
16007 |
|
16008 |
|
16009 |
|
16010 |
|
16011 |
|
16012 | pp$8.validateRegExpPattern = function(state) {
|
16013 | this.regexp_pattern(state);
|
16014 |
|
16015 |
|
16016 |
|
16017 |
|
16018 |
|
16019 |
|
16020 | if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
|
16021 | state.switchN = true;
|
16022 | this.regexp_pattern(state);
|
16023 | }
|
16024 | };
|
16025 |
|
16026 |
|
16027 | pp$8.regexp_pattern = function(state) {
|
16028 | state.pos = 0;
|
16029 | state.lastIntValue = 0;
|
16030 | state.lastStringValue = "";
|
16031 | state.lastAssertionIsQuantifiable = false;
|
16032 | state.numCapturingParens = 0;
|
16033 | state.maxBackReference = 0;
|
16034 | state.groupNames.length = 0;
|
16035 | state.backReferenceNames.length = 0;
|
16036 |
|
16037 | this.regexp_disjunction(state);
|
16038 |
|
16039 | if (state.pos !== state.source.length) {
|
16040 |
|
16041 | if (state.eat(0x29 )) {
|
16042 | state.raise("Unmatched ')'");
|
16043 | }
|
16044 | if (state.eat(0x5D ) || state.eat(0x7D )) {
|
16045 | state.raise("Lone quantifier brackets");
|
16046 | }
|
16047 | }
|
16048 | if (state.maxBackReference > state.numCapturingParens) {
|
16049 | state.raise("Invalid escape");
|
16050 | }
|
16051 | for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
|
16052 | var name = list[i];
|
16053 |
|
16054 | if (state.groupNames.indexOf(name) === -1) {
|
16055 | state.raise("Invalid named capture referenced");
|
16056 | }
|
16057 | }
|
16058 | };
|
16059 |
|
16060 |
|
16061 | pp$8.regexp_disjunction = function(state) {
|
16062 | this.regexp_alternative(state);
|
16063 | while (state.eat(0x7C )) {
|
16064 | this.regexp_alternative(state);
|
16065 | }
|
16066 |
|
16067 |
|
16068 | if (this.regexp_eatQuantifier(state, true)) {
|
16069 | state.raise("Nothing to repeat");
|
16070 | }
|
16071 | if (state.eat(0x7B )) {
|
16072 | state.raise("Lone quantifier brackets");
|
16073 | }
|
16074 | };
|
16075 |
|
16076 |
|
16077 | pp$8.regexp_alternative = function(state) {
|
16078 | while (state.pos < state.source.length && this.regexp_eatTerm(state))
|
16079 | { }
|
16080 | };
|
16081 |
|
16082 |
|
16083 | pp$8.regexp_eatTerm = function(state) {
|
16084 | if (this.regexp_eatAssertion(state)) {
|
16085 |
|
16086 |
|
16087 |
|
16088 | if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
|
16089 |
|
16090 | if (state.switchU) {
|
16091 | state.raise("Invalid quantifier");
|
16092 | }
|
16093 | }
|
16094 | return true
|
16095 | }
|
16096 |
|
16097 | if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
|
16098 | this.regexp_eatQuantifier(state);
|
16099 | return true
|
16100 | }
|
16101 |
|
16102 | return false
|
16103 | };
|
16104 |
|
16105 |
|
16106 | pp$8.regexp_eatAssertion = function(state) {
|
16107 | var start = state.pos;
|
16108 | state.lastAssertionIsQuantifiable = false;
|
16109 |
|
16110 |
|
16111 | if (state.eat(0x5E ) || state.eat(0x24 )) {
|
16112 | return true
|
16113 | }
|
16114 |
|
16115 |
|
16116 | if (state.eat(0x5C )) {
|
16117 | if (state.eat(0x42 ) || state.eat(0x62 )) {
|
16118 | return true
|
16119 | }
|
16120 | state.pos = start;
|
16121 | }
|
16122 |
|
16123 |
|
16124 | if (state.eat(0x28 ) && state.eat(0x3F )) {
|
16125 | var lookbehind = false;
|
16126 | if (this.options.ecmaVersion >= 9) {
|
16127 | lookbehind = state.eat(0x3C );
|
16128 | }
|
16129 | if (state.eat(0x3D ) || state.eat(0x21 )) {
|
16130 | this.regexp_disjunction(state);
|
16131 | if (!state.eat(0x29 )) {
|
16132 | state.raise("Unterminated group");
|
16133 | }
|
16134 | state.lastAssertionIsQuantifiable = !lookbehind;
|
16135 | return true
|
16136 | }
|
16137 | }
|
16138 |
|
16139 | state.pos = start;
|
16140 | return false
|
16141 | };
|
16142 |
|
16143 |
|
16144 | pp$8.regexp_eatQuantifier = function(state, noError) {
|
16145 | if ( noError === void 0 ) noError = false;
|
16146 |
|
16147 | if (this.regexp_eatQuantifierPrefix(state, noError)) {
|
16148 | state.eat(0x3F );
|
16149 | return true
|
16150 | }
|
16151 | return false
|
16152 | };
|
16153 |
|
16154 |
|
16155 | pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
|
16156 | return (
|
16157 | state.eat(0x2A ) ||
|
16158 | state.eat(0x2B ) ||
|
16159 | state.eat(0x3F ) ||
|
16160 | this.regexp_eatBracedQuantifier(state, noError)
|
16161 | )
|
16162 | };
|
16163 | pp$8.regexp_eatBracedQuantifier = function(state, noError) {
|
16164 | var start = state.pos;
|
16165 | if (state.eat(0x7B )) {
|
16166 | var min = 0, max = -1;
|
16167 | if (this.regexp_eatDecimalDigits(state)) {
|
16168 | min = state.lastIntValue;
|
16169 | if (state.eat(0x2C ) && this.regexp_eatDecimalDigits(state)) {
|
16170 | max = state.lastIntValue;
|
16171 | }
|
16172 | if (state.eat(0x7D )) {
|
16173 |
|
16174 | if (max !== -1 && max < min && !noError) {
|
16175 | state.raise("numbers out of order in {} quantifier");
|
16176 | }
|
16177 | return true
|
16178 | }
|
16179 | }
|
16180 | if (state.switchU && !noError) {
|
16181 | state.raise("Incomplete quantifier");
|
16182 | }
|
16183 | state.pos = start;
|
16184 | }
|
16185 | return false
|
16186 | };
|
16187 |
|
16188 |
|
16189 | pp$8.regexp_eatAtom = function(state) {
|
16190 | return (
|
16191 | this.regexp_eatPatternCharacters(state) ||
|
16192 | state.eat(0x2E ) ||
|
16193 | this.regexp_eatReverseSolidusAtomEscape(state) ||
|
16194 | this.regexp_eatCharacterClass(state) ||
|
16195 | this.regexp_eatUncapturingGroup(state) ||
|
16196 | this.regexp_eatCapturingGroup(state)
|
16197 | )
|
16198 | };
|
16199 | pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
|
16200 | var start = state.pos;
|
16201 | if (state.eat(0x5C )) {
|
16202 | if (this.regexp_eatAtomEscape(state)) {
|
16203 | return true
|
16204 | }
|
16205 | state.pos = start;
|
16206 | }
|
16207 | return false
|
16208 | };
|
16209 | pp$8.regexp_eatUncapturingGroup = function(state) {
|
16210 | var start = state.pos;
|
16211 | if (state.eat(0x28 )) {
|
16212 | if (state.eat(0x3F ) && state.eat(0x3A )) {
|
16213 | this.regexp_disjunction(state);
|
16214 | if (state.eat(0x29 )) {
|
16215 | return true
|
16216 | }
|
16217 | state.raise("Unterminated group");
|
16218 | }
|
16219 | state.pos = start;
|
16220 | }
|
16221 | return false
|
16222 | };
|
16223 | pp$8.regexp_eatCapturingGroup = function(state) {
|
16224 | if (state.eat(0x28 )) {
|
16225 | if (this.options.ecmaVersion >= 9) {
|
16226 | this.regexp_groupSpecifier(state);
|
16227 | } else if (state.current() === 0x3F ) {
|
16228 | state.raise("Invalid group");
|
16229 | }
|
16230 | this.regexp_disjunction(state);
|
16231 | if (state.eat(0x29 )) {
|
16232 | state.numCapturingParens += 1;
|
16233 | return true
|
16234 | }
|
16235 | state.raise("Unterminated group");
|
16236 | }
|
16237 | return false
|
16238 | };
|
16239 |
|
16240 |
|
16241 | pp$8.regexp_eatExtendedAtom = function(state) {
|
16242 | return (
|
16243 | state.eat(0x2E ) ||
|
16244 | this.regexp_eatReverseSolidusAtomEscape(state) ||
|
16245 | this.regexp_eatCharacterClass(state) ||
|
16246 | this.regexp_eatUncapturingGroup(state) ||
|
16247 | this.regexp_eatCapturingGroup(state) ||
|
16248 | this.regexp_eatInvalidBracedQuantifier(state) ||
|
16249 | this.regexp_eatExtendedPatternCharacter(state)
|
16250 | )
|
16251 | };
|
16252 |
|
16253 |
|
16254 | pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
|
16255 | if (this.regexp_eatBracedQuantifier(state, true)) {
|
16256 | state.raise("Nothing to repeat");
|
16257 | }
|
16258 | return false
|
16259 | };
|
16260 |
|
16261 |
|
16262 | pp$8.regexp_eatSyntaxCharacter = function(state) {
|
16263 | var ch = state.current();
|
16264 | if (isSyntaxCharacter(ch)) {
|
16265 | state.lastIntValue = ch;
|
16266 | state.advance();
|
16267 | return true
|
16268 | }
|
16269 | return false
|
16270 | };
|
16271 | function isSyntaxCharacter(ch) {
|
16272 | return (
|
16273 | ch === 0x24 ||
|
16274 | ch >= 0x28 && ch <= 0x2B ||
|
16275 | ch === 0x2E ||
|
16276 | ch === 0x3F ||
|
16277 | ch >= 0x5B && ch <= 0x5E ||
|
16278 | ch >= 0x7B && ch <= 0x7D
|
16279 | )
|
16280 | }
|
16281 |
|
16282 |
|
16283 |
|
16284 | pp$8.regexp_eatPatternCharacters = function(state) {
|
16285 | var start = state.pos;
|
16286 | var ch = 0;
|
16287 | while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
|
16288 | state.advance();
|
16289 | }
|
16290 | return state.pos !== start
|
16291 | };
|
16292 |
|
16293 |
|
16294 | pp$8.regexp_eatExtendedPatternCharacter = function(state) {
|
16295 | var ch = state.current();
|
16296 | if (
|
16297 | ch !== -1 &&
|
16298 | ch !== 0x24 &&
|
16299 | !(ch >= 0x28 && ch <= 0x2B ) &&
|
16300 | ch !== 0x2E &&
|
16301 | ch !== 0x3F &&
|
16302 | ch !== 0x5B &&
|
16303 | ch !== 0x5E &&
|
16304 | ch !== 0x7C
|
16305 | ) {
|
16306 | state.advance();
|
16307 | return true
|
16308 | }
|
16309 | return false
|
16310 | };
|
16311 |
|
16312 |
|
16313 |
|
16314 |
|
16315 | pp$8.regexp_groupSpecifier = function(state) {
|
16316 | if (state.eat(0x3F )) {
|
16317 | if (this.regexp_eatGroupName(state)) {
|
16318 | if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
|
16319 | state.raise("Duplicate capture group name");
|
16320 | }
|
16321 | state.groupNames.push(state.lastStringValue);
|
16322 | return
|
16323 | }
|
16324 | state.raise("Invalid group");
|
16325 | }
|
16326 | };
|
16327 |
|
16328 |
|
16329 |
|
16330 |
|
16331 | pp$8.regexp_eatGroupName = function(state) {
|
16332 | state.lastStringValue = "";
|
16333 | if (state.eat(0x3C )) {
|
16334 | if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E )) {
|
16335 | return true
|
16336 | }
|
16337 | state.raise("Invalid capture group name");
|
16338 | }
|
16339 | return false
|
16340 | };
|
16341 |
|
16342 |
|
16343 |
|
16344 |
|
16345 |
|
16346 | pp$8.regexp_eatRegExpIdentifierName = function(state) {
|
16347 | state.lastStringValue = "";
|
16348 | if (this.regexp_eatRegExpIdentifierStart(state)) {
|
16349 | state.lastStringValue += codePointToString(state.lastIntValue);
|
16350 | while (this.regexp_eatRegExpIdentifierPart(state)) {
|
16351 | state.lastStringValue += codePointToString(state.lastIntValue);
|
16352 | }
|
16353 | return true
|
16354 | }
|
16355 | return false
|
16356 | };
|
16357 |
|
16358 |
|
16359 |
|
16360 |
|
16361 |
|
16362 |
|
16363 | pp$8.regexp_eatRegExpIdentifierStart = function(state) {
|
16364 | var start = state.pos;
|
16365 | var forceU = this.options.ecmaVersion >= 11;
|
16366 | var ch = state.current(forceU);
|
16367 | state.advance(forceU);
|
16368 |
|
16369 | if (ch === 0x5C && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
|
16370 | ch = state.lastIntValue;
|
16371 | }
|
16372 | if (isRegExpIdentifierStart(ch)) {
|
16373 | state.lastIntValue = ch;
|
16374 | return true
|
16375 | }
|
16376 |
|
16377 | state.pos = start;
|
16378 | return false
|
16379 | };
|
16380 | function isRegExpIdentifierStart(ch) {
|
16381 | return isIdentifierStart(ch, true) || ch === 0x24 || ch === 0x5F
|
16382 | }
|
16383 |
|
16384 |
|
16385 |
|
16386 |
|
16387 |
|
16388 |
|
16389 |
|
16390 |
|
16391 | pp$8.regexp_eatRegExpIdentifierPart = function(state) {
|
16392 | var start = state.pos;
|
16393 | var forceU = this.options.ecmaVersion >= 11;
|
16394 | var ch = state.current(forceU);
|
16395 | state.advance(forceU);
|
16396 |
|
16397 | if (ch === 0x5C && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
|
16398 | ch = state.lastIntValue;
|
16399 | }
|
16400 | if (isRegExpIdentifierPart(ch)) {
|
16401 | state.lastIntValue = ch;
|
16402 | return true
|
16403 | }
|
16404 |
|
16405 | state.pos = start;
|
16406 | return false
|
16407 | };
|
16408 | function isRegExpIdentifierPart(ch) {
|
16409 | return isIdentifierChar(ch, true) || ch === 0x24 || ch === 0x5F || ch === 0x200C || ch === 0x200D
|
16410 | }
|
16411 |
|
16412 |
|
16413 | pp$8.regexp_eatAtomEscape = function(state) {
|
16414 | if (
|
16415 | this.regexp_eatBackReference(state) ||
|
16416 | this.regexp_eatCharacterClassEscape(state) ||
|
16417 | this.regexp_eatCharacterEscape(state) ||
|
16418 | (state.switchN && this.regexp_eatKGroupName(state))
|
16419 | ) {
|
16420 | return true
|
16421 | }
|
16422 | if (state.switchU) {
|
16423 |
|
16424 | if (state.current() === 0x63 ) {
|
16425 | state.raise("Invalid unicode escape");
|
16426 | }
|
16427 | state.raise("Invalid escape");
|
16428 | }
|
16429 | return false
|
16430 | };
|
16431 | pp$8.regexp_eatBackReference = function(state) {
|
16432 | var start = state.pos;
|
16433 | if (this.regexp_eatDecimalEscape(state)) {
|
16434 | var n = state.lastIntValue;
|
16435 | if (state.switchU) {
|
16436 |
|
16437 | if (n > state.maxBackReference) {
|
16438 | state.maxBackReference = n;
|
16439 | }
|
16440 | return true
|
16441 | }
|
16442 | if (n <= state.numCapturingParens) {
|
16443 | return true
|
16444 | }
|
16445 | state.pos = start;
|
16446 | }
|
16447 | return false
|
16448 | };
|
16449 | pp$8.regexp_eatKGroupName = function(state) {
|
16450 | if (state.eat(0x6B )) {
|
16451 | if (this.regexp_eatGroupName(state)) {
|
16452 | state.backReferenceNames.push(state.lastStringValue);
|
16453 | return true
|
16454 | }
|
16455 | state.raise("Invalid named reference");
|
16456 | }
|
16457 | return false
|
16458 | };
|
16459 |
|
16460 |
|
16461 | pp$8.regexp_eatCharacterEscape = function(state) {
|
16462 | return (
|
16463 | this.regexp_eatControlEscape(state) ||
|
16464 | this.regexp_eatCControlLetter(state) ||
|
16465 | this.regexp_eatZero(state) ||
|
16466 | this.regexp_eatHexEscapeSequence(state) ||
|
16467 | this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
|
16468 | (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
|
16469 | this.regexp_eatIdentityEscape(state)
|
16470 | )
|
16471 | };
|
16472 | pp$8.regexp_eatCControlLetter = function(state) {
|
16473 | var start = state.pos;
|
16474 | if (state.eat(0x63 )) {
|
16475 | if (this.regexp_eatControlLetter(state)) {
|
16476 | return true
|
16477 | }
|
16478 | state.pos = start;
|
16479 | }
|
16480 | return false
|
16481 | };
|
16482 | pp$8.regexp_eatZero = function(state) {
|
16483 | if (state.current() === 0x30 && !isDecimalDigit(state.lookahead())) {
|
16484 | state.lastIntValue = 0;
|
16485 | state.advance();
|
16486 | return true
|
16487 | }
|
16488 | return false
|
16489 | };
|
16490 |
|
16491 |
|
16492 | pp$8.regexp_eatControlEscape = function(state) {
|
16493 | var ch = state.current();
|
16494 | if (ch === 0x74 ) {
|
16495 | state.lastIntValue = 0x09;
|
16496 | state.advance();
|
16497 | return true
|
16498 | }
|
16499 | if (ch === 0x6E ) {
|
16500 | state.lastIntValue = 0x0A;
|
16501 | state.advance();
|
16502 | return true
|
16503 | }
|
16504 | if (ch === 0x76 ) {
|
16505 | state.lastIntValue = 0x0B;
|
16506 | state.advance();
|
16507 | return true
|
16508 | }
|
16509 | if (ch === 0x66 ) {
|
16510 | state.lastIntValue = 0x0C;
|
16511 | state.advance();
|
16512 | return true
|
16513 | }
|
16514 | if (ch === 0x72 ) {
|
16515 | state.lastIntValue = 0x0D;
|
16516 | state.advance();
|
16517 | return true
|
16518 | }
|
16519 | return false
|
16520 | };
|
16521 |
|
16522 |
|
16523 | pp$8.regexp_eatControlLetter = function(state) {
|
16524 | var ch = state.current();
|
16525 | if (isControlLetter(ch)) {
|
16526 | state.lastIntValue = ch % 0x20;
|
16527 | state.advance();
|
16528 | return true
|
16529 | }
|
16530 | return false
|
16531 | };
|
16532 | function isControlLetter(ch) {
|
16533 | return (
|
16534 | (ch >= 0x41 && ch <= 0x5A ) ||
|
16535 | (ch >= 0x61 && ch <= 0x7A )
|
16536 | )
|
16537 | }
|
16538 |
|
16539 |
|
16540 | pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
|
16541 | if ( forceU === void 0 ) forceU = false;
|
16542 |
|
16543 | var start = state.pos;
|
16544 | var switchU = forceU || state.switchU;
|
16545 |
|
16546 | if (state.eat(0x75 )) {
|
16547 | if (this.regexp_eatFixedHexDigits(state, 4)) {
|
16548 | var lead = state.lastIntValue;
|
16549 | if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
|
16550 | var leadSurrogateEnd = state.pos;
|
16551 | if (state.eat(0x5C ) && state.eat(0x75 ) && this.regexp_eatFixedHexDigits(state, 4)) {
|
16552 | var trail = state.lastIntValue;
|
16553 | if (trail >= 0xDC00 && trail <= 0xDFFF) {
|
16554 | state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
|
16555 | return true
|
16556 | }
|
16557 | }
|
16558 | state.pos = leadSurrogateEnd;
|
16559 | state.lastIntValue = lead;
|
16560 | }
|
16561 | return true
|
16562 | }
|
16563 | if (
|
16564 | switchU &&
|
16565 | state.eat(0x7B ) &&
|
16566 | this.regexp_eatHexDigits(state) &&
|
16567 | state.eat(0x7D ) &&
|
16568 | isValidUnicode(state.lastIntValue)
|
16569 | ) {
|
16570 | return true
|
16571 | }
|
16572 | if (switchU) {
|
16573 | state.raise("Invalid unicode escape");
|
16574 | }
|
16575 | state.pos = start;
|
16576 | }
|
16577 |
|
16578 | return false
|
16579 | };
|
16580 | function isValidUnicode(ch) {
|
16581 | return ch >= 0 && ch <= 0x10FFFF
|
16582 | }
|
16583 |
|
16584 |
|
16585 | pp$8.regexp_eatIdentityEscape = function(state) {
|
16586 | if (state.switchU) {
|
16587 | if (this.regexp_eatSyntaxCharacter(state)) {
|
16588 | return true
|
16589 | }
|
16590 | if (state.eat(0x2F )) {
|
16591 | state.lastIntValue = 0x2F;
|
16592 | return true
|
16593 | }
|
16594 | return false
|
16595 | }
|
16596 |
|
16597 | var ch = state.current();
|
16598 | if (ch !== 0x63 && (!state.switchN || ch !== 0x6B )) {
|
16599 | state.lastIntValue = ch;
|
16600 | state.advance();
|
16601 | return true
|
16602 | }
|
16603 |
|
16604 | return false
|
16605 | };
|
16606 |
|
16607 |
|
16608 | pp$8.regexp_eatDecimalEscape = function(state) {
|
16609 | state.lastIntValue = 0;
|
16610 | var ch = state.current();
|
16611 | if (ch >= 0x31 && ch <= 0x39 ) {
|
16612 | do {
|
16613 | state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 );
|
16614 | state.advance();
|
16615 | } while ((ch = state.current()) >= 0x30 && ch <= 0x39 )
|
16616 | return true
|
16617 | }
|
16618 | return false
|
16619 | };
|
16620 |
|
16621 |
|
16622 | pp$8.regexp_eatCharacterClassEscape = function(state) {
|
16623 | var ch = state.current();
|
16624 |
|
16625 | if (isCharacterClassEscape(ch)) {
|
16626 | state.lastIntValue = -1;
|
16627 | state.advance();
|
16628 | return true
|
16629 | }
|
16630 |
|
16631 | if (
|
16632 | state.switchU &&
|
16633 | this.options.ecmaVersion >= 9 &&
|
16634 | (ch === 0x50 || ch === 0x70 )
|
16635 | ) {
|
16636 | state.lastIntValue = -1;
|
16637 | state.advance();
|
16638 | if (
|
16639 | state.eat(0x7B ) &&
|
16640 | this.regexp_eatUnicodePropertyValueExpression(state) &&
|
16641 | state.eat(0x7D )
|
16642 | ) {
|
16643 | return true
|
16644 | }
|
16645 | state.raise("Invalid property name");
|
16646 | }
|
16647 |
|
16648 | return false
|
16649 | };
|
16650 | function isCharacterClassEscape(ch) {
|
16651 | return (
|
16652 | ch === 0x64 ||
|
16653 | ch === 0x44 ||
|
16654 | ch === 0x73 ||
|
16655 | ch === 0x53 ||
|
16656 | ch === 0x77 ||
|
16657 | ch === 0x57
|
16658 | )
|
16659 | }
|
16660 |
|
16661 |
|
16662 |
|
16663 |
|
16664 | pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
|
16665 | var start = state.pos;
|
16666 |
|
16667 |
|
16668 | if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D )) {
|
16669 | var name = state.lastStringValue;
|
16670 | if (this.regexp_eatUnicodePropertyValue(state)) {
|
16671 | var value = state.lastStringValue;
|
16672 | this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
|
16673 | return true
|
16674 | }
|
16675 | }
|
16676 | state.pos = start;
|
16677 |
|
16678 |
|
16679 | if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
|
16680 | var nameOrValue = state.lastStringValue;
|
16681 | this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
|
16682 | return true
|
16683 | }
|
16684 | return false
|
16685 | };
|
16686 | pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
|
16687 | if (!has(state.unicodeProperties.nonBinary, name))
|
16688 | { state.raise("Invalid property name"); }
|
16689 | if (!state.unicodeProperties.nonBinary[name].test(value))
|
16690 | { state.raise("Invalid property value"); }
|
16691 | };
|
16692 | pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
|
16693 | if (!state.unicodeProperties.binary.test(nameOrValue))
|
16694 | { state.raise("Invalid property name"); }
|
16695 | };
|
16696 |
|
16697 |
|
16698 |
|
16699 | pp$8.regexp_eatUnicodePropertyName = function(state) {
|
16700 | var ch = 0;
|
16701 | state.lastStringValue = "";
|
16702 | while (isUnicodePropertyNameCharacter(ch = state.current())) {
|
16703 | state.lastStringValue += codePointToString(ch);
|
16704 | state.advance();
|
16705 | }
|
16706 | return state.lastStringValue !== ""
|
16707 | };
|
16708 | function isUnicodePropertyNameCharacter(ch) {
|
16709 | return isControlLetter(ch) || ch === 0x5F
|
16710 | }
|
16711 |
|
16712 |
|
16713 |
|
16714 | pp$8.regexp_eatUnicodePropertyValue = function(state) {
|
16715 | var ch = 0;
|
16716 | state.lastStringValue = "";
|
16717 | while (isUnicodePropertyValueCharacter(ch = state.current())) {
|
16718 | state.lastStringValue += codePointToString(ch);
|
16719 | state.advance();
|
16720 | }
|
16721 | return state.lastStringValue !== ""
|
16722 | };
|
16723 | function isUnicodePropertyValueCharacter(ch) {
|
16724 | return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
|
16725 | }
|
16726 |
|
16727 |
|
16728 |
|
16729 | pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
|
16730 | return this.regexp_eatUnicodePropertyValue(state)
|
16731 | };
|
16732 |
|
16733 |
|
16734 | pp$8.regexp_eatCharacterClass = function(state) {
|
16735 | if (state.eat(0x5B )) {
|
16736 | state.eat(0x5E );
|
16737 | this.regexp_classRanges(state);
|
16738 | if (state.eat(0x5D )) {
|
16739 | return true
|
16740 | }
|
16741 |
|
16742 | state.raise("Unterminated character class");
|
16743 | }
|
16744 | return false
|
16745 | };
|
16746 |
|
16747 |
|
16748 |
|
16749 |
|
16750 | pp$8.regexp_classRanges = function(state) {
|
16751 | while (this.regexp_eatClassAtom(state)) {
|
16752 | var left = state.lastIntValue;
|
16753 | if (state.eat(0x2D ) && this.regexp_eatClassAtom(state)) {
|
16754 | var right = state.lastIntValue;
|
16755 | if (state.switchU && (left === -1 || right === -1)) {
|
16756 | state.raise("Invalid character class");
|
16757 | }
|
16758 | if (left !== -1 && right !== -1 && left > right) {
|
16759 | state.raise("Range out of order in character class");
|
16760 | }
|
16761 | }
|
16762 | }
|
16763 | };
|
16764 |
|
16765 |
|
16766 |
|
16767 | pp$8.regexp_eatClassAtom = function(state) {
|
16768 | var start = state.pos;
|
16769 |
|
16770 | if (state.eat(0x5C )) {
|
16771 | if (this.regexp_eatClassEscape(state)) {
|
16772 | return true
|
16773 | }
|
16774 | if (state.switchU) {
|
16775 |
|
16776 | var ch$1 = state.current();
|
16777 | if (ch$1 === 0x63 || isOctalDigit(ch$1)) {
|
16778 | state.raise("Invalid class escape");
|
16779 | }
|
16780 | state.raise("Invalid escape");
|
16781 | }
|
16782 | state.pos = start;
|
16783 | }
|
16784 |
|
16785 | var ch = state.current();
|
16786 | if (ch !== 0x5D ) {
|
16787 | state.lastIntValue = ch;
|
16788 | state.advance();
|
16789 | return true
|
16790 | }
|
16791 |
|
16792 | return false
|
16793 | };
|
16794 |
|
16795 |
|
16796 | pp$8.regexp_eatClassEscape = function(state) {
|
16797 | var start = state.pos;
|
16798 |
|
16799 | if (state.eat(0x62 )) {
|
16800 | state.lastIntValue = 0x08;
|
16801 | return true
|
16802 | }
|
16803 |
|
16804 | if (state.switchU && state.eat(0x2D )) {
|
16805 | state.lastIntValue = 0x2D;
|
16806 | return true
|
16807 | }
|
16808 |
|
16809 | if (!state.switchU && state.eat(0x63 )) {
|
16810 | if (this.regexp_eatClassControlLetter(state)) {
|
16811 | return true
|
16812 | }
|
16813 | state.pos = start;
|
16814 | }
|
16815 |
|
16816 | return (
|
16817 | this.regexp_eatCharacterClassEscape(state) ||
|
16818 | this.regexp_eatCharacterEscape(state)
|
16819 | )
|
16820 | };
|
16821 |
|
16822 |
|
16823 | pp$8.regexp_eatClassControlLetter = function(state) {
|
16824 | var ch = state.current();
|
16825 | if (isDecimalDigit(ch) || ch === 0x5F ) {
|
16826 | state.lastIntValue = ch % 0x20;
|
16827 | state.advance();
|
16828 | return true
|
16829 | }
|
16830 | return false
|
16831 | };
|
16832 |
|
16833 |
|
16834 | pp$8.regexp_eatHexEscapeSequence = function(state) {
|
16835 | var start = state.pos;
|
16836 | if (state.eat(0x78 )) {
|
16837 | if (this.regexp_eatFixedHexDigits(state, 2)) {
|
16838 | return true
|
16839 | }
|
16840 | if (state.switchU) {
|
16841 | state.raise("Invalid escape");
|
16842 | }
|
16843 | state.pos = start;
|
16844 | }
|
16845 | return false
|
16846 | };
|
16847 |
|
16848 |
|
16849 | pp$8.regexp_eatDecimalDigits = function(state) {
|
16850 | var start = state.pos;
|
16851 | var ch = 0;
|
16852 | state.lastIntValue = 0;
|
16853 | while (isDecimalDigit(ch = state.current())) {
|
16854 | state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 );
|
16855 | state.advance();
|
16856 | }
|
16857 | return state.pos !== start
|
16858 | };
|
16859 | function isDecimalDigit(ch) {
|
16860 | return ch >= 0x30 && ch <= 0x39
|
16861 | }
|
16862 |
|
16863 |
|
16864 | pp$8.regexp_eatHexDigits = function(state) {
|
16865 | var start = state.pos;
|
16866 | var ch = 0;
|
16867 | state.lastIntValue = 0;
|
16868 | while (isHexDigit(ch = state.current())) {
|
16869 | state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
|
16870 | state.advance();
|
16871 | }
|
16872 | return state.pos !== start
|
16873 | };
|
16874 | function isHexDigit(ch) {
|
16875 | return (
|
16876 | (ch >= 0x30 && ch <= 0x39 ) ||
|
16877 | (ch >= 0x41 && ch <= 0x46 ) ||
|
16878 | (ch >= 0x61 && ch <= 0x66 )
|
16879 | )
|
16880 | }
|
16881 | function hexToInt(ch) {
|
16882 | if (ch >= 0x41 && ch <= 0x46 ) {
|
16883 | return 10 + (ch - 0x41 )
|
16884 | }
|
16885 | if (ch >= 0x61 && ch <= 0x66 ) {
|
16886 | return 10 + (ch - 0x61 )
|
16887 | }
|
16888 | return ch - 0x30
|
16889 | }
|
16890 |
|
16891 |
|
16892 |
|
16893 | pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
|
16894 | if (this.regexp_eatOctalDigit(state)) {
|
16895 | var n1 = state.lastIntValue;
|
16896 | if (this.regexp_eatOctalDigit(state)) {
|
16897 | var n2 = state.lastIntValue;
|
16898 | if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
|
16899 | state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
|
16900 | } else {
|
16901 | state.lastIntValue = n1 * 8 + n2;
|
16902 | }
|
16903 | } else {
|
16904 | state.lastIntValue = n1;
|
16905 | }
|
16906 | return true
|
16907 | }
|
16908 | return false
|
16909 | };
|
16910 |
|
16911 |
|
16912 | pp$8.regexp_eatOctalDigit = function(state) {
|
16913 | var ch = state.current();
|
16914 | if (isOctalDigit(ch)) {
|
16915 | state.lastIntValue = ch - 0x30;
|
16916 | state.advance();
|
16917 | return true
|
16918 | }
|
16919 | state.lastIntValue = 0;
|
16920 | return false
|
16921 | };
|
16922 | function isOctalDigit(ch) {
|
16923 | return ch >= 0x30 && ch <= 0x37
|
16924 | }
|
16925 |
|
16926 |
|
16927 |
|
16928 |
|
16929 | pp$8.regexp_eatFixedHexDigits = function(state, length) {
|
16930 | var start = state.pos;
|
16931 | state.lastIntValue = 0;
|
16932 | for (var i = 0; i < length; ++i) {
|
16933 | var ch = state.current();
|
16934 | if (!isHexDigit(ch)) {
|
16935 | state.pos = start;
|
16936 | return false
|
16937 | }
|
16938 | state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
|
16939 | state.advance();
|
16940 | }
|
16941 | return true
|
16942 | };
|
16943 |
|
16944 |
|
16945 |
|
16946 |
|
16947 |
|
16948 | var Token = function Token(p) {
|
16949 | this.type = p.type;
|
16950 | this.value = p.value;
|
16951 | this.start = p.start;
|
16952 | this.end = p.end;
|
16953 | if (p.options.locations)
|
16954 | { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
|
16955 | if (p.options.ranges)
|
16956 | { this.range = [p.start, p.end]; }
|
16957 | };
|
16958 |
|
16959 |
|
16960 |
|
16961 | var pp$9 = Parser.prototype;
|
16962 |
|
16963 |
|
16964 |
|
16965 | pp$9.next = function(ignoreEscapeSequenceInKeyword) {
|
16966 | if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
|
16967 | { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
|
16968 | if (this.options.onToken)
|
16969 | { this.options.onToken(new Token(this)); }
|
16970 |
|
16971 | this.lastTokEnd = this.end;
|
16972 | this.lastTokStart = this.start;
|
16973 | this.lastTokEndLoc = this.endLoc;
|
16974 | this.lastTokStartLoc = this.startLoc;
|
16975 | this.nextToken();
|
16976 | };
|
16977 |
|
16978 | pp$9.getToken = function() {
|
16979 | this.next();
|
16980 | return new Token(this)
|
16981 | };
|
16982 |
|
16983 |
|
16984 | if (typeof Symbol !== "undefined")
|
16985 | { pp$9[Symbol.iterator] = function() {
|
16986 | var this$1 = this;
|
16987 |
|
16988 | return {
|
16989 | next: function () {
|
16990 | var token = this$1.getToken();
|
16991 | return {
|
16992 | done: token.type === types.eof,
|
16993 | value: token
|
16994 | }
|
16995 | }
|
16996 | }
|
16997 | }; }
|
16998 |
|
16999 |
|
17000 |
|
17001 |
|
17002 | pp$9.curContext = function() {
|
17003 | return this.context[this.context.length - 1]
|
17004 | };
|
17005 |
|
17006 |
|
17007 |
|
17008 |
|
17009 | pp$9.nextToken = function() {
|
17010 | var curContext = this.curContext();
|
17011 | if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
|
17012 |
|
17013 | this.start = this.pos;
|
17014 | if (this.options.locations) { this.startLoc = this.curPosition(); }
|
17015 | if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
|
17016 |
|
17017 | if (curContext.override) { return curContext.override(this) }
|
17018 | else { this.readToken(this.fullCharCodeAtPos()); }
|
17019 | };
|
17020 |
|
17021 | pp$9.readToken = function(code) {
|
17022 |
|
17023 |
|
17024 | if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 )
|
17025 | { return this.readWord() }
|
17026 |
|
17027 | return this.getTokenFromCode(code)
|
17028 | };
|
17029 |
|
17030 | pp$9.fullCharCodeAtPos = function() {
|
17031 | var code = this.input.charCodeAt(this.pos);
|
17032 | if (code <= 0xd7ff || code >= 0xe000) { return code }
|
17033 | var next = this.input.charCodeAt(this.pos + 1);
|
17034 | return (code << 10) + next - 0x35fdc00
|
17035 | };
|
17036 |
|
17037 | pp$9.skipBlockComment = function() {
|
17038 | var startLoc = this.options.onComment && this.curPosition();
|
17039 | var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
|
17040 | if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
|
17041 | this.pos = end + 2;
|
17042 | if (this.options.locations) {
|
17043 | lineBreakG.lastIndex = start;
|
17044 | var match;
|
17045 | while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
|
17046 | ++this.curLine;
|
17047 | this.lineStart = match.index + match[0].length;
|
17048 | }
|
17049 | }
|
17050 | if (this.options.onComment)
|
17051 | { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
|
17052 | startLoc, this.curPosition()); }
|
17053 | };
|
17054 |
|
17055 | pp$9.skipLineComment = function(startSkip) {
|
17056 | var start = this.pos;
|
17057 | var startLoc = this.options.onComment && this.curPosition();
|
17058 | var ch = this.input.charCodeAt(this.pos += startSkip);
|
17059 | while (this.pos < this.input.length && !isNewLine(ch)) {
|
17060 | ch = this.input.charCodeAt(++this.pos);
|
17061 | }
|
17062 | if (this.options.onComment)
|
17063 | { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
|
17064 | startLoc, this.curPosition()); }
|
17065 | };
|
17066 |
|
17067 |
|
17068 |
|
17069 |
|
17070 | pp$9.skipSpace = function() {
|
17071 | loop: while (this.pos < this.input.length) {
|
17072 | var ch = this.input.charCodeAt(this.pos);
|
17073 | switch (ch) {
|
17074 | case 32: case 160:
|
17075 | ++this.pos;
|
17076 | break
|
17077 | case 13:
|
17078 | if (this.input.charCodeAt(this.pos + 1) === 10) {
|
17079 | ++this.pos;
|
17080 | }
|
17081 | case 10: case 8232: case 8233:
|
17082 | ++this.pos;
|
17083 | if (this.options.locations) {
|
17084 | ++this.curLine;
|
17085 | this.lineStart = this.pos;
|
17086 | }
|
17087 | break
|
17088 | case 47:
|
17089 | switch (this.input.charCodeAt(this.pos + 1)) {
|
17090 | case 42:
|
17091 | this.skipBlockComment();
|
17092 | break
|
17093 | case 47:
|
17094 | this.skipLineComment(2);
|
17095 | break
|
17096 | default:
|
17097 | break loop
|
17098 | }
|
17099 | break
|
17100 | default:
|
17101 | if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
|
17102 | ++this.pos;
|
17103 | } else {
|
17104 | break loop
|
17105 | }
|
17106 | }
|
17107 | }
|
17108 | };
|
17109 |
|
17110 |
|
17111 |
|
17112 |
|
17113 |
|
17114 |
|
17115 | pp$9.finishToken = function(type, val) {
|
17116 | this.end = this.pos;
|
17117 | if (this.options.locations) { this.endLoc = this.curPosition(); }
|
17118 | var prevType = this.type;
|
17119 | this.type = type;
|
17120 | this.value = val;
|
17121 |
|
17122 | this.updateContext(prevType);
|
17123 | };
|
17124 |
|
17125 |
|
17126 |
|
17127 |
|
17128 |
|
17129 |
|
17130 |
|
17131 |
|
17132 |
|
17133 |
|
17134 | pp$9.readToken_dot = function() {
|
17135 | var next = this.input.charCodeAt(this.pos + 1);
|
17136 | if (next >= 48 && next <= 57) { return this.readNumber(true) }
|
17137 | var next2 = this.input.charCodeAt(this.pos + 2);
|
17138 | if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
|
17139 | this.pos += 3;
|
17140 | return this.finishToken(types.ellipsis)
|
17141 | } else {
|
17142 | ++this.pos;
|
17143 | return this.finishToken(types.dot)
|
17144 | }
|
17145 | };
|
17146 |
|
17147 | pp$9.readToken_slash = function() {
|
17148 | var next = this.input.charCodeAt(this.pos + 1);
|
17149 | if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
|
17150 | if (next === 61) { return this.finishOp(types.assign, 2) }
|
17151 | return this.finishOp(types.slash, 1)
|
17152 | };
|
17153 |
|
17154 | pp$9.readToken_mult_modulo_exp = function(code) {
|
17155 | var next = this.input.charCodeAt(this.pos + 1);
|
17156 | var size = 1;
|
17157 | var tokentype = code === 42 ? types.star : types.modulo;
|
17158 |
|
17159 |
|
17160 | if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
|
17161 | ++size;
|
17162 | tokentype = types.starstar;
|
17163 | next = this.input.charCodeAt(this.pos + 2);
|
17164 | }
|
17165 |
|
17166 | if (next === 61) { return this.finishOp(types.assign, size + 1) }
|
17167 | return this.finishOp(tokentype, size)
|
17168 | };
|
17169 |
|
17170 | pp$9.readToken_pipe_amp = function(code) {
|
17171 | var next = this.input.charCodeAt(this.pos + 1);
|
17172 | if (next === code) {
|
17173 | if (this.options.ecmaVersion >= 12) {
|
17174 | var next2 = this.input.charCodeAt(this.pos + 2);
|
17175 | if (next2 === 61) { return this.finishOp(types.assign, 3) }
|
17176 | }
|
17177 | return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
|
17178 | }
|
17179 | if (next === 61) { return this.finishOp(types.assign, 2) }
|
17180 | return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
|
17181 | };
|
17182 |
|
17183 | pp$9.readToken_caret = function() {
|
17184 | var next = this.input.charCodeAt(this.pos + 1);
|
17185 | if (next === 61) { return this.finishOp(types.assign, 2) }
|
17186 | return this.finishOp(types.bitwiseXOR, 1)
|
17187 | };
|
17188 |
|
17189 | pp$9.readToken_plus_min = function(code) {
|
17190 | var next = this.input.charCodeAt(this.pos + 1);
|
17191 | if (next === code) {
|
17192 | if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
|
17193 | (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
|
17194 |
|
17195 | this.skipLineComment(3);
|
17196 | this.skipSpace();
|
17197 | return this.nextToken()
|
17198 | }
|
17199 | return this.finishOp(types.incDec, 2)
|
17200 | }
|
17201 | if (next === 61) { return this.finishOp(types.assign, 2) }
|
17202 | return this.finishOp(types.plusMin, 1)
|
17203 | };
|
17204 |
|
17205 | pp$9.readToken_lt_gt = function(code) {
|
17206 | var next = this.input.charCodeAt(this.pos + 1);
|
17207 | var size = 1;
|
17208 | if (next === code) {
|
17209 | size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
|
17210 | if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
|
17211 | return this.finishOp(types.bitShift, size)
|
17212 | }
|
17213 | if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
|
17214 | this.input.charCodeAt(this.pos + 3) === 45) {
|
17215 |
|
17216 | this.skipLineComment(4);
|
17217 | this.skipSpace();
|
17218 | return this.nextToken()
|
17219 | }
|
17220 | if (next === 61) { size = 2; }
|
17221 | return this.finishOp(types.relational, size)
|
17222 | };
|
17223 |
|
17224 | pp$9.readToken_eq_excl = function(code) {
|
17225 | var next = this.input.charCodeAt(this.pos + 1);
|
17226 | if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
|
17227 | if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
|
17228 | this.pos += 2;
|
17229 | return this.finishToken(types.arrow)
|
17230 | }
|
17231 | return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
|
17232 | };
|
17233 |
|
17234 | pp$9.readToken_question = function() {
|
17235 | var ecmaVersion = this.options.ecmaVersion;
|
17236 | if (ecmaVersion >= 11) {
|
17237 | var next = this.input.charCodeAt(this.pos + 1);
|
17238 | if (next === 46) {
|
17239 | var next2 = this.input.charCodeAt(this.pos + 2);
|
17240 | if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
|
17241 | }
|
17242 | if (next === 63) {
|
17243 | if (ecmaVersion >= 12) {
|
17244 | var next2$1 = this.input.charCodeAt(this.pos + 2);
|
17245 | if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
|
17246 | }
|
17247 | return this.finishOp(types.coalesce, 2)
|
17248 | }
|
17249 | }
|
17250 | return this.finishOp(types.question, 1)
|
17251 | };
|
17252 |
|
17253 | pp$9.getTokenFromCode = function(code) {
|
17254 | switch (code) {
|
17255 |
|
17256 |
|
17257 | case 46:
|
17258 | return this.readToken_dot()
|
17259 |
|
17260 |
|
17261 | case 40: ++this.pos; return this.finishToken(types.parenL)
|
17262 | case 41: ++this.pos; return this.finishToken(types.parenR)
|
17263 | case 59: ++this.pos; return this.finishToken(types.semi)
|
17264 | case 44: ++this.pos; return this.finishToken(types.comma)
|
17265 | case 91: ++this.pos; return this.finishToken(types.bracketL)
|
17266 | case 93: ++this.pos; return this.finishToken(types.bracketR)
|
17267 | case 123: ++this.pos; return this.finishToken(types.braceL)
|
17268 | case 125: ++this.pos; return this.finishToken(types.braceR)
|
17269 | case 58: ++this.pos; return this.finishToken(types.colon)
|
17270 |
|
17271 | case 96:
|
17272 | if (this.options.ecmaVersion < 6) { break }
|
17273 | ++this.pos;
|
17274 | return this.finishToken(types.backQuote)
|
17275 |
|
17276 | case 48:
|
17277 | var next = this.input.charCodeAt(this.pos + 1);
|
17278 | if (next === 120 || next === 88) { return this.readRadixNumber(16) }
|
17279 | if (this.options.ecmaVersion >= 6) {
|
17280 | if (next === 111 || next === 79) { return this.readRadixNumber(8) }
|
17281 | if (next === 98 || next === 66) { return this.readRadixNumber(2) }
|
17282 | }
|
17283 |
|
17284 |
|
17285 |
|
17286 | case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57:
|
17287 | return this.readNumber(false)
|
17288 |
|
17289 |
|
17290 | case 34: case 39:
|
17291 | return this.readString(code)
|
17292 |
|
17293 |
|
17294 |
|
17295 |
|
17296 |
|
17297 |
|
17298 | case 47:
|
17299 | return this.readToken_slash()
|
17300 |
|
17301 | case 37: case 42:
|
17302 | return this.readToken_mult_modulo_exp(code)
|
17303 |
|
17304 | case 124: case 38:
|
17305 | return this.readToken_pipe_amp(code)
|
17306 |
|
17307 | case 94:
|
17308 | return this.readToken_caret()
|
17309 |
|
17310 | case 43: case 45:
|
17311 | return this.readToken_plus_min(code)
|
17312 |
|
17313 | case 60: case 62:
|
17314 | return this.readToken_lt_gt(code)
|
17315 |
|
17316 | case 61: case 33:
|
17317 | return this.readToken_eq_excl(code)
|
17318 |
|
17319 | case 63:
|
17320 | return this.readToken_question()
|
17321 |
|
17322 | case 126:
|
17323 | return this.finishOp(types.prefix, 1)
|
17324 | }
|
17325 |
|
17326 | this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
|
17327 | };
|
17328 |
|
17329 | pp$9.finishOp = function(type, size) {
|
17330 | var str = this.input.slice(this.pos, this.pos + size);
|
17331 | this.pos += size;
|
17332 | return this.finishToken(type, str)
|
17333 | };
|
17334 |
|
17335 | pp$9.readRegexp = function() {
|
17336 | var escaped, inClass, start = this.pos;
|
17337 | for (;;) {
|
17338 | if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
|
17339 | var ch = this.input.charAt(this.pos);
|
17340 | if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
|
17341 | if (!escaped) {
|
17342 | if (ch === "[") { inClass = true; }
|
17343 | else if (ch === "]" && inClass) { inClass = false; }
|
17344 | else if (ch === "/" && !inClass) { break }
|
17345 | escaped = ch === "\\";
|
17346 | } else { escaped = false; }
|
17347 | ++this.pos;
|
17348 | }
|
17349 | var pattern = this.input.slice(start, this.pos);
|
17350 | ++this.pos;
|
17351 | var flagsStart = this.pos;
|
17352 | var flags = this.readWord1();
|
17353 | if (this.containsEsc) { this.unexpected(flagsStart); }
|
17354 |
|
17355 |
|
17356 | var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
|
17357 | state.reset(start, pattern, flags);
|
17358 | this.validateRegExpFlags(state);
|
17359 | this.validateRegExpPattern(state);
|
17360 |
|
17361 |
|
17362 | var value = null;
|
17363 | try {
|
17364 | value = new RegExp(pattern, flags);
|
17365 | } catch (e) {
|
17366 |
|
17367 |
|
17368 | }
|
17369 |
|
17370 | return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
|
17371 | };
|
17372 |
|
17373 |
|
17374 |
|
17375 |
|
17376 |
|
17377 | pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
|
17378 |
|
17379 | var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
|
17380 |
|
17381 |
|
17382 |
|
17383 |
|
17384 | var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
|
17385 |
|
17386 | var start = this.pos, total = 0, lastCode = 0;
|
17387 | for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
|
17388 | var code = this.input.charCodeAt(this.pos), val = (void 0);
|
17389 |
|
17390 | if (allowSeparators && code === 95) {
|
17391 | if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
|
17392 | if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
|
17393 | if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
|
17394 | lastCode = code;
|
17395 | continue
|
17396 | }
|
17397 |
|
17398 | if (code >= 97) { val = code - 97 + 10; }
|
17399 | else if (code >= 65) { val = code - 65 + 10; }
|
17400 | else if (code >= 48 && code <= 57) { val = code - 48; }
|
17401 | else { val = Infinity; }
|
17402 | if (val >= radix) { break }
|
17403 | lastCode = code;
|
17404 | total = total * radix + val;
|
17405 | }
|
17406 |
|
17407 | if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
|
17408 | if (this.pos === start || len != null && this.pos - start !== len) { return null }
|
17409 |
|
17410 | return total
|
17411 | };
|
17412 |
|
17413 | function stringToNumber(str, isLegacyOctalNumericLiteral) {
|
17414 | if (isLegacyOctalNumericLiteral) {
|
17415 | return parseInt(str, 8)
|
17416 | }
|
17417 |
|
17418 |
|
17419 | return parseFloat(str.replace(/_/g, ""))
|
17420 | }
|
17421 |
|
17422 | function stringToBigInt(str) {
|
17423 | if (typeof BigInt !== "function") {
|
17424 | return null
|
17425 | }
|
17426 |
|
17427 |
|
17428 | return BigInt(str.replace(/_/g, ""))
|
17429 | }
|
17430 |
|
17431 | pp$9.readRadixNumber = function(radix) {
|
17432 | var start = this.pos;
|
17433 | this.pos += 2;
|
17434 | var val = this.readInt(radix);
|
17435 | if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
|
17436 | if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
|
17437 | val = stringToBigInt(this.input.slice(start, this.pos));
|
17438 | ++this.pos;
|
17439 | } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
|
17440 | return this.finishToken(types.num, val)
|
17441 | };
|
17442 |
|
17443 |
|
17444 |
|
17445 | pp$9.readNumber = function(startsWithDot) {
|
17446 | var start = this.pos;
|
17447 | if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
|
17448 | var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
|
17449 | if (octal && this.strict) { this.raise(start, "Invalid number"); }
|
17450 | var next = this.input.charCodeAt(this.pos);
|
17451 | if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
|
17452 | var val$1 = stringToBigInt(this.input.slice(start, this.pos));
|
17453 | ++this.pos;
|
17454 | if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
|
17455 | return this.finishToken(types.num, val$1)
|
17456 | }
|
17457 | if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
|
17458 | if (next === 46 && !octal) {
|
17459 | ++this.pos;
|
17460 | this.readInt(10);
|
17461 | next = this.input.charCodeAt(this.pos);
|
17462 | }
|
17463 | if ((next === 69 || next === 101) && !octal) {
|
17464 | next = this.input.charCodeAt(++this.pos);
|
17465 | if (next === 43 || next === 45) { ++this.pos; }
|
17466 | if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
|
17467 | }
|
17468 | if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
|
17469 |
|
17470 | var val = stringToNumber(this.input.slice(start, this.pos), octal);
|
17471 | return this.finishToken(types.num, val)
|
17472 | };
|
17473 |
|
17474 |
|
17475 |
|
17476 | pp$9.readCodePoint = function() {
|
17477 | var ch = this.input.charCodeAt(this.pos), code;
|
17478 |
|
17479 | if (ch === 123) {
|
17480 | if (this.options.ecmaVersion < 6) { this.unexpected(); }
|
17481 | var codePos = ++this.pos;
|
17482 | code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
|
17483 | ++this.pos;
|
17484 | if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
|
17485 | } else {
|
17486 | code = this.readHexChar(4);
|
17487 | }
|
17488 | return code
|
17489 | };
|
17490 |
|
17491 | function codePointToString$1(code) {
|
17492 |
|
17493 | if (code <= 0xFFFF) { return String.fromCharCode(code) }
|
17494 | code -= 0x10000;
|
17495 | return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
|
17496 | }
|
17497 |
|
17498 | pp$9.readString = function(quote) {
|
17499 | var out = "", chunkStart = ++this.pos;
|
17500 | for (;;) {
|
17501 | if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
|
17502 | var ch = this.input.charCodeAt(this.pos);
|
17503 | if (ch === quote) { break }
|
17504 | if (ch === 92) {
|
17505 | out += this.input.slice(chunkStart, this.pos);
|
17506 | out += this.readEscapedChar(false);
|
17507 | chunkStart = this.pos;
|
17508 | } else {
|
17509 | if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
|
17510 | ++this.pos;
|
17511 | }
|
17512 | }
|
17513 | out += this.input.slice(chunkStart, this.pos++);
|
17514 | return this.finishToken(types.string, out)
|
17515 | };
|
17516 |
|
17517 |
|
17518 |
|
17519 | var INVALID_TEMPLATE_ESCAPE_ERROR = {};
|
17520 |
|
17521 | pp$9.tryReadTemplateToken = function() {
|
17522 | this.inTemplateElement = true;
|
17523 | try {
|
17524 | this.readTmplToken();
|
17525 | } catch (err) {
|
17526 | if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
|
17527 | this.readInvalidTemplateToken();
|
17528 | } else {
|
17529 | throw err
|
17530 | }
|
17531 | }
|
17532 |
|
17533 | this.inTemplateElement = false;
|
17534 | };
|
17535 |
|
17536 | pp$9.invalidStringToken = function(position, message) {
|
17537 | if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
|
17538 | throw INVALID_TEMPLATE_ESCAPE_ERROR
|
17539 | } else {
|
17540 | this.raise(position, message);
|
17541 | }
|
17542 | };
|
17543 |
|
17544 | pp$9.readTmplToken = function() {
|
17545 | var out = "", chunkStart = this.pos;
|
17546 | for (;;) {
|
17547 | if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
|
17548 | var ch = this.input.charCodeAt(this.pos);
|
17549 | if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
|
17550 | if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
|
17551 | if (ch === 36) {
|
17552 | this.pos += 2;
|
17553 | return this.finishToken(types.dollarBraceL)
|
17554 | } else {
|
17555 | ++this.pos;
|
17556 | return this.finishToken(types.backQuote)
|
17557 | }
|
17558 | }
|
17559 | out += this.input.slice(chunkStart, this.pos);
|
17560 | return this.finishToken(types.template, out)
|
17561 | }
|
17562 | if (ch === 92) {
|
17563 | out += this.input.slice(chunkStart, this.pos);
|
17564 | out += this.readEscapedChar(true);
|
17565 | chunkStart = this.pos;
|
17566 | } else if (isNewLine(ch)) {
|
17567 | out += this.input.slice(chunkStart, this.pos);
|
17568 | ++this.pos;
|
17569 | switch (ch) {
|
17570 | case 13:
|
17571 | if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
|
17572 | case 10:
|
17573 | out += "\n";
|
17574 | break
|
17575 | default:
|
17576 | out += String.fromCharCode(ch);
|
17577 | break
|
17578 | }
|
17579 | if (this.options.locations) {
|
17580 | ++this.curLine;
|
17581 | this.lineStart = this.pos;
|
17582 | }
|
17583 | chunkStart = this.pos;
|
17584 | } else {
|
17585 | ++this.pos;
|
17586 | }
|
17587 | }
|
17588 | };
|
17589 |
|
17590 |
|
17591 | pp$9.readInvalidTemplateToken = function() {
|
17592 | for (; this.pos < this.input.length; this.pos++) {
|
17593 | switch (this.input[this.pos]) {
|
17594 | case "\\":
|
17595 | ++this.pos;
|
17596 | break
|
17597 |
|
17598 | case "$":
|
17599 | if (this.input[this.pos + 1] !== "{") {
|
17600 | break
|
17601 | }
|
17602 |
|
17603 |
|
17604 | case "`":
|
17605 | return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
|
17606 |
|
17607 |
|
17608 | }
|
17609 | }
|
17610 | this.raise(this.start, "Unterminated template");
|
17611 | };
|
17612 |
|
17613 |
|
17614 |
|
17615 | pp$9.readEscapedChar = function(inTemplate) {
|
17616 | var ch = this.input.charCodeAt(++this.pos);
|
17617 | ++this.pos;
|
17618 | switch (ch) {
|
17619 | case 110: return "\n"
|
17620 | case 114: return "\r"
|
17621 | case 120: return String.fromCharCode(this.readHexChar(2))
|
17622 | case 117: return codePointToString$1(this.readCodePoint())
|
17623 | case 116: return "\t"
|
17624 | case 98: return "\b"
|
17625 | case 118: return "\u000b"
|
17626 | case 102: return "\f"
|
17627 | case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
|
17628 | case 10:
|
17629 | if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
|
17630 | return ""
|
17631 | case 56:
|
17632 | case 57:
|
17633 | if (this.strict) {
|
17634 | this.invalidStringToken(
|
17635 | this.pos - 1,
|
17636 | "Invalid escape sequence"
|
17637 | );
|
17638 | }
|
17639 | if (inTemplate) {
|
17640 | var codePos = this.pos - 1;
|
17641 |
|
17642 | this.invalidStringToken(
|
17643 | codePos,
|
17644 | "Invalid escape sequence in template string"
|
17645 | );
|
17646 |
|
17647 | return null
|
17648 | }
|
17649 | default:
|
17650 | if (ch >= 48 && ch <= 55) {
|
17651 | var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
|
17652 | var octal = parseInt(octalStr, 8);
|
17653 | if (octal > 255) {
|
17654 | octalStr = octalStr.slice(0, -1);
|
17655 | octal = parseInt(octalStr, 8);
|
17656 | }
|
17657 | this.pos += octalStr.length - 1;
|
17658 | ch = this.input.charCodeAt(this.pos);
|
17659 | if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
|
17660 | this.invalidStringToken(
|
17661 | this.pos - 1 - octalStr.length,
|
17662 | inTemplate
|
17663 | ? "Octal literal in template string"
|
17664 | : "Octal literal in strict mode"
|
17665 | );
|
17666 | }
|
17667 | return String.fromCharCode(octal)
|
17668 | }
|
17669 | if (isNewLine(ch)) {
|
17670 |
|
17671 |
|
17672 | return ""
|
17673 | }
|
17674 | return String.fromCharCode(ch)
|
17675 | }
|
17676 | };
|
17677 |
|
17678 |
|
17679 |
|
17680 | pp$9.readHexChar = function(len) {
|
17681 | var codePos = this.pos;
|
17682 | var n = this.readInt(16, len);
|
17683 | if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
|
17684 | return n
|
17685 | };
|
17686 |
|
17687 |
|
17688 |
|
17689 |
|
17690 |
|
17691 |
|
17692 |
|
17693 | pp$9.readWord1 = function() {
|
17694 | this.containsEsc = false;
|
17695 | var word = "", first = true, chunkStart = this.pos;
|
17696 | var astral = this.options.ecmaVersion >= 6;
|
17697 | while (this.pos < this.input.length) {
|
17698 | var ch = this.fullCharCodeAtPos();
|
17699 | if (isIdentifierChar(ch, astral)) {
|
17700 | this.pos += ch <= 0xffff ? 1 : 2;
|
17701 | } else if (ch === 92) {
|
17702 | this.containsEsc = true;
|
17703 | word += this.input.slice(chunkStart, this.pos);
|
17704 | var escStart = this.pos;
|
17705 | if (this.input.charCodeAt(++this.pos) !== 117)
|
17706 | { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
|
17707 | ++this.pos;
|
17708 | var esc = this.readCodePoint();
|
17709 | if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
|
17710 | { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
|
17711 | word += codePointToString$1(esc);
|
17712 | chunkStart = this.pos;
|
17713 | } else {
|
17714 | break
|
17715 | }
|
17716 | first = false;
|
17717 | }
|
17718 | return word + this.input.slice(chunkStart, this.pos)
|
17719 | };
|
17720 |
|
17721 |
|
17722 |
|
17723 |
|
17724 | pp$9.readWord = function() {
|
17725 | var word = this.readWord1();
|
17726 | var type = types.name;
|
17727 | if (this.keywords.test(word)) {
|
17728 | type = keywords$1[word];
|
17729 | }
|
17730 | return this.finishToken(type, word)
|
17731 | };
|
17732 |
|
17733 |
|
17734 |
|
17735 | var version$1 = "8.0.3";
|
17736 |
|
17737 | Parser.acorn = {
|
17738 | Parser: Parser,
|
17739 | version: version$1,
|
17740 | defaultOptions: defaultOptions,
|
17741 | Position: Position,
|
17742 | SourceLocation: SourceLocation,
|
17743 | getLineInfo: getLineInfo,
|
17744 | Node: Node,
|
17745 | TokenType: TokenType,
|
17746 | tokTypes: types,
|
17747 | keywordTypes: keywords$1,
|
17748 | TokContext: TokContext,
|
17749 | tokContexts: types$1,
|
17750 | isIdentifierChar: isIdentifierChar,
|
17751 | isIdentifierStart: isIdentifierStart,
|
17752 | Token: Token,
|
17753 | isNewLine: isNewLine,
|
17754 | lineBreak: lineBreak,
|
17755 | lineBreakG: lineBreakG,
|
17756 | nonASCIIwhitespace: nonASCIIwhitespace
|
17757 | };
|
17758 |
|
17759 |
|
17760 |
|
17761 |
|
17762 |
|
17763 |
|
17764 |
|
17765 |
|
17766 | function parse(input, options) {
|
17767 | return Parser.parse(input, options)
|
17768 | }
|
17769 |
|
17770 |
|
17771 |
|
17772 |
|
17773 |
|
17774 | function parseExpressionAt(input, pos, options) {
|
17775 | return Parser.parseExpressionAt(input, pos, options)
|
17776 | }
|
17777 |
|
17778 |
|
17779 |
|
17780 |
|
17781 | function tokenizer(input, options) {
|
17782 | return Parser.tokenizer(input, options)
|
17783 | }
|
17784 |
|
17785 | var acorn = {
|
17786 | __proto__: null,
|
17787 | Node: Node,
|
17788 | Parser: Parser,
|
17789 | Position: Position,
|
17790 | SourceLocation: SourceLocation,
|
17791 | TokContext: TokContext,
|
17792 | Token: Token,
|
17793 | TokenType: TokenType,
|
17794 | defaultOptions: defaultOptions,
|
17795 | getLineInfo: getLineInfo,
|
17796 | isIdentifierChar: isIdentifierChar,
|
17797 | isIdentifierStart: isIdentifierStart,
|
17798 | isNewLine: isNewLine,
|
17799 | keywordTypes: keywords$1,
|
17800 | lineBreak: lineBreak,
|
17801 | lineBreakG: lineBreakG,
|
17802 | nonASCIIwhitespace: nonASCIIwhitespace,
|
17803 | parse: parse,
|
17804 | parseExpressionAt: parseExpressionAt,
|
17805 | tokContexts: types$1,
|
17806 | tokTypes: types,
|
17807 | tokenizer: tokenizer,
|
17808 | version: version$1
|
17809 | };
|
17810 |
|
17811 | class GlobalScope extends Scope {
|
17812 | constructor() {
|
17813 | super();
|
17814 | this.variables.set('undefined', new UndefinedVariable());
|
17815 | }
|
17816 | findVariable(name) {
|
17817 | let variable = this.variables.get(name);
|
17818 | if (!variable) {
|
17819 | variable = new GlobalVariable(name);
|
17820 | this.variables.set(name, variable);
|
17821 | }
|
17822 | return variable;
|
17823 | }
|
17824 | }
|
17825 |
|
17826 | const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
|
17827 | function mkdirpath(path) {
|
17828 | const dir = sysPath.dirname(path);
|
17829 | try {
|
17830 | fs.readdirSync(dir);
|
17831 | }
|
17832 | catch (err) {
|
17833 | mkdirpath(dir);
|
17834 | try {
|
17835 | fs.mkdirSync(dir);
|
17836 | }
|
17837 | catch (err2) {
|
17838 | if (err2.code !== 'EEXIST') {
|
17839 | throw err2;
|
17840 | }
|
17841 | }
|
17842 | }
|
17843 | }
|
17844 | function writeFile(dest, data) {
|
17845 | return new Promise((fulfil, reject) => {
|
17846 | mkdirpath(dest);
|
17847 | fs.writeFile(dest, data, err => {
|
17848 | if (err) {
|
17849 | reject(err);
|
17850 | }
|
17851 | else {
|
17852 | fulfil();
|
17853 | }
|
17854 | });
|
17855 | });
|
17856 | }
|
17857 |
|
17858 | async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
|
17859 | const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
|
17860 | if (pluginResult != null)
|
17861 | return pluginResult;
|
17862 |
|
17863 |
|
17864 | if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
|
17865 | return null;
|
17866 |
|
17867 |
|
17868 |
|
17869 |
|
17870 | return addJsExtensionIfNecessary(sysPath.resolve(importer ? sysPath.dirname(importer) : sysPath.resolve(), source), preserveSymlinks);
|
17871 | }
|
17872 | function addJsExtensionIfNecessary(file, preserveSymlinks) {
|
17873 | let found = findFile(file, preserveSymlinks);
|
17874 | if (found)
|
17875 | return found;
|
17876 | found = findFile(file + '.mjs', preserveSymlinks);
|
17877 | if (found)
|
17878 | return found;
|
17879 | found = findFile(file + '.js', preserveSymlinks);
|
17880 | return found;
|
17881 | }
|
17882 | function findFile(file, preserveSymlinks) {
|
17883 | try {
|
17884 | const stats = fs.lstatSync(file);
|
17885 | if (!preserveSymlinks && stats.isSymbolicLink())
|
17886 | return findFile(fs.realpathSync(file), preserveSymlinks);
|
17887 | if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
|
17888 |
|
17889 | const name = sysPath.basename(file);
|
17890 | const files = fs.readdirSync(sysPath.dirname(file));
|
17891 | if (files.indexOf(name) !== -1)
|
17892 | return file;
|
17893 | }
|
17894 | }
|
17895 | catch (_a) {
|
17896 |
|
17897 | }
|
17898 | }
|
17899 |
|
17900 | const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
|
17901 | const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
|
17902 | function throwPluginError(err, plugin, { hook, id } = {}) {
|
17903 | if (typeof err === 'string')
|
17904 | err = { message: err };
|
17905 | if (err.code && err.code !== Errors.PLUGIN_ERROR) {
|
17906 | err.pluginCode = err.code;
|
17907 | }
|
17908 | err.code = Errors.PLUGIN_ERROR;
|
17909 | err.plugin = plugin;
|
17910 | if (hook) {
|
17911 | err.hook = hook;
|
17912 | }
|
17913 | if (id) {
|
17914 | err.id = id;
|
17915 | }
|
17916 | return error(err);
|
17917 | }
|
17918 | const deprecatedHooks = [
|
17919 | { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
|
17920 | ];
|
17921 | function warnDeprecatedHooks(plugins, options) {
|
17922 | for (const { active, deprecated, replacement } of deprecatedHooks) {
|
17923 | for (const plugin of plugins) {
|
17924 | if (deprecated in plugin) {
|
17925 | warnDeprecation({
|
17926 | message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
|
17927 | plugin: plugin.name
|
17928 | }, active, options);
|
17929 | }
|
17930 | }
|
17931 | }
|
17932 | }
|
17933 |
|
17934 | function createPluginCache(cache) {
|
17935 | return {
|
17936 | has(id) {
|
17937 | const item = cache[id];
|
17938 | if (!item)
|
17939 | return false;
|
17940 | item[0] = 0;
|
17941 | return true;
|
17942 | },
|
17943 | get(id) {
|
17944 | const item = cache[id];
|
17945 | if (!item)
|
17946 | return undefined;
|
17947 | item[0] = 0;
|
17948 | return item[1];
|
17949 | },
|
17950 | set(id, value) {
|
17951 | cache[id] = [0, value];
|
17952 | },
|
17953 | delete(id) {
|
17954 | return delete cache[id];
|
17955 | }
|
17956 | };
|
17957 | }
|
17958 | function getTrackedPluginCache(pluginCache, onUse) {
|
17959 | return {
|
17960 | has(id) {
|
17961 | onUse();
|
17962 | return pluginCache.has(id);
|
17963 | },
|
17964 | get(id) {
|
17965 | onUse();
|
17966 | return pluginCache.get(id);
|
17967 | },
|
17968 | set(id, value) {
|
17969 | onUse();
|
17970 | return pluginCache.set(id, value);
|
17971 | },
|
17972 | delete(id) {
|
17973 | onUse();
|
17974 | return pluginCache.delete(id);
|
17975 | }
|
17976 | };
|
17977 | }
|
17978 | const NO_CACHE = {
|
17979 | has() {
|
17980 | return false;
|
17981 | },
|
17982 | get() {
|
17983 | return undefined;
|
17984 | },
|
17985 | set() { },
|
17986 | delete() {
|
17987 | return false;
|
17988 | }
|
17989 | };
|
17990 | function uncacheablePluginError(pluginName) {
|
17991 | if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
|
17992 | pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
|
17993 | return error({
|
17994 | code: 'ANONYMOUS_PLUGIN_CACHE',
|
17995 | message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
|
17996 | });
|
17997 | }
|
17998 | return error({
|
17999 | code: 'DUPLICATE_PLUGIN_NAME',
|
18000 | 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).`
|
18001 | });
|
18002 | }
|
18003 | function getCacheForUncacheablePlugin(pluginName) {
|
18004 | return {
|
18005 | has() {
|
18006 | return uncacheablePluginError(pluginName);
|
18007 | },
|
18008 | get() {
|
18009 | return uncacheablePluginError(pluginName);
|
18010 | },
|
18011 | set() {
|
18012 | return uncacheablePluginError(pluginName);
|
18013 | },
|
18014 | delete() {
|
18015 | return uncacheablePluginError(pluginName);
|
18016 | }
|
18017 | };
|
18018 | }
|
18019 |
|
18020 | function transform(source, module, pluginDriver, warn) {
|
18021 | const id = module.id;
|
18022 | const sourcemapChain = [];
|
18023 | let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
|
18024 | const originalCode = source.code;
|
18025 | let ast = source.ast;
|
18026 | const transformDependencies = [];
|
18027 | const emittedFiles = [];
|
18028 | let customTransformCache = false;
|
18029 | const useCustomTransformCache = () => (customTransformCache = true);
|
18030 | let curPlugin;
|
18031 | const curSource = source.code;
|
18032 | function transformReducer(previousCode, result, plugin) {
|
18033 | let code;
|
18034 | let map;
|
18035 | if (typeof result === 'string') {
|
18036 | code = result;
|
18037 | }
|
18038 | else if (result && typeof result === 'object') {
|
18039 | module.updateOptions(result);
|
18040 | if (result.code == null) {
|
18041 | if (result.map || result.ast) {
|
18042 | warn(errNoTransformMapOrAstWithoutCode(plugin.name));
|
18043 | }
|
18044 | return previousCode;
|
18045 | }
|
18046 | ({ code, map, ast } = result);
|
18047 | }
|
18048 | else {
|
18049 | return previousCode;
|
18050 | }
|
18051 |
|
18052 |
|
18053 | if (map !== null) {
|
18054 | sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
|
18055 | missing: true,
|
18056 | plugin: plugin.name
|
18057 | });
|
18058 | }
|
18059 | return code;
|
18060 | }
|
18061 | return pluginDriver
|
18062 | .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
|
18063 | curPlugin = plugin;
|
18064 | return {
|
18065 | ...pluginContext,
|
18066 | cache: customTransformCache
|
18067 | ? pluginContext.cache
|
18068 | : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
|
18069 | warn(warning, pos) {
|
18070 | if (typeof warning === 'string')
|
18071 | warning = { message: warning };
|
18072 | if (pos)
|
18073 | augmentCodeLocation(warning, pos, curSource, id);
|
18074 | warning.id = id;
|
18075 | warning.hook = 'transform';
|
18076 | pluginContext.warn(warning);
|
18077 | },
|
18078 | error(err, pos) {
|
18079 | if (typeof err === 'string')
|
18080 | err = { message: err };
|
18081 | if (pos)
|
18082 | augmentCodeLocation(err, pos, curSource, id);
|
18083 | err.id = id;
|
18084 | err.hook = 'transform';
|
18085 | return pluginContext.error(err);
|
18086 | },
|
18087 | emitAsset(name, source) {
|
18088 | emittedFiles.push({ type: 'asset', name, source });
|
18089 | return pluginContext.emitAsset(name, source);
|
18090 | },
|
18091 | emitChunk(id, options) {
|
18092 | emittedFiles.push({ type: 'chunk', id, name: options && options.name });
|
18093 | return pluginContext.emitChunk(id, options);
|
18094 | },
|
18095 | emitFile(emittedFile) {
|
18096 | emittedFiles.push(emittedFile);
|
18097 | return pluginDriver.emitFile(emittedFile);
|
18098 | },
|
18099 | addWatchFile(id) {
|
18100 | transformDependencies.push(id);
|
18101 | pluginContext.addWatchFile(id);
|
18102 | },
|
18103 | setAssetSource() {
|
18104 | return this.error({
|
18105 | code: 'INVALID_SETASSETSOURCE',
|
18106 | message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
|
18107 | });
|
18108 | },
|
18109 | getCombinedSourcemap() {
|
18110 | const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
|
18111 | if (!combinedMap) {
|
18112 | const magicString = new MagicString(originalCode);
|
18113 | return magicString.generateMap({ includeContent: true, hires: true, source: id });
|
18114 | }
|
18115 | if (originalSourcemap !== combinedMap) {
|
18116 | originalSourcemap = combinedMap;
|
18117 | sourcemapChain.length = 0;
|
18118 | }
|
18119 | return new SourceMap({
|
18120 | ...combinedMap,
|
18121 | file: null,
|
18122 | sourcesContent: combinedMap.sourcesContent
|
18123 | });
|
18124 | }
|
18125 | };
|
18126 | })
|
18127 | .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
|
18128 | .then(code => {
|
18129 | if (!customTransformCache) {
|
18130 |
|
18131 | if (emittedFiles.length)
|
18132 | module.transformFiles = emittedFiles;
|
18133 | }
|
18134 | return {
|
18135 | ast,
|
18136 | code,
|
18137 | customTransformCache,
|
18138 | meta: module.info.meta,
|
18139 | originalCode,
|
18140 | originalSourcemap,
|
18141 | sourcemapChain,
|
18142 | transformDependencies
|
18143 | };
|
18144 | });
|
18145 | }
|
18146 |
|
18147 | class ModuleLoader {
|
18148 | constructor(graph, modulesById, options, pluginDriver) {
|
18149 | this.graph = graph;
|
18150 | this.modulesById = modulesById;
|
18151 | this.options = options;
|
18152 | this.pluginDriver = pluginDriver;
|
18153 | this.implicitEntryModules = new Set();
|
18154 | this.indexedEntryModules = [];
|
18155 | this.latestLoadModulesPromise = Promise.resolve();
|
18156 | this.nextEntryModuleIndex = 0;
|
18157 | this.hasModuleSideEffects = options.treeshake
|
18158 | ? options.treeshake.moduleSideEffects
|
18159 | : () => true;
|
18160 | }
|
18161 | async addAdditionalModules(unresolvedModules) {
|
18162 | const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
|
18163 | await this.awaitLoadModulesPromise();
|
18164 | return result;
|
18165 | }
|
18166 | async addEntryModules(unresolvedEntryModules, isUserDefined) {
|
18167 | const firstEntryModuleIndex = this.nextEntryModuleIndex;
|
18168 | this.nextEntryModuleIndex += unresolvedEntryModules.length;
|
18169 | const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
|
18170 | let moduleIndex = firstEntryModuleIndex;
|
18171 | for (let index = 0; index < entryModules.length; index++) {
|
18172 | const entryModule = entryModules[index];
|
18173 | entryModule.isUserDefinedEntryPoint =
|
18174 | entryModule.isUserDefinedEntryPoint || isUserDefined;
|
18175 | addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
|
18176 | const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
|
18177 | if (!existingIndexedModule) {
|
18178 | this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
|
18179 | }
|
18180 | else {
|
18181 | existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
|
18182 | }
|
18183 | moduleIndex++;
|
18184 | }
|
18185 | this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
|
18186 | return entryModules;
|
18187 | }));
|
18188 | await this.awaitLoadModulesPromise();
|
18189 | return {
|
18190 | entryModules: this.indexedEntryModules.map(({ module }) => module),
|
18191 | implicitEntryModules: [...this.implicitEntryModules],
|
18192 | newEntryModules
|
18193 | };
|
18194 | }
|
18195 | async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
|
18196 | const unresolvedModule = {
|
18197 | fileName: fileName || null,
|
18198 | id,
|
18199 | importer,
|
18200 | name: name || null
|
18201 | };
|
18202 | const module = implicitlyLoadedAfterOneOf
|
18203 | ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
|
18204 | : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
|
18205 | if (preserveSignature != null) {
|
18206 | module.preserveSignature = preserveSignature;
|
18207 | }
|
18208 | return module;
|
18209 | }
|
18210 | async resolveId(source, importer, customOptions, skip = null) {
|
18211 | return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
|
18212 | ? false
|
18213 | : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
|
18214 | }
|
18215 | addDefaultsToResolvedId(resolvedId) {
|
18216 | var _a, _b;
|
18217 | if (!resolvedId) {
|
18218 | return null;
|
18219 | }
|
18220 | const external = resolvedId.external || false;
|
18221 | return {
|
18222 | external,
|
18223 | id: resolvedId.id,
|
18224 | meta: resolvedId.meta || EMPTY_OBJECT,
|
18225 | moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
|
18226 | syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
|
18227 | };
|
18228 | }
|
18229 | addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
|
18230 | return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
|
18231 | addChunkNamesToModule(entryModule, unresolvedModule, false);
|
18232 | if (!entryModule.info.isEntry) {
|
18233 | this.implicitEntryModules.add(entryModule);
|
18234 | const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
|
18235 | for (const module of implicitlyLoadedAfterModules) {
|
18236 | entryModule.implicitlyLoadedAfter.add(module);
|
18237 | }
|
18238 | for (const dependant of entryModule.implicitlyLoadedAfter) {
|
18239 | dependant.implicitlyLoadedBefore.add(entryModule);
|
18240 | }
|
18241 | }
|
18242 | return entryModule;
|
18243 | }));
|
18244 | }
|
18245 | async addModuleSource(id, importer, module) {
|
18246 | var _a;
|
18247 | timeStart('load modules', 3);
|
18248 | let source;
|
18249 | try {
|
18250 | source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
|
18251 | }
|
18252 | catch (err) {
|
18253 | timeEnd('load modules', 3);
|
18254 | let msg = `Could not load ${id}`;
|
18255 | if (importer)
|
18256 | msg += ` (imported by ${relativeId(importer)})`;
|
18257 | msg += `: ${err.message}`;
|
18258 | err.message = msg;
|
18259 | throw err;
|
18260 | }
|
18261 | timeEnd('load modules', 3);
|
18262 | const sourceDescription = typeof source === 'string'
|
18263 | ? { code: source }
|
18264 | : typeof source === 'object' && typeof source.code === 'string'
|
18265 | ? source
|
18266 | : error(errBadLoader(id));
|
18267 | const cachedModule = this.graph.cachedModules.get(id);
|
18268 | if (cachedModule &&
|
18269 | !cachedModule.customTransformCache &&
|
18270 | cachedModule.originalCode === sourceDescription.code) {
|
18271 | if (cachedModule.transformFiles) {
|
18272 | for (const emittedFile of cachedModule.transformFiles)
|
18273 | this.pluginDriver.emitFile(emittedFile);
|
18274 | }
|
18275 | module.setSource(cachedModule);
|
18276 | }
|
18277 | else {
|
18278 | module.updateOptions(sourceDescription);
|
18279 | module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
|
18280 | }
|
18281 | }
|
18282 | async awaitLoadModulesPromise() {
|
18283 | let startingPromise;
|
18284 | do {
|
18285 | startingPromise = this.latestLoadModulesPromise;
|
18286 | await startingPromise;
|
18287 | } while (startingPromise !== this.latestLoadModulesPromise);
|
18288 | }
|
18289 | extendLoadModulesPromise(loadNewModulesPromise) {
|
18290 | this.latestLoadModulesPromise = Promise.all([
|
18291 | loadNewModulesPromise,
|
18292 | this.latestLoadModulesPromise
|
18293 | ]);
|
18294 | this.latestLoadModulesPromise.catch(() => {
|
18295 |
|
18296 | });
|
18297 | return loadNewModulesPromise;
|
18298 | }
|
18299 | async fetchDynamicDependencies(module) {
|
18300 | const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
|
18301 | const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
|
18302 | ? dynamicImport.argument
|
18303 | : dynamicImport.argument.esTreeNode, module.id);
|
18304 | if (resolvedId === null)
|
18305 | return null;
|
18306 | if (typeof resolvedId === 'string') {
|
18307 | dynamicImport.resolution = resolvedId;
|
18308 | return null;
|
18309 | }
|
18310 | return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
|
18311 | }));
|
18312 | for (const dependency of dependencies) {
|
18313 | if (dependency) {
|
18314 | module.dynamicDependencies.add(dependency);
|
18315 | dependency.dynamicImporters.push(module.id);
|
18316 | }
|
18317 | }
|
18318 | }
|
18319 | async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
|
18320 | const existingModule = this.modulesById.get(id);
|
18321 | if (existingModule instanceof Module) {
|
18322 | if (isEntry) {
|
18323 | existingModule.info.isEntry = true;
|
18324 | this.implicitEntryModules.delete(existingModule);
|
18325 | for (const dependant of existingModule.implicitlyLoadedAfter) {
|
18326 | dependant.implicitlyLoadedBefore.delete(existingModule);
|
18327 | }
|
18328 | existingModule.implicitlyLoadedAfter.clear();
|
18329 | }
|
18330 | return existingModule;
|
18331 | }
|
18332 | const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
|
18333 | this.modulesById.set(id, module);
|
18334 | this.graph.watchFiles[id] = true;
|
18335 | await this.addModuleSource(id, importer, module);
|
18336 | await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
|
18337 | await Promise.all([
|
18338 | this.fetchStaticDependencies(module),
|
18339 | this.fetchDynamicDependencies(module)
|
18340 | ]);
|
18341 | module.linkImports();
|
18342 | return module;
|
18343 | }
|
18344 | fetchResolvedDependency(source, importer, resolvedId) {
|
18345 | if (resolvedId.external) {
|
18346 | if (!this.modulesById.has(resolvedId.id)) {
|
18347 | this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
|
18348 | }
|
18349 | const externalModule = this.modulesById.get(resolvedId.id);
|
18350 | if (!(externalModule instanceof ExternalModule)) {
|
18351 | return error(errInternalIdCannotBeExternal(source, importer));
|
18352 | }
|
18353 | return Promise.resolve(externalModule);
|
18354 | }
|
18355 | else {
|
18356 | return this.fetchModule(resolvedId, importer, false);
|
18357 | }
|
18358 | }
|
18359 | async fetchStaticDependencies(module) {
|
18360 | for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
|
18361 | module.resolvedIds[source] ||
|
18362 | this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
|
18363 | module.dependencies.add(dependency);
|
18364 | dependency.importers.push(module.id);
|
18365 | }
|
18366 | }
|
18367 | getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
|
18368 | if (resolveIdResult) {
|
18369 | if (typeof resolveIdResult === 'object') {
|
18370 | return {
|
18371 | ...resolveIdResult,
|
18372 | external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
|
18373 | };
|
18374 | }
|
18375 | const external = this.options.external(resolveIdResult, importer, true);
|
18376 | return {
|
18377 | external,
|
18378 | id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
|
18379 | };
|
18380 | }
|
18381 | const id = normalizeRelativeExternalId(source, importer);
|
18382 | if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
|
18383 | return null;
|
18384 | }
|
18385 | return {
|
18386 | external: true,
|
18387 | id
|
18388 | };
|
18389 | }
|
18390 | handleResolveId(resolvedId, source, importer) {
|
18391 | if (resolvedId === null) {
|
18392 | if (isRelative(source)) {
|
18393 | return error(errUnresolvedImport(source, importer));
|
18394 | }
|
18395 | this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
|
18396 | return {
|
18397 | external: true,
|
18398 | id: source,
|
18399 | meta: EMPTY_OBJECT,
|
18400 | moduleSideEffects: this.hasModuleSideEffects(source, true),
|
18401 | syntheticNamedExports: false
|
18402 | };
|
18403 | }
|
18404 | else {
|
18405 | if (resolvedId.external && resolvedId.syntheticNamedExports) {
|
18406 | this.options.onwarn(errExternalSyntheticExports(source, importer));
|
18407 | }
|
18408 | }
|
18409 | return resolvedId;
|
18410 | }
|
18411 | async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
|
18412 | const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
|
18413 | if (resolveIdResult == null) {
|
18414 | return error(implicitlyLoadedBefore === null
|
18415 | ? errUnresolvedEntry(unresolvedId)
|
18416 | : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
|
18417 | }
|
18418 | if (resolveIdResult === false ||
|
18419 | (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
|
18420 | return error(implicitlyLoadedBefore === null
|
18421 | ? errEntryCannotBeExternal(unresolvedId)
|
18422 | : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
|
18423 | }
|
18424 | return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
|
18425 | }
|
18426 | async resolveDynamicImport(module, specifier, importer) {
|
18427 | const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
|
18428 | specifier,
|
18429 | importer
|
18430 | ]);
|
18431 | if (typeof specifier !== 'string') {
|
18432 | if (typeof resolution === 'string') {
|
18433 | return resolution;
|
18434 | }
|
18435 | if (!resolution) {
|
18436 | return null;
|
18437 | }
|
18438 | return {
|
18439 | external: false,
|
18440 | moduleSideEffects: true,
|
18441 | ...resolution
|
18442 | };
|
18443 | }
|
18444 | if (resolution == null) {
|
18445 | return (module.resolvedIds[specifier] =
|
18446 | module.resolvedIds[specifier] ||
|
18447 | this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
|
18448 | }
|
18449 | return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
|
18450 | }
|
18451 | }
|
18452 | function normalizeRelativeExternalId(source, importer) {
|
18453 | return isRelative(source)
|
18454 | ? importer
|
18455 | ? sysPath.resolve(importer, '..', source)
|
18456 | : sysPath.resolve(source)
|
18457 | : source;
|
18458 | }
|
18459 | function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
|
18460 | if (fileName !== null) {
|
18461 | module.chunkFileNames.add(fileName);
|
18462 | }
|
18463 | else if (name !== null) {
|
18464 | if (module.chunkName === null) {
|
18465 | module.chunkName = name;
|
18466 | }
|
18467 | if (isUserDefined) {
|
18468 | module.userChunkNames.add(name);
|
18469 | }
|
18470 | }
|
18471 | }
|
18472 |
|
18473 | function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
|
18474 | let deprecationWarningShown = false;
|
18475 | return ((...args) => {
|
18476 | if (!deprecationWarningShown) {
|
18477 | deprecationWarningShown = true;
|
18478 | warnDeprecation({
|
18479 | message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
|
18480 | plugin: pluginName
|
18481 | }, activeDeprecation, options);
|
18482 | }
|
18483 | return handler(...args);
|
18484 | });
|
18485 | }
|
18486 | function getPluginContexts(pluginCache, graph, options, fileEmitter) {
|
18487 | const existingPluginNames = new Set();
|
18488 | return (plugin, pidx) => {
|
18489 | let cacheable = true;
|
18490 | if (typeof plugin.cacheKey !== 'string') {
|
18491 | if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
|
18492 | plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
|
18493 | existingPluginNames.has(plugin.name)) {
|
18494 | cacheable = false;
|
18495 | }
|
18496 | else {
|
18497 | existingPluginNames.add(plugin.name);
|
18498 | }
|
18499 | }
|
18500 | let cacheInstance;
|
18501 | if (!pluginCache) {
|
18502 | cacheInstance = NO_CACHE;
|
18503 | }
|
18504 | else if (cacheable) {
|
18505 | const cacheKey = plugin.cacheKey || plugin.name;
|
18506 | cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
|
18507 | }
|
18508 | else {
|
18509 | cacheInstance = getCacheForUncacheablePlugin(plugin.name);
|
18510 | }
|
18511 | const context = {
|
18512 | addWatchFile(id) {
|
18513 | if (graph.phase >= BuildPhase.GENERATE) {
|
18514 | return this.error(errInvalidRollupPhaseForAddWatchFile());
|
18515 | }
|
18516 | graph.watchFiles[id] = true;
|
18517 | },
|
18518 | cache: cacheInstance,
|
18519 | emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
|
18520 | emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
|
18521 | emitFile: fileEmitter.emitFile,
|
18522 | error(err) {
|
18523 | return throwPluginError(err, plugin.name);
|
18524 | },
|
18525 | getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
|
18526 | getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
|
18527 | getFileName: fileEmitter.getFileName,
|
18528 | getModuleIds: () => graph.modulesById.keys(),
|
18529 | getModuleInfo: graph.getModuleInfo,
|
18530 | getWatchFiles: () => Object.keys(graph.watchFiles),
|
18531 | isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
|
18532 | meta: {
|
18533 | rollupVersion: version,
|
18534 | watchMode: graph.watchMode
|
18535 | },
|
18536 | get moduleIds() {
|
18537 | function* wrappedModuleIds() {
|
18538 | warnDeprecation({
|
18539 | message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
|
18540 | plugin: plugin.name
|
18541 | }, false, options);
|
18542 | yield* moduleIds;
|
18543 | }
|
18544 | const moduleIds = graph.modulesById.keys();
|
18545 | return wrappedModuleIds();
|
18546 | },
|
18547 | parse: graph.contextParse,
|
18548 | resolve(source, importer, { custom, skipSelf } = BLANK) {
|
18549 | return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
|
18550 | },
|
18551 | resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
|
18552 | .resolveId(source, importer, BLANK)
|
18553 | .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
|
18554 | setAssetSource: fileEmitter.setAssetSource,
|
18555 | warn(warning) {
|
18556 | if (typeof warning === 'string')
|
18557 | warning = { message: warning };
|
18558 | if (warning.code)
|
18559 | warning.pluginCode = warning.code;
|
18560 | warning.code = 'PLUGIN_WARNING';
|
18561 | warning.plugin = plugin.name;
|
18562 | options.onwarn(warning);
|
18563 | }
|
18564 | };
|
18565 | return context;
|
18566 | };
|
18567 | }
|
18568 |
|
18569 | const inputHookNames = {
|
18570 | buildEnd: 1,
|
18571 | buildStart: 1,
|
18572 | closeWatcher: 1,
|
18573 | load: 1,
|
18574 | moduleParsed: 1,
|
18575 | options: 1,
|
18576 | resolveDynamicImport: 1,
|
18577 | resolveId: 1,
|
18578 | transform: 1,
|
18579 | watchChange: 1
|
18580 | };
|
18581 | const inputHooks = Object.keys(inputHookNames);
|
18582 | function throwInvalidHookError(hookName, pluginName) {
|
18583 | return error({
|
18584 | code: 'INVALID_PLUGIN_HOOK',
|
18585 | message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
|
18586 | });
|
18587 | }
|
18588 | class PluginDriver {
|
18589 | constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
|
18590 | this.graph = graph;
|
18591 | this.options = options;
|
18592 | warnDeprecatedHooks(userPlugins, options);
|
18593 | this.pluginCache = pluginCache;
|
18594 | this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
|
18595 | this.emitFile = this.fileEmitter.emitFile;
|
18596 | this.getFileName = this.fileEmitter.getFileName;
|
18597 | this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
|
18598 | this.setOutputBundle = this.fileEmitter.setOutputBundle;
|
18599 | this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
|
18600 | this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
|
18601 | if (basePluginDriver) {
|
18602 | for (const plugin of userPlugins) {
|
18603 | for (const hook of inputHooks) {
|
18604 | if (hook in plugin) {
|
18605 | options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
|
18606 | }
|
18607 | }
|
18608 | }
|
18609 | }
|
18610 | }
|
18611 | createOutputPluginDriver(plugins) {
|
18612 | return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
|
18613 | }
|
18614 |
|
18615 | hookFirst(hookName, args, replaceContext, skip) {
|
18616 | let promise = Promise.resolve(undefined);
|
18617 | for (let i = 0; i < this.plugins.length; i++) {
|
18618 | if (skip === i)
|
18619 | continue;
|
18620 | promise = promise.then(result => {
|
18621 | if (result != null)
|
18622 | return result;
|
18623 | return this.runHook(hookName, args, i, false, replaceContext);
|
18624 | });
|
18625 | }
|
18626 | return promise;
|
18627 | }
|
18628 |
|
18629 | hookFirstSync(hookName, args, replaceContext) {
|
18630 | for (let i = 0; i < this.plugins.length; i++) {
|
18631 | const result = this.runHookSync(hookName, args, i, replaceContext);
|
18632 | if (result != null)
|
18633 | return result;
|
18634 | }
|
18635 | return null;
|
18636 | }
|
18637 |
|
18638 | hookParallel(hookName, args, replaceContext) {
|
18639 | const promises = [];
|
18640 | for (let i = 0; i < this.plugins.length; i++) {
|
18641 | const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
|
18642 | if (!hookPromise)
|
18643 | continue;
|
18644 | promises.push(hookPromise);
|
18645 | }
|
18646 | return Promise.all(promises).then(() => { });
|
18647 | }
|
18648 |
|
18649 | hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
|
18650 | let promise = Promise.resolve(arg0);
|
18651 | for (let i = 0; i < this.plugins.length; i++) {
|
18652 | promise = promise.then(arg0 => {
|
18653 | const args = [arg0, ...rest];
|
18654 | const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
|
18655 | if (!hookPromise)
|
18656 | return arg0;
|
18657 | return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
|
18658 | });
|
18659 | }
|
18660 | return promise;
|
18661 | }
|
18662 |
|
18663 | hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
|
18664 | for (let i = 0; i < this.plugins.length; i++) {
|
18665 | const args = [arg0, ...rest];
|
18666 | const result = this.runHookSync(hookName, args, i, replaceContext);
|
18667 | arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
|
18668 | }
|
18669 | return arg0;
|
18670 | }
|
18671 |
|
18672 | hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
|
18673 | let promise = Promise.resolve(initialValue);
|
18674 | for (let i = 0; i < this.plugins.length; i++) {
|
18675 | promise = promise.then(value => {
|
18676 | const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
|
18677 | if (!hookPromise)
|
18678 | return value;
|
18679 | return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
|
18680 | });
|
18681 | }
|
18682 | return promise;
|
18683 | }
|
18684 |
|
18685 | hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
|
18686 | let acc = initialValue;
|
18687 | for (let i = 0; i < this.plugins.length; i++) {
|
18688 | const result = this.runHookSync(hookName, args, i, replaceContext);
|
18689 | acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
|
18690 | }
|
18691 | return acc;
|
18692 | }
|
18693 |
|
18694 | hookSeq(hookName, args, replaceContext) {
|
18695 | let promise = Promise.resolve();
|
18696 | for (let i = 0; i < this.plugins.length; i++) {
|
18697 | promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
|
18698 | }
|
18699 | return promise;
|
18700 | }
|
18701 |
|
18702 | hookSeqSync(hookName, args, replaceContext) {
|
18703 | for (let i = 0; i < this.plugins.length; i++) {
|
18704 | this.runHookSync(hookName, args, i, replaceContext);
|
18705 | }
|
18706 | }
|
18707 | runHook(hookName, args, pluginIndex, permitValues, hookContext) {
|
18708 | const plugin = this.plugins[pluginIndex];
|
18709 | const hook = plugin[hookName];
|
18710 | if (!hook)
|
18711 | return undefined;
|
18712 | let context = this.pluginContexts[pluginIndex];
|
18713 | if (hookContext) {
|
18714 | context = hookContext(context, plugin);
|
18715 | }
|
18716 | return Promise.resolve()
|
18717 | .then(() => {
|
18718 |
|
18719 | if (typeof hook !== 'function') {
|
18720 | if (permitValues)
|
18721 | return hook;
|
18722 | return throwInvalidHookError(hookName, plugin.name);
|
18723 | }
|
18724 | return hook.apply(context, args);
|
18725 | })
|
18726 | .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
|
18727 | }
|
18728 | |
18729 |
|
18730 |
|
18731 |
|
18732 |
|
18733 |
|
18734 |
|
18735 | runHookSync(hookName, args, pluginIndex, hookContext) {
|
18736 | const plugin = this.plugins[pluginIndex];
|
18737 | const hook = plugin[hookName];
|
18738 | if (!hook)
|
18739 | return undefined;
|
18740 | let context = this.pluginContexts[pluginIndex];
|
18741 | if (hookContext) {
|
18742 | context = hookContext(context, plugin);
|
18743 | }
|
18744 | try {
|
18745 |
|
18746 | if (typeof hook !== 'function') {
|
18747 | return throwInvalidHookError(hookName, plugin.name);
|
18748 | }
|
18749 | return hook.apply(context, args);
|
18750 | }
|
18751 | catch (err) {
|
18752 | return throwPluginError(err, plugin.name, { hook: hookName });
|
18753 | }
|
18754 | }
|
18755 | }
|
18756 |
|
18757 | function normalizeEntryModules(entryModules) {
|
18758 | if (Array.isArray(entryModules)) {
|
18759 | return entryModules.map(id => ({
|
18760 | fileName: null,
|
18761 | id,
|
18762 | implicitlyLoadedAfter: [],
|
18763 | importer: undefined,
|
18764 | name: null
|
18765 | }));
|
18766 | }
|
18767 | return Object.keys(entryModules).map(name => ({
|
18768 | fileName: null,
|
18769 | id: entryModules[name],
|
18770 | implicitlyLoadedAfter: [],
|
18771 | importer: undefined,
|
18772 | name
|
18773 | }));
|
18774 | }
|
18775 | class Graph {
|
18776 | constructor(options, watcher) {
|
18777 | var _a, _b;
|
18778 | this.options = options;
|
18779 | this.entryModules = [];
|
18780 | this.modulesById = new Map();
|
18781 | this.needsTreeshakingPass = false;
|
18782 | this.phase = BuildPhase.LOAD_AND_PARSE;
|
18783 | this.watchFiles = Object.create(null);
|
18784 | this.watchMode = false;
|
18785 | this.externalModules = [];
|
18786 | this.implicitEntryModules = [];
|
18787 | this.modules = [];
|
18788 | this.getModuleInfo = (moduleId) => {
|
18789 | const foundModule = this.modulesById.get(moduleId);
|
18790 | if (!foundModule)
|
18791 | return null;
|
18792 | return foundModule.info;
|
18793 | };
|
18794 | this.deoptimizationTracker = new PathTracker();
|
18795 | this.cachedModules = new Map();
|
18796 | if (options.cache !== false) {
|
18797 | if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
|
18798 | for (const module of options.cache.modules)
|
18799 | this.cachedModules.set(module.id, module);
|
18800 | }
|
18801 | this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
|
18802 |
|
18803 | for (const name in this.pluginCache) {
|
18804 | const cache = this.pluginCache[name];
|
18805 | for (const key of Object.keys(cache))
|
18806 | cache[key][0]++;
|
18807 | }
|
18808 | }
|
18809 | this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
|
18810 | ...this.options.acorn,
|
18811 | ...options
|
18812 | });
|
18813 | if (watcher) {
|
18814 | this.watchMode = true;
|
18815 | const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
|
18816 | const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
|
18817 | watcher.on('change', handleChange);
|
18818 | watcher.on('close', handleClose);
|
18819 | watcher.once('restart', () => {
|
18820 | watcher.removeListener('change', handleChange);
|
18821 | watcher.removeListener('close', handleClose);
|
18822 | });
|
18823 | }
|
18824 | this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
|
18825 | this.scope = new GlobalScope();
|
18826 | this.acornParser = Parser.extend(...options.acornInjectPlugins);
|
18827 | this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
|
18828 | }
|
18829 | async build() {
|
18830 | timeStart('generate module graph', 2);
|
18831 | await this.generateModuleGraph();
|
18832 | timeEnd('generate module graph', 2);
|
18833 | timeStart('sort modules', 2);
|
18834 | this.phase = BuildPhase.ANALYSE;
|
18835 | this.sortModules();
|
18836 | timeEnd('sort modules', 2);
|
18837 | timeStart('mark included statements', 2);
|
18838 | this.includeStatements();
|
18839 | timeEnd('mark included statements', 2);
|
18840 | this.phase = BuildPhase.GENERATE;
|
18841 | }
|
18842 | getCache() {
|
18843 |
|
18844 | for (const name in this.pluginCache) {
|
18845 | const cache = this.pluginCache[name];
|
18846 | let allDeleted = true;
|
18847 | for (const key of Object.keys(cache)) {
|
18848 | if (cache[key][0] >= this.options.experimentalCacheExpiry)
|
18849 | delete cache[key];
|
18850 | else
|
18851 | allDeleted = false;
|
18852 | }
|
18853 | if (allDeleted)
|
18854 | delete this.pluginCache[name];
|
18855 | }
|
18856 | return {
|
18857 | modules: this.modules.map(module => module.toJSON()),
|
18858 | plugins: this.pluginCache
|
18859 | };
|
18860 | }
|
18861 | async generateModuleGraph() {
|
18862 | ({
|
18863 | entryModules: this.entryModules,
|
18864 | implicitEntryModules: this.implicitEntryModules
|
18865 | } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
|
18866 | if (this.entryModules.length === 0) {
|
18867 | throw new Error('You must supply options.input to rollup');
|
18868 | }
|
18869 | for (const module of this.modulesById.values()) {
|
18870 | if (module instanceof Module) {
|
18871 | this.modules.push(module);
|
18872 | }
|
18873 | else {
|
18874 | this.externalModules.push(module);
|
18875 | }
|
18876 | }
|
18877 | }
|
18878 | includeStatements() {
|
18879 | for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
|
18880 | if (module.preserveSignature !== false) {
|
18881 | module.includeAllExports(false);
|
18882 | }
|
18883 | else {
|
18884 | markModuleAndImpureDependenciesAsExecuted(module);
|
18885 | }
|
18886 | }
|
18887 | if (this.options.treeshake) {
|
18888 | let treeshakingPass = 1;
|
18889 | do {
|
18890 | timeStart(`treeshaking pass ${treeshakingPass}`, 3);
|
18891 | this.needsTreeshakingPass = false;
|
18892 | for (const module of this.modules) {
|
18893 | if (module.isExecuted) {
|
18894 | if (module.info.hasModuleSideEffects === 'no-treeshake') {
|
18895 | module.includeAllInBundle();
|
18896 | }
|
18897 | else {
|
18898 | module.include();
|
18899 | }
|
18900 | }
|
18901 | }
|
18902 | timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
|
18903 | } while (this.needsTreeshakingPass);
|
18904 | }
|
18905 | else {
|
18906 | for (const module of this.modules)
|
18907 | module.includeAllInBundle();
|
18908 | }
|
18909 | for (const externalModule of this.externalModules)
|
18910 | externalModule.warnUnusedImports();
|
18911 | for (const module of this.implicitEntryModules) {
|
18912 | for (const dependant of module.implicitlyLoadedAfter) {
|
18913 | if (!(dependant.info.isEntry || dependant.isIncluded())) {
|
18914 | error(errImplicitDependantIsNotIncluded(dependant));
|
18915 | }
|
18916 | }
|
18917 | }
|
18918 | }
|
18919 | sortModules() {
|
18920 | const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
|
18921 | for (const cyclePath of cyclePaths) {
|
18922 | this.options.onwarn({
|
18923 | code: 'CIRCULAR_DEPENDENCY',
|
18924 | cycle: cyclePath,
|
18925 | importer: cyclePath[0],
|
18926 | message: `Circular dependency: ${cyclePath.join(' -> ')}`
|
18927 | });
|
18928 | }
|
18929 | this.modules = orderedModules;
|
18930 | for (const module of this.modules) {
|
18931 | module.bindReferences();
|
18932 | }
|
18933 | this.warnForMissingExports();
|
18934 | }
|
18935 | warnForMissingExports() {
|
18936 | for (const module of this.modules) {
|
18937 | for (const importName of Object.keys(module.importDescriptions)) {
|
18938 | const importDescription = module.importDescriptions[importName];
|
18939 | if (importDescription.name !== '*' &&
|
18940 | !importDescription.module.getVariableForExportName(importDescription.name)) {
|
18941 | module.warn({
|
18942 | code: 'NON_EXISTENT_EXPORT',
|
18943 | message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
|
18944 | name: importDescription.name,
|
18945 | source: importDescription.module.id
|
18946 | }, importDescription.start);
|
18947 | }
|
18948 | }
|
18949 | }
|
18950 | }
|
18951 | }
|
18952 |
|
18953 | function createCommonjsModule(fn, basedir, module) {
|
18954 | return module = {
|
18955 | path: basedir,
|
18956 | exports: {},
|
18957 | require: function (path, base) {
|
18958 | return commonjsRequire();
|
18959 | }
|
18960 | }, fn(module, module.exports), module.exports;
|
18961 | }
|
18962 |
|
18963 | function getAugmentedNamespace(n) {
|
18964 | if (n.__esModule) return n;
|
18965 | var a = Object.defineProperty({}, '__esModule', {value: true});
|
18966 | Object.keys(n).forEach(function (k) {
|
18967 | var d = Object.getOwnPropertyDescriptor(n, k);
|
18968 | Object.defineProperty(a, k, d.get ? d : {
|
18969 | enumerable: true,
|
18970 | get: function () {
|
18971 | return n[k];
|
18972 | }
|
18973 | });
|
18974 | });
|
18975 | return a;
|
18976 | }
|
18977 |
|
18978 | function commonjsRequire () {
|
18979 | throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
|
18980 | }
|
18981 |
|
18982 | var require$$0 = getAugmentedNamespace(acorn);
|
18983 |
|
18984 | const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
|
18985 |
|
18986 | const getAcorn = Parser => {
|
18987 | if (Parser.acorn) return Parser.acorn
|
18988 |
|
18989 | const acorn = require$$0;
|
18990 |
|
18991 | if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
|
18992 | throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
|
18993 | }
|
18994 |
|
18995 |
|
18996 |
|
18997 | for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
|
18998 | if (cur !== acorn.Parser) {
|
18999 | throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
|
19000 | }
|
19001 | }
|
19002 | return acorn
|
19003 | };
|
19004 |
|
19005 | var acornPrivateClassElements = function(Parser) {
|
19006 |
|
19007 | if (Parser.prototype.parsePrivateName) {
|
19008 | return Parser
|
19009 | }
|
19010 |
|
19011 | const acorn = getAcorn(Parser);
|
19012 |
|
19013 | Parser = class extends Parser {
|
19014 | _branch() {
|
19015 | this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
|
19016 | this.__branch.end = this.end;
|
19017 | this.__branch.pos = this.pos;
|
19018 | this.__branch.type = this.type;
|
19019 | this.__branch.value = this.value;
|
19020 | this.__branch.containsEsc = this.containsEsc;
|
19021 | return this.__branch
|
19022 | }
|
19023 |
|
19024 | parsePrivateClassElementName(element) {
|
19025 | element.computed = false;
|
19026 | element.key = this.parsePrivateName();
|
19027 | if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
|
19028 | const accept = {get: "set", set: "get"}[element.kind];
|
19029 | const privateBoundNames = this._privateBoundNames;
|
19030 | if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
|
19031 | this.raise(element.start, "Duplicate private element");
|
19032 | }
|
19033 | privateBoundNames[element.key.name] = element.kind || true;
|
19034 | delete this._unresolvedPrivateNames[element.key.name];
|
19035 | return element.key
|
19036 | }
|
19037 |
|
19038 | parsePrivateName() {
|
19039 | const node = this.startNode();
|
19040 | node.name = this.value;
|
19041 | this.next();
|
19042 | this.finishNode(node, "PrivateName");
|
19043 | if (this.options.allowReserved == "never") this.checkUnreserved(node);
|
19044 | return node
|
19045 | }
|
19046 |
|
19047 |
|
19048 | getTokenFromCode(code) {
|
19049 | if (code === 35) {
|
19050 | ++this.pos;
|
19051 | const word = this.readWord1();
|
19052 | return this.finishToken(this.privateNameToken, word)
|
19053 | }
|
19054 | return super.getTokenFromCode(code)
|
19055 | }
|
19056 |
|
19057 |
|
19058 | parseClass(node, isStatement) {
|
19059 | const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
|
19060 | this._outerPrivateBoundNames = this._privateBoundNames;
|
19061 | this._privateBoundNames = Object.create(this._privateBoundNames || null);
|
19062 | const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
|
19063 | this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
|
19064 | this._unresolvedPrivateNames = Object.create(null);
|
19065 |
|
19066 | const _return = super.parseClass(node, isStatement);
|
19067 |
|
19068 | const unresolvedPrivateNames = this._unresolvedPrivateNames;
|
19069 | this._privateBoundNames = this._outerPrivateBoundNames;
|
19070 | this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
|
19071 | this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
|
19072 | this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
|
19073 | if (!this._unresolvedPrivateNames) {
|
19074 | const names = Object.keys(unresolvedPrivateNames);
|
19075 | if (names.length) {
|
19076 | names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
|
19077 | this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
|
19078 | }
|
19079 | } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
|
19080 | return _return
|
19081 | }
|
19082 |
|
19083 |
|
19084 | parseClassSuper(node) {
|
19085 | const privateBoundNames = this._privateBoundNames;
|
19086 | this._privateBoundNames = this._outerPrivateBoundNames;
|
19087 | const unresolvedPrivateNames = this._unresolvedPrivateNames;
|
19088 | this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
|
19089 | const _return = super.parseClassSuper(node);
|
19090 | this._privateBoundNames = privateBoundNames;
|
19091 | this._unresolvedPrivateNames = unresolvedPrivateNames;
|
19092 | return _return
|
19093 | }
|
19094 |
|
19095 |
|
19096 | parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
|
19097 | const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
|
19098 | const branch = this._branch();
|
19099 | if (!(
|
19100 | (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
|
19101 | branch.type == this.privateNameToken
|
19102 | )) {
|
19103 | return super.parseSubscript.apply(this, arguments)
|
19104 | }
|
19105 | let optional = false;
|
19106 | if (!this.eat(acorn.tokTypes.dot)) {
|
19107 | this.expect(acorn.tokTypes.questionDot);
|
19108 | optional = true;
|
19109 | }
|
19110 | let node = this.startNodeAt(startPos, startLoc);
|
19111 | node.object = base;
|
19112 | node.computed = false;
|
19113 | if (optionalSupported) {
|
19114 | node.optional = optional;
|
19115 | }
|
19116 | if (this.type == this.privateNameToken) {
|
19117 | if (base.type == "Super") {
|
19118 | this.raise(this.start, "Cannot access private element on super");
|
19119 | }
|
19120 | node.property = this.parsePrivateName();
|
19121 | if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
|
19122 | if (!this._unresolvedPrivateNames) {
|
19123 | this.raise(node.property.start, "Usage of undeclared private name");
|
19124 | }
|
19125 | this._unresolvedPrivateNames[node.property.name] = node.property.start;
|
19126 | }
|
19127 | } else {
|
19128 | node.property = this.parseIdent(true);
|
19129 | }
|
19130 | return this.finishNode(node, "MemberExpression")
|
19131 | }
|
19132 |
|
19133 |
|
19134 | parseMaybeUnary(refDestructuringErrors, sawUnary) {
|
19135 | const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
|
19136 | if (_return.operator == "delete") {
|
19137 | if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateName") {
|
19138 | this.raise(_return.start, "Private elements may not be deleted");
|
19139 | }
|
19140 | }
|
19141 | return _return
|
19142 | }
|
19143 | };
|
19144 | Parser.prototype.privateNameToken = new acorn.TokenType("privateName");
|
19145 | return Parser
|
19146 | };
|
19147 |
|
19148 | var acornClassFields = function(Parser) {
|
19149 | const acorn = Parser.acorn || require$$0;
|
19150 | const tt = acorn.tokTypes;
|
19151 |
|
19152 | Parser = acornPrivateClassElements(Parser);
|
19153 | return class extends Parser {
|
19154 | _maybeParseFieldValue(field) {
|
19155 | if (this.eat(tt.eq)) {
|
19156 | const oldInFieldValue = this._inFieldValue;
|
19157 | this._inFieldValue = true;
|
19158 | if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
|
19159 | field.value = this.parseAwait();
|
19160 | } else field.value = this.parseExpression();
|
19161 | this._inFieldValue = oldInFieldValue;
|
19162 | } else field.value = null;
|
19163 | }
|
19164 |
|
19165 |
|
19166 | parseClassElement(_constructorAllowsSuper) {
|
19167 | if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateNameToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
|
19168 | const branch = this._branch();
|
19169 | if (branch.type == tt.bracketL) {
|
19170 | let count = 0;
|
19171 | do {
|
19172 | if (branch.eat(tt.bracketL)) ++count;
|
19173 | else if (branch.eat(tt.bracketR)) --count;
|
19174 | else branch.next();
|
19175 | } while (count > 0)
|
19176 | } else branch.next(true);
|
19177 | let isField = branch.type == tt.eq || branch.type == tt.semi;
|
19178 | if (!isField && branch.canInsertSemicolon()) {
|
19179 | isField = branch.type != tt.parenL;
|
19180 | }
|
19181 | if (isField) {
|
19182 | const node = this.startNode();
|
19183 | if (this.type == this.privateNameToken) {
|
19184 | this.parsePrivateClassElementName(node);
|
19185 | } else {
|
19186 | this.parsePropertyName(node);
|
19187 | }
|
19188 | if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
|
19189 | (node.key.type === "Literal" && node.key.value === "constructor")) {
|
19190 | this.raise(node.key.start, "Classes may not have a field called constructor");
|
19191 | }
|
19192 | this.enterScope(64 | 2 | 1);
|
19193 | this._maybeParseFieldValue(node);
|
19194 | this.exitScope();
|
19195 | this.finishNode(node, "FieldDefinition");
|
19196 | this.semicolon();
|
19197 | return node
|
19198 | }
|
19199 | }
|
19200 |
|
19201 | return super.parseClassElement.apply(this, arguments)
|
19202 | }
|
19203 |
|
19204 |
|
19205 | parseIdent(liberal, isBinding) {
|
19206 | const ident = super.parseIdent(liberal, isBinding);
|
19207 | if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
|
19208 | return ident
|
19209 | }
|
19210 | }
|
19211 | };
|
19212 |
|
19213 | function withoutAcornBigInt(acorn, Parser) {
|
19214 | return class extends Parser {
|
19215 | readInt(radix, len) {
|
19216 |
|
19217 |
|
19218 | if (len != null) return super.readInt(radix, len)
|
19219 |
|
19220 | let start = this.pos, total = 0, acceptUnderscore = false;
|
19221 | for (;;) {
|
19222 | let code = this.input.charCodeAt(this.pos), val;
|
19223 | if (code >= 97) val = code - 97 + 10;
|
19224 | else if (code == 95) {
|
19225 | if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
|
19226 | ++this.pos;
|
19227 | acceptUnderscore = false;
|
19228 | continue
|
19229 | } else if (code >= 65) val = code - 65 + 10;
|
19230 | else if (code >= 48 && code <= 57) val = code - 48;
|
19231 | else val = Infinity;
|
19232 | if (val >= radix) break
|
19233 | ++this.pos;
|
19234 | total = total * radix + val;
|
19235 | acceptUnderscore = true;
|
19236 | }
|
19237 | if (this.pos === start) return null
|
19238 | if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
|
19239 |
|
19240 | return total
|
19241 | }
|
19242 |
|
19243 | readNumber(startsWithDot) {
|
19244 | const token = super.readNumber(startsWithDot);
|
19245 | let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
|
19246 | const stripped = this.getNumberInput(this.start, this.end);
|
19247 | if (stripped.length < this.end - this.start) {
|
19248 | if (octal) this.raise(this.start, "Invalid number");
|
19249 | this.value = parseFloat(stripped);
|
19250 | }
|
19251 | return token
|
19252 | }
|
19253 |
|
19254 |
|
19255 | getNumberInput(start, end) {
|
19256 | return this.input.slice(start, end).replace(/_/g, "")
|
19257 | }
|
19258 | }
|
19259 | }
|
19260 |
|
19261 | function withAcornBigInt(acorn, Parser) {
|
19262 | return class extends Parser {
|
19263 | readInt(radix, len) {
|
19264 |
|
19265 |
|
19266 | if (len != null) return super.readInt(radix, len)
|
19267 |
|
19268 | let start = this.pos, total = 0, acceptUnderscore = false;
|
19269 | for (;;) {
|
19270 | let code = this.input.charCodeAt(this.pos), val;
|
19271 | if (code >= 97) val = code - 97 + 10;
|
19272 | else if (code == 95) {
|
19273 | if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
|
19274 | ++this.pos;
|
19275 | acceptUnderscore = false;
|
19276 | continue
|
19277 | } else if (code >= 65) val = code - 65 + 10;
|
19278 | else if (code >= 48 && code <= 57) val = code - 48;
|
19279 | else val = Infinity;
|
19280 | if (val >= radix) break
|
19281 | ++this.pos;
|
19282 | total = total * radix + val;
|
19283 | acceptUnderscore = true;
|
19284 | }
|
19285 | if (this.pos === start) return null
|
19286 | if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
|
19287 |
|
19288 | return total
|
19289 | }
|
19290 |
|
19291 | readNumber(startsWithDot) {
|
19292 | let start = this.pos;
|
19293 | if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
|
19294 | let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
|
19295 | let octalLike = false;
|
19296 | if (octal && this.strict) this.raise(start, "Invalid number");
|
19297 | let next = this.input.charCodeAt(this.pos);
|
19298 | if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
|
19299 | let str = this.getNumberInput(start, this.pos);
|
19300 |
|
19301 | let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
|
19302 | ++this.pos;
|
19303 | if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
|
19304 | return this.finishToken(acorn.tokTypes.num, val)
|
19305 | }
|
19306 | if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
|
19307 | octal = false;
|
19308 | octalLike = true;
|
19309 | }
|
19310 | if (next === 46 && !octal) {
|
19311 | ++this.pos;
|
19312 | this.readInt(10);
|
19313 | next = this.input.charCodeAt(this.pos);
|
19314 | }
|
19315 | if ((next === 69 || next === 101) && !octal) {
|
19316 | next = this.input.charCodeAt(++this.pos);
|
19317 | if (next === 43 || next === 45) ++this.pos;
|
19318 | if (this.readInt(10) === null) this.raise(start, "Invalid number");
|
19319 | }
|
19320 | if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
|
19321 | let str = this.getNumberInput(start, this.pos);
|
19322 | if ((octal || octalLike) && str.length < this.pos - start) {
|
19323 | this.raise(start, "Invalid number");
|
19324 | }
|
19325 |
|
19326 | let val = octal ? parseInt(str, 8) : parseFloat(str);
|
19327 | return this.finishToken(acorn.tokTypes.num, val)
|
19328 | }
|
19329 |
|
19330 | parseLiteral(value) {
|
19331 | const ret = super.parseLiteral(value);
|
19332 | if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
|
19333 | return ret
|
19334 | }
|
19335 |
|
19336 | readRadixNumber(radix) {
|
19337 | let start = this.pos;
|
19338 | this.pos += 2;
|
19339 | let val = this.readInt(radix);
|
19340 | if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
|
19341 | if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
|
19342 | let str = this.getNumberInput(start, this.pos);
|
19343 |
|
19344 | val = typeof BigInt !== "undefined" ? BigInt(str) : null;
|
19345 | ++this.pos;
|
19346 | } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
|
19347 | return this.finishToken(acorn.tokTypes.num, val)
|
19348 | }
|
19349 |
|
19350 |
|
19351 | getNumberInput(start, end) {
|
19352 | return this.input.slice(start, end).replace(/_/g, "")
|
19353 | }
|
19354 | }
|
19355 | }
|
19356 |
|
19357 |
|
19358 | function numericSeparator(Parser) {
|
19359 | const acorn = Parser.acorn || require$$0;
|
19360 | const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
|
19361 |
|
19362 | return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
|
19363 | }
|
19364 |
|
19365 | var acornNumericSeparator = numericSeparator;
|
19366 |
|
19367 | var acornStaticClassFeatures = function(Parser) {
|
19368 | const ExtendedParser = acornPrivateClassElements(Parser);
|
19369 |
|
19370 | const acorn = Parser.acorn || require$$0;
|
19371 | const tt = acorn.tokTypes;
|
19372 |
|
19373 | return class extends ExtendedParser {
|
19374 | _maybeParseFieldValue(field) {
|
19375 | if (this.eat(tt.eq)) {
|
19376 | const oldInFieldValue = this._inStaticFieldScope;
|
19377 | this._inStaticFieldScope = this.currentThisScope();
|
19378 | field.value = this.parseExpression();
|
19379 | this._inStaticFieldScope = oldInFieldValue;
|
19380 | } else field.value = null;
|
19381 | }
|
19382 |
|
19383 |
|
19384 | parseClassElement(_constructorAllowsSuper) {
|
19385 | if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
|
19386 | return super.parseClassElement.apply(this, arguments)
|
19387 | }
|
19388 |
|
19389 | const branch = this._branch();
|
19390 | branch.next();
|
19391 | if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateNameToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
|
19392 | return super.parseClassElement.apply(this, arguments)
|
19393 | }
|
19394 | if (branch.type == tt.bracketL) {
|
19395 | let count = 0;
|
19396 | do {
|
19397 | if (branch.eat(tt.bracketL)) ++count;
|
19398 | else if (branch.eat(tt.bracketR)) --count;
|
19399 | else branch.next();
|
19400 | } while (count > 0)
|
19401 | } else branch.next();
|
19402 | if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
|
19403 | return super.parseClassElement.apply(this, arguments)
|
19404 | }
|
19405 |
|
19406 | const node = this.startNode();
|
19407 | node.static = this.eatContextual("static");
|
19408 | if (this.type == this.privateNameToken) {
|
19409 | this.parsePrivateClassElementName(node);
|
19410 | } else {
|
19411 | this.parsePropertyName(node);
|
19412 | }
|
19413 | if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
|
19414 | (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
|
19415 | this.raise(node.key.start, "Classes may not have a field called constructor");
|
19416 | }
|
19417 | if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
|
19418 | this.raise(node.key.start, "Classes may not have a static property named prototype");
|
19419 | }
|
19420 |
|
19421 | this.enterScope(64 | 2 | 1);
|
19422 | this._maybeParseFieldValue(node);
|
19423 | this.exitScope();
|
19424 | this.finishNode(node, "FieldDefinition");
|
19425 | this.semicolon();
|
19426 | return node
|
19427 | }
|
19428 |
|
19429 |
|
19430 | parsePropertyName(prop) {
|
19431 | if (prop.static && this.type == this.privateNameToken) {
|
19432 | this.parsePrivateClassElementName(prop);
|
19433 | } else {
|
19434 | super.parsePropertyName(prop);
|
19435 | }
|
19436 | }
|
19437 |
|
19438 |
|
19439 | parseIdent(liberal, isBinding) {
|
19440 | const ident = super.parseIdent(liberal, isBinding);
|
19441 | if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
|
19442 | this.raise(ident.start, "A static class field initializer may not contain arguments");
|
19443 | }
|
19444 | return ident
|
19445 | }
|
19446 | }
|
19447 | };
|
19448 |
|
19449 | function normalizeInputOptions(config) {
|
19450 | var _a, _b;
|
19451 |
|
19452 |
|
19453 | const unsetOptions = new Set();
|
19454 | const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
|
19455 | const onwarn = getOnwarn(config);
|
19456 | const strictDeprecations = config.strictDeprecations || false;
|
19457 | const options = {
|
19458 | acorn: getAcorn$1(config),
|
19459 | acornInjectPlugins: getAcornInjectPlugins(config),
|
19460 | cache: getCache(config),
|
19461 | context,
|
19462 | experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
|
19463 | external: getIdMatcher(config.external),
|
19464 | inlineDynamicImports: getInlineDynamicImports(config, onwarn, strictDeprecations),
|
19465 | input: getInput(config),
|
19466 | manualChunks: getManualChunks(config, onwarn, strictDeprecations),
|
19467 | moduleContext: getModuleContext(config, context),
|
19468 | onwarn,
|
19469 | perf: config.perf || false,
|
19470 | plugins: ensureArray(config.plugins),
|
19471 | preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
|
19472 | preserveModules: getPreserveModules(config, onwarn, strictDeprecations),
|
19473 | preserveSymlinks: config.preserveSymlinks || false,
|
19474 | shimMissingExports: config.shimMissingExports || false,
|
19475 | strictDeprecations,
|
19476 | treeshake: getTreeshake(config, onwarn, strictDeprecations)
|
19477 | };
|
19478 | warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
|
19479 | return { options, unsetOptions };
|
19480 | }
|
19481 | const getOnwarn = (config) => {
|
19482 | return config.onwarn
|
19483 | ? warning => {
|
19484 | warning.toString = () => {
|
19485 | let str = '';
|
19486 | if (warning.plugin)
|
19487 | str += `(${warning.plugin} plugin) `;
|
19488 | if (warning.loc)
|
19489 | str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
|
19490 | str += warning.message;
|
19491 | return str;
|
19492 | };
|
19493 | config.onwarn(warning, defaultOnWarn);
|
19494 | }
|
19495 | : defaultOnWarn;
|
19496 | };
|
19497 | const getAcorn$1 = (config) => ({
|
19498 | allowAwaitOutsideFunction: true,
|
19499 | ecmaVersion: 'latest',
|
19500 | preserveParens: false,
|
19501 | sourceType: 'module',
|
19502 | ...config.acorn
|
19503 | });
|
19504 | const getAcornInjectPlugins = (config) => [
|
19505 | acornClassFields,
|
19506 | acornStaticClassFeatures,
|
19507 | acornNumericSeparator,
|
19508 | ...ensureArray(config.acornInjectPlugins)
|
19509 | ];
|
19510 | const getCache = (config) => {
|
19511 | var _a;
|
19512 | return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
|
19513 | };
|
19514 | const getIdMatcher = (option) => {
|
19515 | if (option === true) {
|
19516 | return () => true;
|
19517 | }
|
19518 | if (typeof option === 'function') {
|
19519 | return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
|
19520 | }
|
19521 | if (option) {
|
19522 | const ids = new Set();
|
19523 | const matchers = [];
|
19524 | for (const value of ensureArray(option)) {
|
19525 | if (value instanceof RegExp) {
|
19526 | matchers.push(value);
|
19527 | }
|
19528 | else {
|
19529 | ids.add(value);
|
19530 | }
|
19531 | }
|
19532 | return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
|
19533 | }
|
19534 | return () => false;
|
19535 | };
|
19536 | const getInlineDynamicImports = (config, warn, strictDeprecations) => {
|
19537 | const configInlineDynamicImports = config.inlineDynamicImports;
|
19538 | if (configInlineDynamicImports) {
|
19539 | warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
|
19540 | }
|
19541 | return configInlineDynamicImports;
|
19542 | };
|
19543 | const getInput = (config) => {
|
19544 | const configInput = config.input;
|
19545 | return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
|
19546 | };
|
19547 | const getManualChunks = (config, warn, strictDeprecations) => {
|
19548 | const configManualChunks = config.manualChunks;
|
19549 | if (configManualChunks) {
|
19550 | warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
|
19551 | }
|
19552 | return configManualChunks;
|
19553 | };
|
19554 | const getModuleContext = (config, context) => {
|
19555 | const configModuleContext = config.moduleContext;
|
19556 | if (typeof configModuleContext === 'function') {
|
19557 | return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
|
19558 | }
|
19559 | if (configModuleContext) {
|
19560 | const contextByModuleId = Object.create(null);
|
19561 | for (const key of Object.keys(configModuleContext)) {
|
19562 | contextByModuleId[sysPath.resolve(key)] = configModuleContext[key];
|
19563 | }
|
19564 | return id => contextByModuleId[id] || context;
|
19565 | }
|
19566 | return () => context;
|
19567 | };
|
19568 | const getPreserveEntrySignatures = (config, unsetOptions) => {
|
19569 | const configPreserveEntrySignatures = config.preserveEntrySignatures;
|
19570 | if (configPreserveEntrySignatures == null) {
|
19571 | unsetOptions.add('preserveEntrySignatures');
|
19572 | }
|
19573 | return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
|
19574 | };
|
19575 | const getPreserveModules = (config, warn, strictDeprecations) => {
|
19576 | const configPreserveModules = config.preserveModules;
|
19577 | if (configPreserveModules) {
|
19578 | warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
|
19579 | }
|
19580 | return configPreserveModules;
|
19581 | };
|
19582 | const getTreeshake = (config, warn, strictDeprecations) => {
|
19583 | const configTreeshake = config.treeshake;
|
19584 | if (configTreeshake === false) {
|
19585 | return false;
|
19586 | }
|
19587 | if (configTreeshake && configTreeshake !== true) {
|
19588 | if (typeof configTreeshake.pureExternalModules !== 'undefined') {
|
19589 | 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);
|
19590 | }
|
19591 | return {
|
19592 | annotations: configTreeshake.annotations !== false,
|
19593 | moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
|
19594 | propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
|
19595 | tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
|
19596 | unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
|
19597 | };
|
19598 | }
|
19599 | return {
|
19600 | annotations: true,
|
19601 | moduleSideEffects: () => true,
|
19602 | propertyReadSideEffects: true,
|
19603 | tryCatchDeoptimization: true,
|
19604 | unknownGlobalSideEffects: true
|
19605 | };
|
19606 | };
|
19607 | const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
|
19608 | if (typeof moduleSideEffectsOption === 'boolean') {
|
19609 | return () => moduleSideEffectsOption;
|
19610 | }
|
19611 | if (moduleSideEffectsOption === 'no-external') {
|
19612 | return (_id, external) => !external;
|
19613 | }
|
19614 | if (typeof moduleSideEffectsOption === 'function') {
|
19615 | return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
|
19616 | }
|
19617 | if (Array.isArray(moduleSideEffectsOption)) {
|
19618 | const ids = new Set(moduleSideEffectsOption);
|
19619 | return id => ids.has(id);
|
19620 | }
|
19621 | if (moduleSideEffectsOption) {
|
19622 | warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
|
19623 | }
|
19624 | const isPureExternalModule = getIdMatcher(pureExternalModules);
|
19625 | return (id, external) => !(external && isPureExternalModule(id));
|
19626 | };
|
19627 |
|
19628 | function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
|
19629 | var _a, _b, _c, _d, _e, _f, _g;
|
19630 |
|
19631 |
|
19632 | const unsetOptions = new Set(unsetInputOptions);
|
19633 | const compact = config.compact || false;
|
19634 | const format = getFormat(config);
|
19635 | const inlineDynamicImports = getInlineDynamicImports$1(config, inputOptions);
|
19636 | const preserveModules = getPreserveModules$1(config, inlineDynamicImports, inputOptions);
|
19637 | const file = getFile(config, preserveModules, inputOptions);
|
19638 | const outputOptions = {
|
19639 | amd: getAmd(config),
|
19640 | assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
|
19641 | banner: getAddon(config, 'banner'),
|
19642 | chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
|
19643 | compact,
|
19644 | dir: getDir(config, file),
|
19645 | dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
|
19646 | entryFileNames: getEntryFileNames(config, unsetOptions),
|
19647 | esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
|
19648 | exports: getExports(config, unsetOptions),
|
19649 | extend: config.extend || false,
|
19650 | externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
|
19651 | file,
|
19652 | footer: getAddon(config, 'footer'),
|
19653 | format,
|
19654 | freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
|
19655 | globals: config.globals || {},
|
19656 | hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
|
19657 | indent: getIndent(config, compact),
|
19658 | inlineDynamicImports,
|
19659 | interop: getInterop(config, inputOptions),
|
19660 | intro: getAddon(config, 'intro'),
|
19661 | manualChunks: getManualChunks$1(config, inlineDynamicImports, preserveModules, inputOptions),
|
19662 | minifyInternalExports: getMinifyInternalExports(config, format, compact),
|
19663 | name: config.name,
|
19664 | namespaceToStringTag: config.namespaceToStringTag || false,
|
19665 | noConflict: config.noConflict || false,
|
19666 | outro: getAddon(config, 'outro'),
|
19667 | paths: config.paths || {},
|
19668 | plugins: ensureArray(config.plugins),
|
19669 | preferConst: config.preferConst || false,
|
19670 | preserveModules,
|
19671 | preserveModulesRoot: getPreserveModulesRoot(config),
|
19672 | sourcemap: config.sourcemap || false,
|
19673 | sourcemapExcludeSources: config.sourcemapExcludeSources || false,
|
19674 | sourcemapFile: config.sourcemapFile,
|
19675 | sourcemapPathTransform: config.sourcemapPathTransform,
|
19676 | strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
|
19677 | systemNullSetters: config.systemNullSetters || false
|
19678 | };
|
19679 | warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
|
19680 | return { options: outputOptions, unsetOptions };
|
19681 | }
|
19682 | const getFile = (config, preserveModules, inputOptions) => {
|
19683 | const file = config.file;
|
19684 | if (typeof file === 'string') {
|
19685 | if (preserveModules) {
|
19686 | return error({
|
19687 | code: 'INVALID_OPTION',
|
19688 | message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
|
19689 | });
|
19690 | }
|
19691 | if (!Array.isArray(inputOptions.input))
|
19692 | return error({
|
19693 | code: 'INVALID_OPTION',
|
19694 | message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
|
19695 | });
|
19696 | }
|
19697 | return file;
|
19698 | };
|
19699 | const getFormat = (config) => {
|
19700 | const configFormat = config.format;
|
19701 | switch (configFormat) {
|
19702 | case undefined:
|
19703 | case 'es':
|
19704 | case 'esm':
|
19705 | case 'module':
|
19706 | return 'es';
|
19707 | case 'cjs':
|
19708 | case 'commonjs':
|
19709 | return 'cjs';
|
19710 | case 'system':
|
19711 | case 'systemjs':
|
19712 | return 'system';
|
19713 | case 'amd':
|
19714 | case 'iife':
|
19715 | case 'umd':
|
19716 | return configFormat;
|
19717 | default:
|
19718 | return error({
|
19719 | message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
|
19720 | url: `https://rollupjs.org/guide/en/#outputformat`
|
19721 | });
|
19722 | }
|
19723 | };
|
19724 | const getInlineDynamicImports$1 = (config, inputOptions) => {
|
19725 | var _a;
|
19726 | const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
|
19727 | false;
|
19728 | const { input } = inputOptions;
|
19729 | if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
|
19730 | return error({
|
19731 | code: 'INVALID_OPTION',
|
19732 | message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
|
19733 | });
|
19734 | }
|
19735 | return inlineDynamicImports;
|
19736 | };
|
19737 | const getPreserveModules$1 = (config, inlineDynamicImports, inputOptions) => {
|
19738 | var _a;
|
19739 | const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
|
19740 | if (preserveModules) {
|
19741 | if (inlineDynamicImports) {
|
19742 | return error({
|
19743 | code: 'INVALID_OPTION',
|
19744 | message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
|
19745 | });
|
19746 | }
|
19747 | if (inputOptions.preserveEntrySignatures === false) {
|
19748 | return error({
|
19749 | code: 'INVALID_OPTION',
|
19750 | message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
|
19751 | });
|
19752 | }
|
19753 | }
|
19754 | return preserveModules;
|
19755 | };
|
19756 | const getPreserveModulesRoot = (config) => {
|
19757 | const preserveModulesRoot = config.preserveModulesRoot;
|
19758 | if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
|
19759 | return undefined;
|
19760 | }
|
19761 | return sysPath.resolve(preserveModulesRoot);
|
19762 | };
|
19763 | const getAmd = (config) => ({
|
19764 | define: 'define',
|
19765 | ...config.amd
|
19766 | });
|
19767 | const getAddon = (config, name) => {
|
19768 | const configAddon = config[name];
|
19769 | if (typeof configAddon === 'function') {
|
19770 | return configAddon;
|
19771 | }
|
19772 | return () => configAddon || '';
|
19773 | };
|
19774 | const getDir = (config, file) => {
|
19775 | const dir = config.dir;
|
19776 | if (typeof dir === 'string' && typeof file === 'string') {
|
19777 | return error({
|
19778 | code: 'INVALID_OPTION',
|
19779 | message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
|
19780 | });
|
19781 | }
|
19782 | return dir;
|
19783 | };
|
19784 | const getDynamicImportFunction = (config, inputOptions) => {
|
19785 | const configDynamicImportFunction = config.dynamicImportFunction;
|
19786 | if (configDynamicImportFunction) {
|
19787 | warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
|
19788 | }
|
19789 | return configDynamicImportFunction;
|
19790 | };
|
19791 | const getEntryFileNames = (config, unsetOptions) => {
|
19792 | const configEntryFileNames = config.entryFileNames;
|
19793 | if (configEntryFileNames == null) {
|
19794 | unsetOptions.add('entryFileNames');
|
19795 | }
|
19796 | return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
|
19797 | };
|
19798 | function getExports(config, unsetOptions) {
|
19799 | const configExports = config.exports;
|
19800 | if (configExports == null) {
|
19801 | unsetOptions.add('exports');
|
19802 | }
|
19803 | else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
|
19804 | return error(errInvalidExportOptionValue(configExports));
|
19805 | }
|
19806 | return configExports || 'auto';
|
19807 | }
|
19808 | const getIndent = (config, compact) => {
|
19809 | if (compact) {
|
19810 | return '';
|
19811 | }
|
19812 | const configIndent = config.indent;
|
19813 | return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
|
19814 | };
|
19815 | const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
|
19816 | const getInterop = (config, inputOptions) => {
|
19817 | const configInterop = config.interop;
|
19818 | const validatedInteropTypes = new Set();
|
19819 | const validateInterop = (interop) => {
|
19820 | if (!validatedInteropTypes.has(interop)) {
|
19821 | validatedInteropTypes.add(interop);
|
19822 | if (!ALLOWED_INTEROP_TYPES.has(interop)) {
|
19823 | return error({
|
19824 | code: 'INVALID_OPTION',
|
19825 | message: `The value ${JSON.stringify(interop)} is not supported for "output.interop". Use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value => JSON.stringify(value)).join(', ')} instead.`,
|
19826 | url: 'https://rollupjs.org/guide/en/#outputinterop'
|
19827 | });
|
19828 | }
|
19829 | if (typeof interop === 'boolean') {
|
19830 | warnDeprecation({
|
19831 | message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
|
19832 | url: 'https://rollupjs.org/guide/en/#outputinterop'
|
19833 | }, false, inputOptions);
|
19834 | }
|
19835 | }
|
19836 | return interop;
|
19837 | };
|
19838 | if (typeof configInterop === 'function') {
|
19839 | const interopPerId = Object.create(null);
|
19840 | let defaultInterop = null;
|
19841 | return id => id === null
|
19842 | ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
|
19843 | : id in interopPerId
|
19844 | ? interopPerId[id]
|
19845 | : validateInterop((interopPerId[id] = configInterop(id)));
|
19846 | }
|
19847 | return configInterop === undefined ? () => true : () => validateInterop(configInterop);
|
19848 | };
|
19849 | const getManualChunks$1 = (config, inlineDynamicImports, preserveModules, inputOptions) => {
|
19850 | const configManualChunks = config.manualChunks || inputOptions.manualChunks;
|
19851 | if (configManualChunks) {
|
19852 | if (inlineDynamicImports) {
|
19853 | return error({
|
19854 | code: 'INVALID_OPTION',
|
19855 | message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
|
19856 | });
|
19857 | }
|
19858 | if (preserveModules) {
|
19859 | return error({
|
19860 | code: 'INVALID_OPTION',
|
19861 | message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
|
19862 | });
|
19863 | }
|
19864 | }
|
19865 | return configManualChunks || {};
|
19866 | };
|
19867 | const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
|
19868 |
|
19869 | function rollup(rawInputOptions) {
|
19870 | return rollupInternal(rawInputOptions, null);
|
19871 | }
|
19872 | async function rollupInternal(rawInputOptions, watcher) {
|
19873 | const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
|
19874 | initialiseTimers(inputOptions);
|
19875 | const graph = new Graph(inputOptions, watcher);
|
19876 |
|
19877 | const useCache = rawInputOptions.cache !== false;
|
19878 | delete inputOptions.cache;
|
19879 | delete rawInputOptions.cache;
|
19880 | timeStart('BUILD', 1);
|
19881 | try {
|
19882 | await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
|
19883 | await graph.build();
|
19884 | }
|
19885 | catch (err) {
|
19886 | const watchFiles = Object.keys(graph.watchFiles);
|
19887 | if (watchFiles.length > 0) {
|
19888 | err.watchFiles = watchFiles;
|
19889 | }
|
19890 | await graph.pluginDriver.hookParallel('buildEnd', [err]);
|
19891 | throw err;
|
19892 | }
|
19893 | await graph.pluginDriver.hookParallel('buildEnd', []);
|
19894 | timeEnd('BUILD', 1);
|
19895 | const result = {
|
19896 | cache: useCache ? graph.getCache() : undefined,
|
19897 | async generate(rawOutputOptions) {
|
19898 | return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
|
19899 | },
|
19900 | watchFiles: Object.keys(graph.watchFiles),
|
19901 | async write(rawOutputOptions) {
|
19902 | return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
|
19903 | }
|
19904 | };
|
19905 | if (inputOptions.perf)
|
19906 | result.getTimings = getTimings;
|
19907 | return result;
|
19908 | }
|
19909 | async function getInputOptions(rawInputOptions, watchMode) {
|
19910 | if (!rawInputOptions) {
|
19911 | throw new Error('You must supply an options object to rollup');
|
19912 | }
|
19913 | const rawPlugins = ensureArray(rawInputOptions.plugins);
|
19914 | const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
|
19915 | normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
|
19916 | return { options, unsetOptions };
|
19917 | }
|
19918 | function applyOptionHook(watchMode) {
|
19919 | return async (inputOptions, plugin) => {
|
19920 | if (plugin.options)
|
19921 | return (plugin.options.call({ meta: { rollupVersion: version, watchMode } }, await inputOptions) || inputOptions);
|
19922 | return inputOptions;
|
19923 | };
|
19924 | }
|
19925 | function normalizePlugins(plugins, anonymousPrefix) {
|
19926 | for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
|
19927 | const plugin = plugins[pluginIndex];
|
19928 | if (!plugin.name) {
|
19929 | plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
|
19930 | }
|
19931 | }
|
19932 | }
|
19933 | async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
|
19934 | const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
|
19935 | const bundle = new Bundle$1(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
|
19936 | const generated = await bundle.generate(isWrite);
|
19937 | if (isWrite) {
|
19938 | if (!outputOptions.dir && !outputOptions.file) {
|
19939 | return error({
|
19940 | code: 'MISSING_OPTION',
|
19941 | message: 'You must specify "output.file" or "output.dir" for the build.'
|
19942 | });
|
19943 | }
|
19944 | await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
|
19945 | await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
|
19946 | }
|
19947 | return createOutput(generated);
|
19948 | }
|
19949 | function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
|
19950 | if (!rawOutputOptions) {
|
19951 | throw new Error('You must supply an options object');
|
19952 | }
|
19953 | const rawPlugins = ensureArray(rawOutputOptions.plugins);
|
19954 | normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
|
19955 | const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
|
19956 | return {
|
19957 | ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
|
19958 | outputPluginDriver
|
19959 | };
|
19960 | }
|
19961 | function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
|
19962 | return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
|
19963 | const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
|
19964 | return {
|
19965 | ...pluginContext,
|
19966 | emitFile: emitError,
|
19967 | setAssetSource: emitError
|
19968 | };
|
19969 | }), inputOptions, unsetInputOptions);
|
19970 | }
|
19971 | function createOutput(outputBundle) {
|
19972 | return {
|
19973 | output: Object.keys(outputBundle)
|
19974 | .map(fileName => outputBundle[fileName])
|
19975 | .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
|
19976 | const fileTypeA = getSortingFileType(outputFileA);
|
19977 | const fileTypeB = getSortingFileType(outputFileB);
|
19978 | if (fileTypeA === fileTypeB)
|
19979 | return 0;
|
19980 | return fileTypeA < fileTypeB ? -1 : 1;
|
19981 | })
|
19982 | };
|
19983 | }
|
19984 | var SortingFileType;
|
19985 | (function (SortingFileType) {
|
19986 | SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
|
19987 | SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
|
19988 | SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
|
19989 | })(SortingFileType || (SortingFileType = {}));
|
19990 | function getSortingFileType(file) {
|
19991 | if (file.type === 'asset') {
|
19992 | return SortingFileType.ASSET;
|
19993 | }
|
19994 | if (file.isEntry) {
|
19995 | return SortingFileType.ENTRY_CHUNK;
|
19996 | }
|
19997 | return SortingFileType.SECONDARY_CHUNK;
|
19998 | }
|
19999 | function writeOutputFile(outputFile, outputOptions) {
|
20000 | const fileName = sysPath.resolve(outputOptions.dir || sysPath.dirname(outputOptions.file), outputFile.fileName);
|
20001 | let writeSourceMapPromise;
|
20002 | let source;
|
20003 | if (outputFile.type === 'asset') {
|
20004 | source = outputFile.source;
|
20005 | }
|
20006 | else {
|
20007 | source = outputFile.code;
|
20008 | if (outputOptions.sourcemap && outputFile.map) {
|
20009 | let url;
|
20010 | if (outputOptions.sourcemap === 'inline') {
|
20011 | url = outputFile.map.toUrl();
|
20012 | }
|
20013 | else {
|
20014 | url = `${sysPath.basename(outputFile.fileName)}.map`;
|
20015 | writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
|
20016 | }
|
20017 | if (outputOptions.sourcemap !== 'hidden') {
|
20018 | source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
|
20019 | }
|
20020 | }
|
20021 | }
|
20022 | return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
|
20023 | }
|
20024 |
|
20025 | class WatchEmitter extends require$$0$1.EventEmitter {
|
20026 | constructor() {
|
20027 | super();
|
20028 |
|
20029 |
|
20030 | this.setMaxListeners(Infinity);
|
20031 | }
|
20032 | close() { }
|
20033 | }
|
20034 | function watch(configs) {
|
20035 | const emitter = new WatchEmitter();
|
20036 | const configArray = ensureArray(configs);
|
20037 | const watchConfigs = configArray.filter(config => config.watch !== false);
|
20038 | if (watchConfigs.length === 0) {
|
20039 | throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
|
20040 | }
|
20041 | loadFsEvents()
|
20042 | .then(() => Promise.resolve().then(function () { return require('./watch.js'); }))
|
20043 | .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
|
20044 | return emitter;
|
20045 | }
|
20046 |
|
20047 | exports.createCommonjsModule = createCommonjsModule;
|
20048 | exports.defaultOnWarn = defaultOnWarn;
|
20049 | exports.ensureArray = ensureArray;
|
20050 | exports.error = error;
|
20051 | exports.fseventsImporter = fseventsImporter;
|
20052 | exports.getAliasName = getAliasName;
|
20053 | exports.getAugmentedNamespace = getAugmentedNamespace;
|
20054 | exports.getOrCreate = getOrCreate;
|
20055 | exports.loadFsEvents = loadFsEvents;
|
20056 | exports.relativeId = relativeId;
|
20057 | exports.rollup = rollup;
|
20058 | exports.rollupInternal = rollupInternal;
|
20059 | exports.version = version;
|
20060 | exports.warnUnknownOptions = warnUnknownOptions;
|
20061 | exports.watch = watch;
|
20062 |
|