UNPKG

224 kBJavaScriptView Raw
1/*
2 Rollup.js v0.21.0
3 Sat Nov 14 2015 11:43:53 GMT-0500 (EST) - commit 111c43f7fa539f2191bdb82e6e1e50085cc1277b
4
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10
11(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
13 typeof define === 'function' && define.amd ? define(['exports'], factory) :
14 factory((global.rollup = {}));
15}(this, function (exports) { 'use strict';
16
17 var babelHelpers = {};
18
19 babelHelpers.classCallCheck = function (instance, Constructor) {
20 if (!(instance instanceof Constructor)) {
21 throw new TypeError("Cannot call a class as a function");
22 }
23 };
24 var Promise = window.Promise;
25
26 // TODO does this all work on windows?
27
28 var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|\/])/;
29
30 function isAbsolute(path) {
31 return absolutePath.test(path);
32 }
33
34 function _basename(path) {
35 return path.split(/(\/|\\)/).pop();
36 }
37
38 function dirname(path) {
39 var match = /(\/|\\)[^\/\\]*$/.exec(path);
40 if (!match) return '.';
41
42 var dir = path.slice(0, -match[0].length);
43
44 // If `dir` is the empty string, we're at root.
45 return dir ? dir : '/';
46 }
47
48 function extname(path) {
49 var match = /\.[^\.]+$/.exec(_basename(path));
50 if (!match) return '';
51 return match[0];
52 }
53
54 function resolve() {
55 for (var _len = arguments.length, paths = Array(_len), _key = 0; _key < _len; _key++) {
56 paths[_key] = arguments[_key];
57 }
58
59 var resolvedParts = paths.shift().split(/[\/\\]/);
60
61 paths.forEach(function (path) {
62 if (isAbsolute(path)) {
63 resolvedParts = path.split(/[\/\\]/);
64 } else {
65 var parts = path.split(/[\/\\]/);
66
67 while (parts[0] === '.' || parts[0] === '..') {
68 var part = parts.shift();
69 if (part === '..') {
70 resolvedParts.pop();
71 }
72 }
73
74 resolvedParts.push.apply(resolvedParts, parts);
75 }
76 });
77
78 return resolvedParts.join('/'); // TODO windows...
79 }
80
81 var nope = function (method) {
82 return 'Cannot use fs.' + method + ' inside browser';
83 };
84
85 var isFile = function () {
86 return false;
87 };
88 var readdirSync = nope('readdirSync');
89 var readFileSync = nope('readFileSync');
90 var writeFile = nope('writeFile');
91
92 var keys = Object.keys;
93
94 function blank() {
95 return Object.create(null);
96 }
97
98 // this looks ridiculous, but it prevents sourcemap tooling from mistaking
99 // this for an actual sourceMappingURL
100 var SOURCEMAPPING_URL = 'sourceMa';
101 SOURCEMAPPING_URL += 'ppingURL';
102
103 var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
104
105 var charToInteger = {};
106 var integerToChar = {};
107
108 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
109 charToInteger[ char ] = i;
110 integerToChar[ i ] = char;
111 });
112
113 function encode ( value ) {
114 var result, i;
115
116 if ( typeof value === 'number' ) {
117 result = encodeInteger( value );
118 } else {
119 result = '';
120 for ( i = 0; i < value.length; i += 1 ) {
121 result += encodeInteger( value[i] );
122 }
123 }
124
125 return result;
126 }
127
128 function encodeInteger ( num ) {
129 var result = '', clamped;
130
131 if ( num < 0 ) {
132 num = ( -num << 1 ) | 1;
133 } else {
134 num <<= 1;
135 }
136
137 do {
138 clamped = num & 31;
139 num >>= 5;
140
141 if ( num > 0 ) {
142 clamped |= 32;
143 }
144
145 result += integerToChar[ clamped ];
146 } while ( num > 0 );
147
148 return result;
149 }
150
151 var babelHelpers_classCallCheck = function (instance, Constructor) {
152 if (!(instance instanceof Constructor)) {
153 throw new TypeError("Cannot call a class as a function");
154 }
155 };
156
157 var _btoa = undefined;
158
159 if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
160 _btoa = window.btoa;
161 } else if (typeof Buffer === 'function') {
162 /* global Buffer */
163 _btoa = function (str) {
164 return new Buffer(str).toString('base64');
165 };
166 } else {
167 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
168 }
169
170 var btoa = _btoa;
171
172 var SourceMap = (function () {
173 function SourceMap(properties) {
174 babelHelpers_classCallCheck(this, SourceMap);
175
176 this.version = 3;
177
178 this.file = properties.file;
179 this.sources = properties.sources;
180 this.sourcesContent = properties.sourcesContent;
181 this.names = properties.names;
182 this.mappings = properties.mappings;
183 }
184
185 SourceMap.prototype.toString = function toString() {
186 return JSON.stringify(this);
187 };
188
189 SourceMap.prototype.toUrl = function toUrl() {
190 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
191 };
192
193 return SourceMap;
194 })();
195
196 function guessIndent(code) {
197 var lines = code.split('\n');
198
199 var tabbed = lines.filter(function (line) {
200 return (/^\t+/.test(line)
201 );
202 });
203 var spaced = lines.filter(function (line) {
204 return (/^ {2,}/.test(line)
205 );
206 });
207
208 if (tabbed.length === 0 && spaced.length === 0) {
209 return null;
210 }
211
212 // More lines tabbed than spaced? Assume tabs, and
213 // default to tabs in the case of a tie (or nothing
214 // to go on)
215 if (tabbed.length >= spaced.length) {
216 return '\t';
217 }
218
219 // Otherwise, we need to guess the multiple
220 var min = spaced.reduce(function (previous, current) {
221 var numSpaces = /^ +/.exec(current)[0].length;
222 return Math.min(numSpaces, previous);
223 }, Infinity);
224
225 return new Array(min + 1).join(' ');
226 }
227
228 function encodeMappings(original, str, mappings, hires, sourcemapLocations, sourceIndex, offsets, names, nameLocations) {
229 // store locations, for fast lookup
230 var lineStart = 0;
231 var locations = original.split('\n').map(function (line) {
232 var start = lineStart;
233 lineStart += line.length + 1; // +1 for the newline
234
235 return start;
236 });
237
238 var inverseMappings = invert(str, mappings);
239
240 var charOffset = 0;
241 var lines = str.split('\n').map(function (line) {
242 var segments = [];
243
244 var char = undefined; // TODO put these inside loop, once we've determined it's safe to do so transpilation-wise
245 var origin = undefined;
246 var lastOrigin = -1;
247 var location = undefined;
248 var nameIndex = undefined;
249
250 var i = undefined;
251
252 var len = line.length;
253 for (i = 0; i < len; i += 1) {
254 char = i + charOffset;
255 origin = inverseMappings[char];
256
257 nameIndex = -1;
258 location = null;
259
260 // if this character has no mapping, but the last one did,
261 // create a new segment
262 if (! ~origin && ~lastOrigin) {
263 location = getLocation(locations, lastOrigin + 1);
264
265 if (lastOrigin + 1 in nameLocations) nameIndex = names.indexOf(nameLocations[lastOrigin + 1]);
266 } else if (~origin && (hires || ~lastOrigin && origin !== lastOrigin + 1 || sourcemapLocations[origin])) {
267 location = getLocation(locations, origin);
268 }
269
270 if (location) {
271 segments.push({
272 generatedCodeColumn: i,
273 sourceIndex: sourceIndex,
274 sourceCodeLine: location.line,
275 sourceCodeColumn: location.column,
276 sourceCodeName: nameIndex
277 });
278 }
279
280 lastOrigin = origin;
281 }
282
283 charOffset += line.length + 1;
284 return segments;
285 });
286
287 offsets.sourceIndex = offsets.sourceIndex || 0;
288 offsets.sourceCodeLine = offsets.sourceCodeLine || 0;
289 offsets.sourceCodeColumn = offsets.sourceCodeColumn || 0;
290 offsets.sourceCodeName = offsets.sourceCodeName || 0;
291
292 var encoded = lines.map(function (segments) {
293 var generatedCodeColumn = 0;
294
295 return segments.map(function (segment) {
296 var arr = [segment.generatedCodeColumn - generatedCodeColumn, segment.sourceIndex - offsets.sourceIndex, segment.sourceCodeLine - offsets.sourceCodeLine, segment.sourceCodeColumn - offsets.sourceCodeColumn];
297
298 generatedCodeColumn = segment.generatedCodeColumn;
299 offsets.sourceIndex = segment.sourceIndex;
300 offsets.sourceCodeLine = segment.sourceCodeLine;
301 offsets.sourceCodeColumn = segment.sourceCodeColumn;
302
303 if (~segment.sourceCodeName) {
304 arr.push(segment.sourceCodeName - offsets.sourceCodeName);
305 offsets.sourceCodeName = segment.sourceCodeName;
306 }
307
308 return encode(arr);
309 }).join(',');
310 }).join(';');
311
312 return encoded;
313 }
314
315 function invert(str, mappings) {
316 var inverted = new Uint32Array(str.length);
317
318 // initialise everything to -1
319 var i = str.length;
320 while (i--) {
321 inverted[i] = -1;
322 }
323
324 // then apply the actual mappings
325 i = mappings.length;
326 while (i--) {
327 if (~mappings[i]) {
328 inverted[mappings[i]] = i;
329 }
330 }
331
332 return inverted;
333 }
334
335 function getLocation(locations, char) {
336 var i = locations.length;
337 while (i--) {
338 if (locations[i] <= char) {
339 return {
340 line: i,
341 column: char - locations[i]
342 };
343 }
344 }
345
346 throw new Error('Character out of bounds');
347 }
348
349 function getRelativePath(from, to) {
350 var fromParts = from.split(/[\/\\]/);
351 var toParts = to.split(/[\/\\]/);
352
353 fromParts.pop(); // get dirname
354
355 while (fromParts[0] === toParts[0]) {
356 fromParts.shift();
357 toParts.shift();
358 }
359
360 if (fromParts.length) {
361 var i = fromParts.length;
362 while (i--) fromParts[i] = '..';
363 }
364
365 return fromParts.concat(toParts).join('/');
366 }
367
368 var warned = false;
369
370 var MagicString = (function () {
371 function MagicString(string) {
372 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
373 babelHelpers_classCallCheck(this, MagicString);
374
375 Object.defineProperties(this, {
376 original: { writable: true, value: string },
377 str: { writable: true, value: string },
378 mappings: { writable: true, value: initMappings(string.length) },
379 filename: { writable: true, value: options.filename },
380 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
381 sourcemapLocations: { writable: true, value: {} },
382 nameLocations: { writable: true, value: {} },
383 indentStr: { writable: true, value: guessIndent(string) }
384 });
385 }
386
387 MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
388 this.sourcemapLocations[char] = true;
389 };
390
391 MagicString.prototype.append = function append(content) {
392 if (typeof content !== 'string') {
393 throw new TypeError('appended content must be a string');
394 }
395
396 this.str += content;
397 return this;
398 };
399
400 MagicString.prototype.clone = function clone() {
401 var clone = new MagicString(this.original, { filename: this.filename });
402 clone.str = this.str;
403
404 var i = clone.mappings.length;
405 while (i--) {
406 clone.mappings[i] = this.mappings[i];
407 }
408
409 if (this.indentExclusionRanges) {
410 clone.indentExclusionRanges = typeof this.indentExclusionRanges[0] === 'number' ? [this.indentExclusionRanges[0], this.indentExclusionRanges[1]] : this.indentExclusionRanges.map(function (range) {
411 return [range.start, range.end];
412 });
413 }
414
415 Object.keys(this.sourcemapLocations).forEach(function (loc) {
416 clone.sourcemapLocations[loc] = true;
417 });
418
419 return clone;
420 };
421
422 MagicString.prototype.generateMap = function generateMap(options) {
423 var _this = this;
424
425 options = options || {};
426
427 var names = [];
428 Object.keys(this.nameLocations).forEach(function (location) {
429 var name = _this.nameLocations[location];
430 if (! ~names.indexOf(name)) names.push(name);
431 });
432
433 return new SourceMap({
434 file: options.file ? options.file.split(/[\/\\]/).pop() : null,
435 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
436 sourcesContent: options.includeContent ? [this.original] : [null],
437 names: names,
438 mappings: this.getMappings(options.hires, 0, {}, names)
439 });
440 };
441
442 MagicString.prototype.getIndentString = function getIndentString() {
443 return this.indentStr === null ? '\t' : this.indentStr;
444 };
445
446 MagicString.prototype.getMappings = function getMappings(hires, sourceIndex, offsets, names) {
447 return encodeMappings(this.original, this.str, this.mappings, hires, this.sourcemapLocations, sourceIndex, offsets, names, this.nameLocations);
448 };
449
450 MagicString.prototype.indent = function indent(indentStr, options) {
451 var _this2 = this;
452
453 var mappings = this.mappings;
454 var reverseMappings = reverse(mappings, this.str.length);
455 var pattern = /^[^\r\n]/gm;
456
457 if (typeof indentStr === 'object') {
458 options = indentStr;
459 indentStr = undefined;
460 }
461
462 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
463
464 if (indentStr === '') return this; // noop
465
466 options = options || {};
467
468 // Process exclusion ranges
469 var exclusions = undefined;
470
471 if (options.exclude) {
472 exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
473
474 exclusions = exclusions.map(function (range) {
475 var rangeStart = _this2.locate(range[0]);
476 var rangeEnd = _this2.locate(range[1]);
477
478 if (rangeStart === null || rangeEnd === null) {
479 throw new Error('Cannot use indices of replaced characters as exclusion ranges');
480 }
481
482 return [rangeStart, rangeEnd];
483 });
484
485 exclusions.sort(function (a, b) {
486 return a[0] - b[0];
487 });
488
489 // check for overlaps
490 lastEnd = -1;
491 exclusions.forEach(function (range) {
492 if (range[0] < lastEnd) {
493 throw new Error('Exclusion ranges cannot overlap');
494 }
495
496 lastEnd = range[1];
497 });
498 }
499
500 var indentStart = options.indentStart !== false;
501 var inserts = [];
502
503 if (!exclusions) {
504 this.str = this.str.replace(pattern, function (match, index) {
505 if (!indentStart && index === 0) {
506 return match;
507 }
508
509 inserts.push(index);
510 return indentStr + match;
511 });
512 } else {
513 this.str = this.str.replace(pattern, function (match, index) {
514 if (!indentStart && index === 0 || isExcluded(index - 1)) {
515 return match;
516 }
517
518 inserts.push(index);
519 return indentStr + match;
520 });
521 }
522
523 var adjustments = inserts.map(function (index) {
524 var origin = undefined;
525
526 do {
527 origin = reverseMappings[index++];
528 } while (! ~origin && index < _this2.str.length);
529
530 return origin;
531 });
532
533 var i = adjustments.length;
534 var lastEnd = this.mappings.length;
535 while (i--) {
536 adjust(this.mappings, adjustments[i], lastEnd, (i + 1) * indentStr.length);
537 lastEnd = adjustments[i];
538 }
539
540 return this;
541
542 function isExcluded(index) {
543 var i = exclusions.length;
544 var range = undefined;
545
546 while (i--) {
547 range = exclusions[i];
548
549 if (range[1] < index) {
550 return false;
551 }
552
553 if (range[0] <= index) {
554 return true;
555 }
556 }
557 }
558 };
559
560 MagicString.prototype.insert = function insert(index, content) {
561 if (typeof content !== 'string') {
562 throw new TypeError('inserted content must be a string');
563 }
564
565 if (index === this.original.length) {
566 this.append(content);
567 } else {
568 var mapped = this.locate(index);
569
570 if (mapped === null) {
571 throw new Error('Cannot insert at replaced character index: ' + index);
572 }
573
574 this.str = this.str.substr(0, mapped) + content + this.str.substr(mapped);
575 adjust(this.mappings, index, this.mappings.length, content.length);
576 }
577
578 return this;
579 };
580
581 // get current location of character in original string
582
583 MagicString.prototype.locate = function locate(character) {
584 if (character < 0 || character > this.mappings.length) {
585 throw new Error('Character is out of bounds');
586 }
587
588 var loc = this.mappings[character];
589 return ~loc ? loc : null;
590 };
591
592 MagicString.prototype.locateOrigin = function locateOrigin(character) {
593 if (character < 0 || character >= this.str.length) {
594 throw new Error('Character is out of bounds');
595 }
596
597 var i = this.mappings.length;
598 while (i--) {
599 if (this.mappings[i] === character) {
600 return i;
601 }
602 }
603
604 return null;
605 };
606
607 MagicString.prototype.overwrite = function overwrite(start, end, content, storeName) {
608 if (typeof content !== 'string') {
609 throw new TypeError('replacement content must be a string');
610 }
611
612 var firstChar = this.locate(start);
613 var lastChar = this.locate(end - 1);
614
615 if (firstChar === null || lastChar === null) {
616 throw new Error('Cannot overwrite the same content twice: \'' + this.original.slice(start, end).replace(/\n/g, '\\n') + '\'');
617 }
618
619 if (firstChar > lastChar + 1) {
620 throw new Error('BUG! First character mapped to a position after the last character: ' + '[' + start + ', ' + end + '] -> [' + firstChar + ', ' + (lastChar + 1) + ']');
621 }
622
623 if (storeName) {
624 this.nameLocations[start] = this.original.slice(start, end);
625 }
626
627 this.str = this.str.substr(0, firstChar) + content + this.str.substring(lastChar + 1);
628
629 var d = content.length - (lastChar + 1 - firstChar);
630
631 blank$1(this.mappings, start, end);
632 adjust(this.mappings, end, this.mappings.length, d);
633 return this;
634 };
635
636 MagicString.prototype.prepend = function prepend(content) {
637 this.str = content + this.str;
638 adjust(this.mappings, 0, this.mappings.length, content.length);
639 return this;
640 };
641
642 MagicString.prototype.remove = function remove(start, end) {
643 if (start < 0 || end > this.mappings.length) {
644 throw new Error('Character is out of bounds');
645 }
646
647 var currentStart = -1;
648 var currentEnd = -1;
649 for (var i = start; i < end; i += 1) {
650 var loc = this.mappings[i];
651
652 if (~loc) {
653 if (! ~currentStart) currentStart = loc;
654
655 currentEnd = loc + 1;
656 this.mappings[i] = -1;
657 }
658 }
659
660 this.str = this.str.slice(0, currentStart) + this.str.slice(currentEnd);
661
662 adjust(this.mappings, end, this.mappings.length, currentStart - currentEnd);
663 return this;
664 };
665
666 MagicString.prototype.replace = function replace(start, end, content) {
667 if (!warned) {
668 console.warn('magicString.replace(...) is deprecated. Use magicString.overwrite(...) instead');
669 warned = true;
670 }
671
672 return this.overwrite(start, end, content);
673 };
674
675 MagicString.prototype.slice = function slice(start) {
676 var end = arguments.length <= 1 || arguments[1] === undefined ? this.original.length : arguments[1];
677
678 while (start < 0) start += this.original.length;
679 while (end < 0) end += this.original.length;
680
681 var firstChar = this.locate(start);
682 var lastChar = this.locate(end - 1);
683
684 if (firstChar === null || lastChar === null) {
685 throw new Error('Cannot use replaced characters as slice anchors');
686 }
687
688 return this.str.slice(firstChar, lastChar + 1);
689 };
690
691 MagicString.prototype.snip = function snip(start, end) {
692 var clone = this.clone();
693 clone.remove(0, start);
694 clone.remove(end, clone.original.length);
695
696 return clone;
697 };
698
699 MagicString.prototype.toString = function toString() {
700 return this.str;
701 };
702
703 MagicString.prototype.trimLines = function trimLines() {
704 return this.trim('[\\r\\n]');
705 };
706
707 MagicString.prototype.trim = function trim(charType) {
708 return this.trimStart(charType).trimEnd(charType);
709 };
710
711 MagicString.prototype.trimEnd = function trimEnd(charType) {
712 var _this3 = this;
713
714 var rx = new RegExp((charType || '\\s') + '+$');
715
716 this.str = this.str.replace(rx, function (trailing, index, str) {
717 var strLength = str.length;
718 var length = trailing.length;
719
720 var chars = [];
721
722 var i = strLength;
723 while (i-- > strLength - length) {
724 chars.push(_this3.locateOrigin(i));
725 }
726
727 i = chars.length;
728 while (i--) {
729 if (chars[i] !== null) {
730 _this3.mappings[chars[i]] = -1;
731 }
732 }
733
734 return '';
735 });
736
737 return this;
738 };
739
740 MagicString.prototype.trimStart = function trimStart(charType) {
741 var _this4 = this;
742
743 var rx = new RegExp('^' + (charType || '\\s') + '+');
744
745 this.str = this.str.replace(rx, function (leading) {
746 var length = leading.length;
747
748 var chars = [];
749 var adjustmentStart = 0;
750
751 var i = length;
752 while (i--) {
753 chars.push(_this4.locateOrigin(i));
754 }
755
756 i = chars.length;
757 while (i--) {
758 if (chars[i] !== null) {
759 _this4.mappings[chars[i]] = -1;
760 adjustmentStart += 1;
761 }
762 }
763
764 adjust(_this4.mappings, adjustmentStart, _this4.mappings.length, -length);
765
766 return '';
767 });
768
769 return this;
770 };
771
772 return MagicString;
773 })();
774
775 function adjust(mappings, start, end, d) {
776 if (!d) return; // replacement is same length as replaced string
777
778 var i = end;
779 while (i-- > start) {
780 if (~mappings[i]) {
781 mappings[i] += d;
782 }
783 }
784 }
785
786 function initMappings(i) {
787 var mappings = new Uint32Array(i);
788
789 while (i--) mappings[i] = i;
790 return mappings;
791 }
792
793 function blank$1(mappings, start, i) {
794 while (i-- > start) mappings[i] = -1;
795 }
796
797 function reverse(mappings, i) {
798 var result = new Uint32Array(i);
799
800 while (i--) {
801 result[i] = -1;
802 }
803
804 var location = undefined;
805 i = mappings.length;
806 while (i--) {
807 location = mappings[i];
808
809 if (~location) {
810 result[location] = i;
811 }
812 }
813
814 return result;
815 }
816
817 var hasOwnProp = Object.prototype.hasOwnProperty;
818
819 var Bundle$1 = (function () {
820 function Bundle() {
821 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
822 babelHelpers_classCallCheck(this, Bundle);
823
824 this.intro = options.intro || '';
825 this.outro = options.outro || '';
826 this.separator = options.separator !== undefined ? options.separator : '\n';
827
828 this.sources = [];
829
830 this.uniqueSources = [];
831 this.uniqueSourceIndexByFilename = {};
832 }
833
834 Bundle.prototype.addSource = function addSource(source) {
835 if (source instanceof MagicString) {
836 return this.addSource({
837 content: source,
838 filename: source.filename,
839 separator: this.separator
840 });
841 }
842
843 if (typeof source !== 'object' || !source.content) {
844 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
845 }
846
847 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
848 if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
849 });
850
851 if (source.separator === undefined) {
852 // TODO there's a bunch of this sort of thing, needs cleaning up
853 source.separator = this.separator;
854 }
855
856 if (source.filename) {
857 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
858 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
859 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
860 } else {
861 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
862 if (source.content.original !== uniqueSource.content) {
863 throw new Error('Illegal source: same filename (' + source.filename + '), different contents');
864 }
865 }
866 }
867
868 this.sources.push(source);
869 return this;
870 };
871
872 Bundle.prototype.append = function append(str, options) {
873 this.addSource({
874 content: new MagicString(str),
875 separator: options && options.separator || ''
876 });
877
878 return this;
879 };
880
881 Bundle.prototype.clone = function clone() {
882 var bundle = new Bundle({
883 intro: this.intro,
884 outro: this.outro,
885 separator: this.separator
886 });
887
888 this.sources.forEach(function (source) {
889 bundle.addSource({
890 filename: source.filename,
891 content: source.content.clone(),
892 separator: source.separator
893 });
894 });
895
896 return bundle;
897 };
898
899 Bundle.prototype.generateMap = function generateMap(options) {
900 var _this = this;
901
902 var offsets = {};
903
904 var names = [];
905 this.sources.forEach(function (source) {
906 Object.keys(source.content.nameLocations).forEach(function (location) {
907 var name = source.content.nameLocations[location];
908 if (! ~names.indexOf(name)) names.push(name);
909 });
910 });
911
912 var encoded = getSemis(this.intro) + this.sources.map(function (source, i) {
913 var prefix = i > 0 ? getSemis(source.separator) || ',' : '';
914 var mappings = undefined;
915
916 // we don't bother encoding sources without a filename
917 if (!source.filename) {
918 mappings = getSemis(source.content.toString());
919 } else {
920 var sourceIndex = _this.uniqueSourceIndexByFilename[source.filename];
921 mappings = source.content.getMappings(options.hires, sourceIndex, offsets, names);
922 }
923
924 return prefix + mappings;
925 }).join('') + getSemis(this.outro);
926
927 return new SourceMap({
928 file: options.file ? options.file.split(/[\/\\]/).pop() : null,
929 sources: this.uniqueSources.map(function (source) {
930 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
931 }),
932 sourcesContent: this.uniqueSources.map(function (source) {
933 return options.includeContent ? source.content : null;
934 }),
935 names: names,
936 mappings: encoded
937 });
938 };
939
940 Bundle.prototype.getIndentString = function getIndentString() {
941 var indentStringCounts = {};
942
943 this.sources.forEach(function (source) {
944 var indentStr = source.content.indentStr;
945
946 if (indentStr === null) return;
947
948 if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
949 indentStringCounts[indentStr] += 1;
950 });
951
952 return Object.keys(indentStringCounts).sort(function (a, b) {
953 return indentStringCounts[a] - indentStringCounts[b];
954 })[0] || '\t';
955 };
956
957 Bundle.prototype.indent = function indent(indentStr) {
958 var _this2 = this;
959
960 if (!arguments.length) {
961 indentStr = this.getIndentString();
962 }
963
964 if (indentStr === '') return this; // noop
965
966 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
967
968 this.sources.forEach(function (source, i) {
969 var separator = source.separator !== undefined ? source.separator : _this2.separator;
970 var indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
971
972 source.content.indent(indentStr, {
973 exclude: source.indentExclusionRanges,
974 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
975 });
976
977 trailingNewline = source.content.str.slice(0, -1) === '\n';
978 });
979
980 if (this.intro) {
981 this.intro = indentStr + this.intro.replace(/^[^\n]/gm, function (match, index) {
982 return index > 0 ? indentStr + match : match;
983 });
984 }
985
986 this.outro = this.outro.replace(/^[^\n]/gm, indentStr + '$&');
987
988 return this;
989 };
990
991 Bundle.prototype.prepend = function prepend(str) {
992 this.intro = str + this.intro;
993 return this;
994 };
995
996 Bundle.prototype.toString = function toString() {
997 var _this3 = this;
998
999 var body = this.sources.map(function (source, i) {
1000 var separator = source.separator !== undefined ? source.separator : _this3.separator;
1001 var str = (i > 0 ? separator : '') + source.content.toString();
1002
1003 return str;
1004 }).join('');
1005
1006 return this.intro + body + this.outro;
1007 };
1008
1009 Bundle.prototype.trimLines = function trimLines() {
1010 return this.trim('[\\r\\n]');
1011 };
1012
1013 Bundle.prototype.trim = function trim(charType) {
1014 return this.trimStart(charType).trimEnd(charType);
1015 };
1016
1017 Bundle.prototype.trimStart = function trimStart(charType) {
1018 var rx = new RegExp('^' + (charType || '\\s') + '+');
1019 this.intro = this.intro.replace(rx, '');
1020
1021 if (!this.intro) {
1022 var source = undefined; // TODO put inside loop if safe
1023 var i = 0;
1024
1025 do {
1026 source = this.sources[i];
1027
1028 if (!source) {
1029 this.outro = this.outro.replace(rx, '');
1030 break;
1031 }
1032
1033 source.content.trimStart();
1034 i += 1;
1035 } while (source.content.str === '');
1036 }
1037
1038 return this;
1039 };
1040
1041 Bundle.prototype.trimEnd = function trimEnd(charType) {
1042 var rx = new RegExp((charType || '\\s') + '+$');
1043 this.outro = this.outro.replace(rx, '');
1044
1045 if (!this.outro) {
1046 var source = undefined;
1047 var i = this.sources.length - 1;
1048
1049 do {
1050 source = this.sources[i];
1051
1052 if (!source) {
1053 this.intro = this.intro.replace(rx, '');
1054 break;
1055 }
1056
1057 source.content.trimEnd(charType);
1058 i -= 1;
1059 } while (source.content.str === '');
1060 }
1061
1062 return this;
1063 };
1064
1065 return Bundle;
1066 })();
1067
1068 function getSemis(str) {
1069 return new Array(str.split('\n').length).join(';');
1070 }
1071
1072 MagicString.Bundle = Bundle$1;
1073
1074 // Return the first non-falsy result from an array of
1075 // maybe-sync, maybe-promise-returning functions
1076
1077 function first$1(candidates) {
1078 return function () {
1079 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
1080 args[_key] = arguments[_key];
1081 }
1082
1083 return candidates.reduce(function (promise, candidate) {
1084 return promise.then(function (result) {
1085 return result != null ? result : Promise.resolve(candidate.apply(undefined, args));
1086 });
1087 }, Promise.resolve());
1088 };
1089 }
1090
1091 // This is a trick taken from Esprima. It turns out that, on
1092 // non-Chrome browsers, to check whether a string is in a set, a
1093 // predicate containing a big ugly `switch` statement is faster than
1094 // a regular expression, and on Chrome the two are about on par.
1095 // This function uses `eval` (non-lexical) to produce such a
1096 // predicate from a space-separated string of words.
1097 //
1098 // It starts by sorting the words by length.
1099
1100 // Reserved word lists for various dialects of the language
1101
1102 var reservedWords$1 = {
1103 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",
1104 5: "class enum extends super const export import",
1105 6: "enum",
1106 strict: "implements interface let package private protected public static yield",
1107 strictBind: "eval arguments"
1108 };
1109
1110 // And the keywords
1111
1112 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";
1113
1114 var keywords = {
1115 5: ecma5AndLessKeywords,
1116 6: ecma5AndLessKeywords + " let const class extends export import yield super"
1117 };
1118
1119 // ## Character categories
1120
1121 // Big ugly regular expressions that match characters in the
1122 // whitespace, identifier, and identifier-start categories. These
1123 // are only applied when a character is found to actually have a
1124 // code point above 128.
1125 // Generated by `tools/generate-identifier-regex.js`.
1126
1127 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\u0561-\u0587\u05d0-\u05ea\u05f0-\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\u08a0-\u08b2\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\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\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\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\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-\u13f4\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-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\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-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\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-\uab5f\uab64\uab65\uabc0-\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";
1128 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\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\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\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\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\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\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\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\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\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\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\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-\ufe2d\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
1129
1130 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1131 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1132
1133 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1134
1135 // These are a run-length and offset encoded representation of the
1136 // >0xffff code points that are a valid part of identifiers. The
1137 // offset starts at 0x10000, and each pair of numbers represents an
1138 // offset to the next range, and then a size of the range. They were
1139 // generated by tools/generate-identifier-regex.js
1140 var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 99, 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, 98, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 1, 3071, 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, 4149, 196, 1340, 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, 42710, 42, 4148, 12, 221, 16355, 541];
1141 var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 4305, 6, 792618, 239];
1142
1143 // This has a complexity linear to the value of the code. The
1144 // assumption is that looking up astral identifier characters is
1145 // rare.
1146 function isInAstralSet(code, set) {
1147 var pos = 0x10000;
1148 for (var i = 0; i < set.length; i += 2) {
1149 pos += set[i];
1150 if (pos > code) return false;
1151 pos += set[i + 1];
1152 if (pos >= code) return true;
1153 }
1154 }
1155
1156 // Test whether a given character code starts an identifier.
1157
1158 function isIdentifierStart(code, astral) {
1159 if (code < 65) return code === 36;
1160 if (code < 91) return true;
1161 if (code < 97) return code === 95;
1162 if (code < 123) return true;
1163 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
1164 if (astral === false) return false;
1165 return isInAstralSet(code, astralIdentifierStartCodes);
1166 }
1167
1168 // Test whether a given character is part of an identifier.
1169
1170 function isIdentifierChar(code, astral) {
1171 if (code < 48) return code === 36;
1172 if (code < 58) return true;
1173 if (code < 65) return false;
1174 if (code < 91) return true;
1175 if (code < 97) return code === 95;
1176 if (code < 123) return true;
1177 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
1178 if (astral === false) return false;
1179 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1180 }
1181
1182 // ## Token types
1183
1184 // The assignment of fine-grained, information-carrying type objects
1185 // allows the tokenizer to store the information it has about a
1186 // token in a way that is very cheap for the parser to look up.
1187
1188 // All token type variables start with an underscore, to make them
1189 // easy to recognize.
1190
1191 // The `beforeExpr` property is used to disambiguate between regular
1192 // expressions and divisions. It is set on all token types that can
1193 // be followed by an expression (thus, a slash after them would be a
1194 // regular expression).
1195 //
1196 // The `startsExpr` property is used to check if the token ends a
1197 // `yield` expression. It is set on all token types that either can
1198 // directly start an expression (like a quotation mark) or can
1199 // continue an expression (like the body of a string).
1200 //
1201 // `isLoop` marks a keyword as starting a loop, which is important
1202 // to know when parsing a label, in order to allow or disallow
1203 // continue jumps to that label.
1204
1205 var TokenType = function TokenType(label) {
1206 var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1207 babelHelpers.classCallCheck(this, TokenType);
1208
1209 this.label = label;
1210 this.keyword = conf.keyword;
1211 this.beforeExpr = !!conf.beforeExpr;
1212 this.startsExpr = !!conf.startsExpr;
1213 this.isLoop = !!conf.isLoop;
1214 this.isAssign = !!conf.isAssign;
1215 this.prefix = !!conf.prefix;
1216 this.postfix = !!conf.postfix;
1217 this.binop = conf.binop || null;
1218 this.updateContext = null;
1219 };
1220
1221 function binop(name, prec) {
1222 return new TokenType(name, { beforeExpr: true, binop: prec });
1223 }
1224 var beforeExpr = { beforeExpr: true };
1225 var startsExpr = { startsExpr: true };
1226 var tt = {
1227 num: new TokenType("num", startsExpr),
1228 regexp: new TokenType("regexp", startsExpr),
1229 string: new TokenType("string", startsExpr),
1230 name: new TokenType("name", startsExpr),
1231 eof: new TokenType("eof"),
1232
1233 // Punctuation token types.
1234 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
1235 bracketR: new TokenType("]"),
1236 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
1237 braceR: new TokenType("}"),
1238 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
1239 parenR: new TokenType(")"),
1240 comma: new TokenType(",", beforeExpr),
1241 semi: new TokenType(";", beforeExpr),
1242 colon: new TokenType(":", beforeExpr),
1243 dot: new TokenType("."),
1244 question: new TokenType("?", beforeExpr),
1245 arrow: new TokenType("=>", beforeExpr),
1246 template: new TokenType("template"),
1247 ellipsis: new TokenType("...", beforeExpr),
1248 backQuote: new TokenType("`", startsExpr),
1249 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
1250
1251 // Operators. These carry several kinds of properties to help the
1252 // parser use them properly (the presence of these properties is
1253 // what categorizes them as operators).
1254 //
1255 // `binop`, when present, specifies that this operator is a binary
1256 // operator, and will refer to its precedence.
1257 //
1258 // `prefix` and `postfix` mark the operator as a prefix or postfix
1259 // unary operator.
1260 //
1261 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1262 // binary operators with a very low precedence, that should result
1263 // in AssignmentExpression nodes.
1264
1265 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
1266 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
1267 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
1268 prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }),
1269 logicalOR: binop("||", 1),
1270 logicalAND: binop("&&", 2),
1271 bitwiseOR: binop("|", 3),
1272 bitwiseXOR: binop("^", 4),
1273 bitwiseAND: binop("&", 5),
1274 equality: binop("==/!=", 6),
1275 relational: binop("</>", 7),
1276 bitShift: binop("<</>>", 8),
1277 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
1278 modulo: binop("%", 10),
1279 star: binop("*", 10),
1280 slash: binop("/", 10)
1281 };
1282
1283 // Map keyword names to token types.
1284
1285 var keywordTypes = {};
1286
1287 // Succinct definitions of keyword token types
1288 function kw(name) {
1289 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1290
1291 options.keyword = name;
1292 keywordTypes[name] = tt["_" + name] = new TokenType(name, options);
1293 }
1294
1295 kw("break");
1296 kw("case", beforeExpr);
1297 kw("catch");
1298 kw("continue");
1299 kw("debugger");
1300 kw("default", beforeExpr);
1301 kw("do", { isLoop: true, beforeExpr: true });
1302 kw("else", beforeExpr);
1303 kw("finally");
1304 kw("for", { isLoop: true });
1305 kw("function", startsExpr);
1306 kw("if");
1307 kw("return", beforeExpr);
1308 kw("switch");
1309 kw("throw", beforeExpr);
1310 kw("try");
1311 kw("var");
1312 kw("let");
1313 kw("const");
1314 kw("while", { isLoop: true });
1315 kw("with");
1316 kw("new", { beforeExpr: true, startsExpr: true });
1317 kw("this", startsExpr);
1318 kw("super", startsExpr);
1319 kw("class");
1320 kw("extends", beforeExpr);
1321 kw("export");
1322 kw("import");
1323 kw("yield", { beforeExpr: true, startsExpr: true });
1324 kw("null", startsExpr);
1325 kw("true", startsExpr);
1326 kw("false", startsExpr);
1327 kw("in", { beforeExpr: true, binop: 7 });
1328 kw("instanceof", { beforeExpr: true, binop: 7 });
1329 kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
1330 kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
1331 kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });
1332
1333 // Matches a whole line break (where CRLF is considered a single
1334 // line break). Used to count lines.
1335
1336 var lineBreak = /\r\n?|\n|\u2028|\u2029/;
1337 var lineBreakG = new RegExp(lineBreak.source, "g");
1338
1339 function isNewLine(code) {
1340 return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
1341 }
1342
1343 var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
1344
1345 function isArray$1(obj) {
1346 return Object.prototype.toString.call(obj) === "[object Array]";
1347 }
1348
1349 // Checks if an object has a property.
1350
1351 function has(obj, propName) {
1352 return Object.prototype.hasOwnProperty.call(obj, propName);
1353 }
1354
1355 // These are used when `options.locations` is on, for the
1356 // `startLoc` and `endLoc` properties.
1357
1358 var Position = (function () {
1359 function Position(line, col) {
1360 babelHelpers.classCallCheck(this, Position);
1361
1362 this.line = line;
1363 this.column = col;
1364 }
1365
1366 Position.prototype.offset = function offset(n) {
1367 return new Position(this.line, this.column + n);
1368 };
1369
1370 return Position;
1371 })();
1372
1373 var SourceLocation = function SourceLocation(p, start, end) {
1374 babelHelpers.classCallCheck(this, SourceLocation);
1375
1376 this.start = start;
1377 this.end = end;
1378 if (p.sourceFile !== null) this.source = p.sourceFile;
1379 }
1380
1381 // The `getLineInfo` function is mostly useful when the
1382 // `locations` option is off (for performance reasons) and you
1383 // want to find the line/column position for a given character
1384 // offset. `input` should be the code string that the offset refers
1385 // into.
1386
1387 ;
1388
1389 function getLineInfo(input, offset) {
1390 for (var line = 1, cur = 0;;) {
1391 lineBreakG.lastIndex = cur;
1392 var match = lineBreakG.exec(input);
1393 if (match && match.index < offset) {
1394 ++line;
1395 cur = match.index + match[0].length;
1396 } else {
1397 return new Position(line, offset - cur);
1398 }
1399 }
1400 }
1401
1402 // A second optional argument can be given to further configure
1403 // the parser process. These options are recognized:
1404
1405 var defaultOptions = {
1406 // `ecmaVersion` indicates the ECMAScript version to parse. Must
1407 // be either 3, or 5, or 6. This influences support for strict
1408 // mode, the set of reserved words, support for getters and
1409 // setters and other features.
1410 ecmaVersion: 5,
1411 // Source type ("script" or "module") for different semantics
1412 sourceType: "script",
1413 // `onInsertedSemicolon` can be a callback that will be called
1414 // when a semicolon is automatically inserted. It will be passed
1415 // th position of the comma as an offset, and if `locations` is
1416 // enabled, it is given the location as a `{line, column}` object
1417 // as second argument.
1418 onInsertedSemicolon: null,
1419 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
1420 // trailing commas.
1421 onTrailingComma: null,
1422 // By default, reserved words are only enforced if ecmaVersion >= 5.
1423 // Set `allowReserved` to a boolean value to explicitly turn this on
1424 // an off. When this option has the value "never", reserved words
1425 // and keywords can also not be used as property names.
1426 allowReserved: null,
1427 // When enabled, a return at the top level is not considered an
1428 // error.
1429 allowReturnOutsideFunction: false,
1430 // When enabled, import/export statements are not constrained to
1431 // appearing at the top of the program.
1432 allowImportExportEverywhere: false,
1433 // When enabled, hashbang directive in the beginning of file
1434 // is allowed and treated as a line comment.
1435 allowHashBang: false,
1436 // When `locations` is on, `loc` properties holding objects with
1437 // `start` and `end` properties in `{line, column}` form (with
1438 // line being 1-based and column 0-based) will be attached to the
1439 // nodes.
1440 locations: false,
1441 // A function can be passed as `onToken` option, which will
1442 // cause Acorn to call that function with object in the same
1443 // format as tokens returned from `tokenizer().getToken()`. Note
1444 // that you are not allowed to call the parser from the
1445 // callback—that will corrupt its internal state.
1446 onToken: null,
1447 // A function can be passed as `onComment` option, which will
1448 // cause Acorn to call that function with `(block, text, start,
1449 // end)` parameters whenever a comment is skipped. `block` is a
1450 // boolean indicating whether this is a block (`/* */`) comment,
1451 // `text` is the content of the comment, and `start` and `end` are
1452 // character offsets that denote the start and end of the comment.
1453 // When the `locations` option is on, two more parameters are
1454 // passed, the full `{line, column}` locations of the start and
1455 // end of the comments. Note that you are not allowed to call the
1456 // parser from the callback—that will corrupt its internal state.
1457 onComment: null,
1458 // Nodes have their start and end characters offsets recorded in
1459 // `start` and `end` properties (directly on the node, rather than
1460 // the `loc` object, which holds line/column data. To also add a
1461 // [semi-standardized][range] `range` property holding a `[start,
1462 // end]` array with the same numbers, set the `ranges` option to
1463 // `true`.
1464 //
1465 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
1466 ranges: false,
1467 // It is possible to parse multiple files into a single AST by
1468 // passing the tree produced by parsing the first file as
1469 // `program` option in subsequent parses. This will add the
1470 // toplevel forms of the parsed file to the `Program` (top) node
1471 // of an existing parse tree.
1472 program: null,
1473 // When `locations` is on, you can pass this to record the source
1474 // file in every node's `loc` object.
1475 sourceFile: null,
1476 // This value, if given, is stored in every node, whether
1477 // `locations` is on or off.
1478 directSourceFile: null,
1479 // When enabled, parenthesized expressions are represented by
1480 // (non-standard) ParenthesizedExpression nodes
1481 preserveParens: false,
1482 plugins: {}
1483 };
1484
1485 // Interpret and default an options object
1486
1487 function getOptions(opts) {
1488 var options = {};
1489 for (var opt in defaultOptions) {
1490 options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
1491 }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion >= 5;
1492
1493 if (isArray$1(options.onToken)) {
1494 (function () {
1495 var tokens = options.onToken;
1496 options.onToken = function (token) {
1497 return tokens.push(token);
1498 };
1499 })();
1500 }
1501 if (isArray$1(options.onComment)) options.onComment = pushComment(options, options.onComment);
1502
1503 return options;
1504 }
1505
1506 function pushComment(options, array) {
1507 return function (block, text, start, end, startLoc, endLoc) {
1508 var comment = {
1509 type: block ? 'Block' : 'Line',
1510 value: text,
1511 start: start,
1512 end: end
1513 };
1514 if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc);
1515 if (options.ranges) comment.range = [start, end];
1516 array.push(comment);
1517 };
1518 }
1519
1520 // Registered plugins
1521 var plugins = {};
1522
1523 function keywordRegexp(words) {
1524 return new RegExp("^(" + words.replace(/ /g, "|") + ")$");
1525 }
1526
1527 var Parser = (function () {
1528 function Parser(options, input, startPos) {
1529 babelHelpers.classCallCheck(this, Parser);
1530
1531 this.options = getOptions(options);
1532 this.sourceFile = this.options.sourceFile;
1533 this.keywords = keywordRegexp(keywords[this.options.ecmaVersion >= 6 ? 6 : 5]);
1534 var reserved = this.options.allowReserved ? "" : reservedWords$1[this.options.ecmaVersion] + (options.sourceType == "module" ? " await" : "");
1535 this.reservedWords = keywordRegexp(reserved);
1536 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
1537 this.reservedWordsStrict = keywordRegexp(reservedStrict);
1538 this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords$1.strictBind);
1539 this.input = String(input);
1540
1541 // Used to signal to callers of `readWord1` whether the word
1542 // contained any escape sequences. This is needed because words with
1543 // escape sequences must not be interpreted as keywords.
1544 this.containsEsc = false;
1545
1546 // Load plugins
1547 this.loadPlugins(this.options.plugins);
1548
1549 // Set up token state
1550
1551 // The current position of the tokenizer in the input.
1552 if (startPos) {
1553 this.pos = startPos;
1554 this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
1555 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
1556 } else {
1557 this.pos = this.lineStart = 0;
1558 this.curLine = 1;
1559 }
1560
1561 // Properties of the current token:
1562 // Its type
1563 this.type = tt.eof;
1564 // For tokens that include more information than their type, the value
1565 this.value = null;
1566 // Its start and end offset
1567 this.start = this.end = this.pos;
1568 // And, if locations are used, the {line, column} object
1569 // corresponding to those offsets
1570 this.startLoc = this.endLoc = this.curPosition();
1571
1572 // Position information for the previous token
1573 this.lastTokEndLoc = this.lastTokStartLoc = null;
1574 this.lastTokStart = this.lastTokEnd = this.pos;
1575
1576 // The context stack is used to superficially track syntactic
1577 // context to predict whether a regular expression is allowed in a
1578 // given position.
1579 this.context = this.initialContext();
1580 this.exprAllowed = true;
1581
1582 // Figure out if it's a module code.
1583 this.strict = this.inModule = this.options.sourceType === "module";
1584
1585 // Used to signify the start of a potential arrow function
1586 this.potentialArrowAt = -1;
1587
1588 // Flags to track whether we are in a function, a generator.
1589 this.inFunction = this.inGenerator = false;
1590 // Labels in scope.
1591 this.labels = [];
1592
1593 // If enabled, skip leading hashbang line.
1594 if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2);
1595 }
1596
1597 // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
1598
1599 Parser.prototype.isKeyword = function isKeyword(word) {
1600 return this.keywords.test(word);
1601 };
1602
1603 Parser.prototype.isReservedWord = function isReservedWord(word) {
1604 return this.reservedWords.test(word);
1605 };
1606
1607 Parser.prototype.extend = function extend(name, f) {
1608 this[name] = f(this[name]);
1609 };
1610
1611 Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
1612 for (var _name in pluginConfigs) {
1613 var plugin = plugins[_name];
1614 if (!plugin) throw new Error("Plugin '" + _name + "' not found");
1615 plugin(this, pluginConfigs[_name]);
1616 }
1617 };
1618
1619 Parser.prototype.parse = function parse() {
1620 var node = this.options.program || this.startNode();
1621 this.nextToken();
1622 return this.parseTopLevel(node);
1623 };
1624
1625 return Parser;
1626 })();
1627
1628 var pp = Parser.prototype;
1629
1630 // ## Parser utilities
1631
1632 // Test whether a statement node is the string literal `"use strict"`.
1633
1634 pp.isUseStrict = function (stmt) {
1635 return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict";
1636 };
1637
1638 // Predicate that tests whether the next token is of the given
1639 // type, and if yes, consumes it as a side effect.
1640
1641 pp.eat = function (type) {
1642 if (this.type === type) {
1643 this.next();
1644 return true;
1645 } else {
1646 return false;
1647 }
1648 };
1649
1650 // Tests whether parsed token is a contextual keyword.
1651
1652 pp.isContextual = function (name) {
1653 return this.type === tt.name && this.value === name;
1654 };
1655
1656 // Consumes contextual keyword if possible.
1657
1658 pp.eatContextual = function (name) {
1659 return this.value === name && this.eat(tt.name);
1660 };
1661
1662 // Asserts that following token is given contextual keyword.
1663
1664 pp.expectContextual = function (name) {
1665 if (!this.eatContextual(name)) this.unexpected();
1666 };
1667
1668 // Test whether a semicolon can be inserted at the current position.
1669
1670 pp.canInsertSemicolon = function () {
1671 return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
1672 };
1673
1674 pp.insertSemicolon = function () {
1675 if (this.canInsertSemicolon()) {
1676 if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
1677 return true;
1678 }
1679 };
1680
1681 // Consume a semicolon, or, failing that, see if we are allowed to
1682 // pretend that there is a semicolon at this position.
1683
1684 pp.semicolon = function () {
1685 if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected();
1686 };
1687
1688 pp.afterTrailingComma = function (tokType) {
1689 if (this.type == tokType) {
1690 if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
1691 this.next();
1692 return true;
1693 }
1694 };
1695
1696 // Expect a token of a given type. If found, consume it, otherwise,
1697 // raise an unexpected token error.
1698
1699 pp.expect = function (type) {
1700 this.eat(type) || this.unexpected();
1701 };
1702
1703 // Raise an unexpected token error.
1704
1705 pp.unexpected = function (pos) {
1706 this.raise(pos != null ? pos : this.start, "Unexpected token");
1707 };
1708
1709 var pp$1 = Parser.prototype;
1710
1711 // ### Statement parsing
1712
1713 // Parse a program. Initializes the parser, reads any number of
1714 // statements, and wraps them in a Program node. Optionally takes a
1715 // `program` argument. If present, the statements will be appended
1716 // to its body instead of creating a new node.
1717
1718 pp$1.parseTopLevel = function (node) {
1719 var first = true;
1720 if (!node.body) node.body = [];
1721 while (this.type !== tt.eof) {
1722 var stmt = this.parseStatement(true, true);
1723 node.body.push(stmt);
1724 if (first) {
1725 if (this.isUseStrict(stmt)) this.setStrict(true);
1726 first = false;
1727 }
1728 }
1729 this.next();
1730 if (this.options.ecmaVersion >= 6) {
1731 node.sourceType = this.options.sourceType;
1732 }
1733 return this.finishNode(node, "Program");
1734 };
1735
1736 var loopLabel = { kind: "loop" };
1737 var switchLabel = { kind: "switch" };
1738 // Parse a single statement.
1739 //
1740 // If expecting a statement and finding a slash operator, parse a
1741 // regular expression literal. This is to handle cases like
1742 // `if (foo) /blah/.exec(foo)`, where looking at the previous token
1743 // does not help.
1744
1745 pp$1.parseStatement = function (declaration, topLevel) {
1746 var starttype = this.type,
1747 node = this.startNode();
1748
1749 // Most types of statements are recognized by the keyword they
1750 // start with. Many are trivial to parse, some require a bit of
1751 // complexity.
1752
1753 switch (starttype) {
1754 case tt._break:case tt._continue:
1755 return this.parseBreakContinueStatement(node, starttype.keyword);
1756 case tt._debugger:
1757 return this.parseDebuggerStatement(node);
1758 case tt._do:
1759 return this.parseDoStatement(node);
1760 case tt._for:
1761 return this.parseForStatement(node);
1762 case tt._function:
1763 if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
1764 return this.parseFunctionStatement(node);
1765 case tt._class:
1766 if (!declaration) this.unexpected();
1767 return this.parseClass(node, true);
1768 case tt._if:
1769 return this.parseIfStatement(node);
1770 case tt._return:
1771 return this.parseReturnStatement(node);
1772 case tt._switch:
1773 return this.parseSwitchStatement(node);
1774 case tt._throw:
1775 return this.parseThrowStatement(node);
1776 case tt._try:
1777 return this.parseTryStatement(node);
1778 case tt._let:case tt._const:
1779 if (!declaration) this.unexpected(); // NOTE: falls through to _var
1780 case tt._var:
1781 return this.parseVarStatement(node, starttype);
1782 case tt._while:
1783 return this.parseWhileStatement(node);
1784 case tt._with:
1785 return this.parseWithStatement(node);
1786 case tt.braceL:
1787 return this.parseBlock();
1788 case tt.semi:
1789 return this.parseEmptyStatement(node);
1790 case tt._export:
1791 case tt._import:
1792 if (!this.options.allowImportExportEverywhere) {
1793 if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
1794 if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
1795 }
1796 return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
1797
1798 // If the statement does not start with a statement keyword or a
1799 // brace, it's an ExpressionStatement or LabeledStatement. We
1800 // simply start parsing an expression, and afterwards, if the
1801 // next token is a colon and the expression was a simple
1802 // Identifier node, we switch to interpreting it as a label.
1803 default:
1804 var maybeName = this.value,
1805 expr = this.parseExpression();
1806 if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
1807 }
1808 };
1809
1810 pp$1.parseBreakContinueStatement = function (node, keyword) {
1811 var isBreak = keyword == "break";
1812 this.next();
1813 if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== tt.name) this.unexpected();else {
1814 node.label = this.parseIdent();
1815 this.semicolon();
1816 }
1817
1818 // Verify that there is an actual destination to break or
1819 // continue to.
1820 for (var i = 0; i < this.labels.length; ++i) {
1821 var lab = this.labels[i];
1822 if (node.label == null || lab.name === node.label.name) {
1823 if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
1824 if (node.label && isBreak) break;
1825 }
1826 }
1827 if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
1828 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
1829 };
1830
1831 pp$1.parseDebuggerStatement = function (node) {
1832 this.next();
1833 this.semicolon();
1834 return this.finishNode(node, "DebuggerStatement");
1835 };
1836
1837 pp$1.parseDoStatement = function (node) {
1838 this.next();
1839 this.labels.push(loopLabel);
1840 node.body = this.parseStatement(false);
1841 this.labels.pop();
1842 this.expect(tt._while);
1843 node.test = this.parseParenExpression();
1844 if (this.options.ecmaVersion >= 6) this.eat(tt.semi);else this.semicolon();
1845 return this.finishNode(node, "DoWhileStatement");
1846 };
1847
1848 // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
1849 // loop is non-trivial. Basically, we have to parse the init `var`
1850 // statement or expression, disallowing the `in` operator (see
1851 // the second parameter to `parseExpression`), and then check
1852 // whether the next token is `in` or `of`. When there is no init
1853 // part (semicolon immediately after the opening parenthesis), it
1854 // is a regular `for` loop.
1855
1856 pp$1.parseForStatement = function (node) {
1857 this.next();
1858 this.labels.push(loopLabel);
1859 this.expect(tt.parenL);
1860 if (this.type === tt.semi) return this.parseFor(node, null);
1861 if (this.type === tt._var || this.type === tt._let || this.type === tt._const) {
1862 var _init = this.startNode(),
1863 varKind = this.type;
1864 this.next();
1865 this.parseVar(_init, true, varKind);
1866 this.finishNode(_init, "VariableDeclaration");
1867 if ((this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== tt._var && _init.declarations[0].init)) return this.parseForIn(node, _init);
1868 return this.parseFor(node, _init);
1869 }
1870 var refShorthandDefaultPos = { start: 0 };
1871 var init = this.parseExpression(true, refShorthandDefaultPos);
1872 if (this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
1873 this.toAssignable(init);
1874 this.checkLVal(init);
1875 return this.parseForIn(node, init);
1876 } else if (refShorthandDefaultPos.start) {
1877 this.unexpected(refShorthandDefaultPos.start);
1878 }
1879 return this.parseFor(node, init);
1880 };
1881
1882 pp$1.parseFunctionStatement = function (node) {
1883 this.next();
1884 return this.parseFunction(node, true);
1885 };
1886
1887 pp$1.parseIfStatement = function (node) {
1888 this.next();
1889 node.test = this.parseParenExpression();
1890 node.consequent = this.parseStatement(false);
1891 node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
1892 return this.finishNode(node, "IfStatement");
1893 };
1894
1895 pp$1.parseReturnStatement = function (node) {
1896 if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
1897 this.next();
1898
1899 // In `return` (and `break`/`continue`), the keywords with
1900 // optional arguments, we eagerly look for a semicolon or the
1901 // possibility to insert one.
1902
1903 if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null;else {
1904 node.argument = this.parseExpression();this.semicolon();
1905 }
1906 return this.finishNode(node, "ReturnStatement");
1907 };
1908
1909 pp$1.parseSwitchStatement = function (node) {
1910 this.next();
1911 node.discriminant = this.parseParenExpression();
1912 node.cases = [];
1913 this.expect(tt.braceL);
1914 this.labels.push(switchLabel);
1915
1916 // Statements under must be grouped (by label) in SwitchCase
1917 // nodes. `cur` is used to keep the node that we are currently
1918 // adding statements to.
1919
1920 for (var cur, sawDefault = false; this.type != tt.braceR;) {
1921 if (this.type === tt._case || this.type === tt._default) {
1922 var isCase = this.type === tt._case;
1923 if (cur) this.finishNode(cur, "SwitchCase");
1924 node.cases.push(cur = this.startNode());
1925 cur.consequent = [];
1926 this.next();
1927 if (isCase) {
1928 cur.test = this.parseExpression();
1929 } else {
1930 if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
1931 sawDefault = true;
1932 cur.test = null;
1933 }
1934 this.expect(tt.colon);
1935 } else {
1936 if (!cur) this.unexpected();
1937 cur.consequent.push(this.parseStatement(true));
1938 }
1939 }
1940 if (cur) this.finishNode(cur, "SwitchCase");
1941 this.next(); // Closing brace
1942 this.labels.pop();
1943 return this.finishNode(node, "SwitchStatement");
1944 };
1945
1946 pp$1.parseThrowStatement = function (node) {
1947 this.next();
1948 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
1949 node.argument = this.parseExpression();
1950 this.semicolon();
1951 return this.finishNode(node, "ThrowStatement");
1952 };
1953
1954 // Reused empty array added for node fields that are always empty.
1955
1956 var empty = [];
1957
1958 pp$1.parseTryStatement = function (node) {
1959 this.next();
1960 node.block = this.parseBlock();
1961 node.handler = null;
1962 if (this.type === tt._catch) {
1963 var clause = this.startNode();
1964 this.next();
1965 this.expect(tt.parenL);
1966 clause.param = this.parseBindingAtom();
1967 this.checkLVal(clause.param, true);
1968 this.expect(tt.parenR);
1969 clause.body = this.parseBlock();
1970 node.handler = this.finishNode(clause, "CatchClause");
1971 }
1972 node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
1973 if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
1974 return this.finishNode(node, "TryStatement");
1975 };
1976
1977 pp$1.parseVarStatement = function (node, kind) {
1978 this.next();
1979 this.parseVar(node, false, kind);
1980 this.semicolon();
1981 return this.finishNode(node, "VariableDeclaration");
1982 };
1983
1984 pp$1.parseWhileStatement = function (node) {
1985 this.next();
1986 node.test = this.parseParenExpression();
1987 this.labels.push(loopLabel);
1988 node.body = this.parseStatement(false);
1989 this.labels.pop();
1990 return this.finishNode(node, "WhileStatement");
1991 };
1992
1993 pp$1.parseWithStatement = function (node) {
1994 if (this.strict) this.raise(this.start, "'with' in strict mode");
1995 this.next();
1996 node.object = this.parseParenExpression();
1997 node.body = this.parseStatement(false);
1998 return this.finishNode(node, "WithStatement");
1999 };
2000
2001 pp$1.parseEmptyStatement = function (node) {
2002 this.next();
2003 return this.finishNode(node, "EmptyStatement");
2004 };
2005
2006 pp$1.parseLabeledStatement = function (node, maybeName, expr) {
2007 for (var i = 0; i < this.labels.length; ++i) {
2008 if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
2009 }var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null;
2010 for (var i = this.labels.length - 1; i >= 0; i--) {
2011 var label = this.labels[i];
2012 if (label.statementStart == node.start) {
2013 label.statementStart = this.start;
2014 label.kind = kind;
2015 } else break;
2016 }
2017 this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
2018 node.body = this.parseStatement(true);
2019 this.labels.pop();
2020 node.label = expr;
2021 return this.finishNode(node, "LabeledStatement");
2022 };
2023
2024 pp$1.parseExpressionStatement = function (node, expr) {
2025 node.expression = expr;
2026 this.semicolon();
2027 return this.finishNode(node, "ExpressionStatement");
2028 };
2029
2030 // Parse a semicolon-enclosed block of statements, handling `"use
2031 // strict"` declarations when `allowStrict` is true (used for
2032 // function bodies).
2033
2034 pp$1.parseBlock = function (allowStrict) {
2035 var node = this.startNode(),
2036 first = true,
2037 oldStrict = undefined;
2038 node.body = [];
2039 this.expect(tt.braceL);
2040 while (!this.eat(tt.braceR)) {
2041 var stmt = this.parseStatement(true);
2042 node.body.push(stmt);
2043 if (first && allowStrict && this.isUseStrict(stmt)) {
2044 oldStrict = this.strict;
2045 this.setStrict(this.strict = true);
2046 }
2047 first = false;
2048 }
2049 if (oldStrict === false) this.setStrict(false);
2050 return this.finishNode(node, "BlockStatement");
2051 };
2052
2053 // Parse a regular `for` loop. The disambiguation code in
2054 // `parseStatement` will already have parsed the init statement or
2055 // expression.
2056
2057 pp$1.parseFor = function (node, init) {
2058 node.init = init;
2059 this.expect(tt.semi);
2060 node.test = this.type === tt.semi ? null : this.parseExpression();
2061 this.expect(tt.semi);
2062 node.update = this.type === tt.parenR ? null : this.parseExpression();
2063 this.expect(tt.parenR);
2064 node.body = this.parseStatement(false);
2065 this.labels.pop();
2066 return this.finishNode(node, "ForStatement");
2067 };
2068
2069 // Parse a `for`/`in` and `for`/`of` loop, which are almost
2070 // same from parser's perspective.
2071
2072 pp$1.parseForIn = function (node, init) {
2073 var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement";
2074 this.next();
2075 node.left = init;
2076 node.right = this.parseExpression();
2077 this.expect(tt.parenR);
2078 node.body = this.parseStatement(false);
2079 this.labels.pop();
2080 return this.finishNode(node, type);
2081 };
2082
2083 // Parse a list of variable declarations.
2084
2085 pp$1.parseVar = function (node, isFor, kind) {
2086 node.declarations = [];
2087 node.kind = kind.keyword;
2088 for (;;) {
2089 var decl = this.startNode();
2090 this.parseVarId(decl);
2091 if (this.eat(tt.eq)) {
2092 decl.init = this.parseMaybeAssign(isFor);
2093 } else if (kind === tt._const && !(this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
2094 this.unexpected();
2095 } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
2096 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
2097 } else {
2098 decl.init = null;
2099 }
2100 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
2101 if (!this.eat(tt.comma)) break;
2102 }
2103 return node;
2104 };
2105
2106 pp$1.parseVarId = function (decl) {
2107 decl.id = this.parseBindingAtom();
2108 this.checkLVal(decl.id, true);
2109 };
2110
2111 // Parse a function declaration or literal (depending on the
2112 // `isStatement` parameter).
2113
2114 pp$1.parseFunction = function (node, isStatement, allowExpressionBody) {
2115 this.initFunction(node);
2116 if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star);
2117 if (isStatement || this.type === tt.name) node.id = this.parseIdent();
2118 this.parseFunctionParams(node);
2119 this.parseFunctionBody(node, allowExpressionBody);
2120 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
2121 };
2122
2123 pp$1.parseFunctionParams = function (node) {
2124 this.expect(tt.parenL);
2125 node.params = this.parseBindingList(tt.parenR, false, false, true);
2126 };
2127
2128 // Parse a class declaration or literal (depending on the
2129 // `isStatement` parameter).
2130
2131 pp$1.parseClass = function (node, isStatement) {
2132 this.next();
2133 this.parseClassId(node, isStatement);
2134 this.parseClassSuper(node);
2135 var classBody = this.startNode();
2136 var hadConstructor = false;
2137 classBody.body = [];
2138 this.expect(tt.braceL);
2139 while (!this.eat(tt.braceR)) {
2140 if (this.eat(tt.semi)) continue;
2141 var method = this.startNode();
2142 var isGenerator = this.eat(tt.star);
2143 var isMaybeStatic = this.type === tt.name && this.value === "static";
2144 this.parsePropertyName(method);
2145 method.static = isMaybeStatic && this.type !== tt.parenL;
2146 if (method.static) {
2147 if (isGenerator) this.unexpected();
2148 isGenerator = this.eat(tt.star);
2149 this.parsePropertyName(method);
2150 }
2151 method.kind = "method";
2152 var isGetSet = false;
2153 if (!method.computed) {
2154 var key = method.key;
2155
2156 if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
2157 isGetSet = true;
2158 method.kind = key.name;
2159 key = this.parsePropertyName(method);
2160 }
2161 if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
2162 if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
2163 if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
2164 if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
2165 method.kind = "constructor";
2166 hadConstructor = true;
2167 }
2168 }
2169 this.parseClassMethod(classBody, method, isGenerator);
2170 if (isGetSet) {
2171 var paramCount = method.kind === "get" ? 0 : 1;
2172 if (method.value.params.length !== paramCount) {
2173 var start = method.value.start;
2174 if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
2175 }
2176 }
2177 }
2178 node.body = this.finishNode(classBody, "ClassBody");
2179 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
2180 };
2181
2182 pp$1.parseClassMethod = function (classBody, method, isGenerator) {
2183 method.value = this.parseMethod(isGenerator);
2184 classBody.body.push(this.finishNode(method, "MethodDefinition"));
2185 };
2186
2187 pp$1.parseClassId = function (node, isStatement) {
2188 node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
2189 };
2190
2191 pp$1.parseClassSuper = function (node) {
2192 node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
2193 };
2194
2195 // Parses module export declaration.
2196
2197 pp$1.parseExport = function (node) {
2198 this.next();
2199 // export * from '...'
2200 if (this.eat(tt.star)) {
2201 this.expectContextual("from");
2202 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2203 this.semicolon();
2204 return this.finishNode(node, "ExportAllDeclaration");
2205 }
2206 if (this.eat(tt._default)) {
2207 // export default ...
2208 var expr = this.parseMaybeAssign();
2209 var needsSemi = true;
2210 if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
2211 needsSemi = false;
2212 if (expr.id) {
2213 expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
2214 }
2215 }
2216 node.declaration = expr;
2217 if (needsSemi) this.semicolon();
2218 return this.finishNode(node, "ExportDefaultDeclaration");
2219 }
2220 // export var|const|let|function|class ...
2221 if (this.shouldParseExportStatement()) {
2222 node.declaration = this.parseStatement(true);
2223 node.specifiers = [];
2224 node.source = null;
2225 } else {
2226 // export { x, y as z } [from '...']
2227 node.declaration = null;
2228 node.specifiers = this.parseExportSpecifiers();
2229 if (this.eatContextual("from")) {
2230 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2231 } else {
2232 // check for keywords used as local names
2233 for (var i = 0; i < node.specifiers.length; i++) {
2234 if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) {
2235 this.unexpected(node.specifiers[i].local.start);
2236 }
2237 }
2238
2239 node.source = null;
2240 }
2241 this.semicolon();
2242 }
2243 return this.finishNode(node, "ExportNamedDeclaration");
2244 };
2245
2246 pp$1.shouldParseExportStatement = function () {
2247 return this.type.keyword;
2248 };
2249
2250 // Parses a comma-separated list of module exports.
2251
2252 pp$1.parseExportSpecifiers = function () {
2253 var nodes = [],
2254 first = true;
2255 // export { x, y as z } [from '...']
2256 this.expect(tt.braceL);
2257 while (!this.eat(tt.braceR)) {
2258 if (!first) {
2259 this.expect(tt.comma);
2260 if (this.afterTrailingComma(tt.braceR)) break;
2261 } else first = false;
2262
2263 var node = this.startNode();
2264 node.local = this.parseIdent(this.type === tt._default);
2265 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
2266 nodes.push(this.finishNode(node, "ExportSpecifier"));
2267 }
2268 return nodes;
2269 };
2270
2271 // Parses import declaration.
2272
2273 pp$1.parseImport = function (node) {
2274 this.next();
2275 // import '...'
2276 if (this.type === tt.string) {
2277 node.specifiers = empty;
2278 node.source = this.parseExprAtom();
2279 } else {
2280 node.specifiers = this.parseImportSpecifiers();
2281 this.expectContextual("from");
2282 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2283 }
2284 this.semicolon();
2285 return this.finishNode(node, "ImportDeclaration");
2286 };
2287
2288 // Parses a comma-separated list of module imports.
2289
2290 pp$1.parseImportSpecifiers = function () {
2291 var nodes = [],
2292 first = true;
2293 if (this.type === tt.name) {
2294 // import defaultObj, { x, y as z } from '...'
2295 var node = this.startNode();
2296 node.local = this.parseIdent();
2297 this.checkLVal(node.local, true);
2298 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
2299 if (!this.eat(tt.comma)) return nodes;
2300 }
2301 if (this.type === tt.star) {
2302 var node = this.startNode();
2303 this.next();
2304 this.expectContextual("as");
2305 node.local = this.parseIdent();
2306 this.checkLVal(node.local, true);
2307 nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"));
2308 return nodes;
2309 }
2310 this.expect(tt.braceL);
2311 while (!this.eat(tt.braceR)) {
2312 if (!first) {
2313 this.expect(tt.comma);
2314 if (this.afterTrailingComma(tt.braceR)) break;
2315 } else first = false;
2316
2317 var node = this.startNode();
2318 node.imported = this.parseIdent(true);
2319 node.local = this.eatContextual("as") ? this.parseIdent() : node.imported;
2320 this.checkLVal(node.local, true);
2321 nodes.push(this.finishNode(node, "ImportSpecifier"));
2322 }
2323 return nodes;
2324 };
2325
2326 var pp$2 = Parser.prototype;
2327
2328 // Convert existing expression atom to assignable pattern
2329 // if possible.
2330
2331 pp$2.toAssignable = function (node, isBinding) {
2332 if (this.options.ecmaVersion >= 6 && node) {
2333 switch (node.type) {
2334 case "Identifier":
2335 case "ObjectPattern":
2336 case "ArrayPattern":
2337 case "AssignmentPattern":
2338 break;
2339
2340 case "ObjectExpression":
2341 node.type = "ObjectPattern";
2342 for (var i = 0; i < node.properties.length; i++) {
2343 var prop = node.properties[i];
2344 if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
2345 this.toAssignable(prop.value, isBinding);
2346 }
2347 break;
2348
2349 case "ArrayExpression":
2350 node.type = "ArrayPattern";
2351 this.toAssignableList(node.elements, isBinding);
2352 break;
2353
2354 case "AssignmentExpression":
2355 if (node.operator === "=") {
2356 node.type = "AssignmentPattern";
2357 delete node.operator;
2358 } else {
2359 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
2360 }
2361 break;
2362
2363 case "ParenthesizedExpression":
2364 node.expression = this.toAssignable(node.expression, isBinding);
2365 break;
2366
2367 case "MemberExpression":
2368 if (!isBinding) break;
2369
2370 default:
2371 this.raise(node.start, "Assigning to rvalue");
2372 }
2373 }
2374 return node;
2375 };
2376
2377 // Convert list of expression atoms to binding list.
2378
2379 pp$2.toAssignableList = function (exprList, isBinding) {
2380 var end = exprList.length;
2381 if (end) {
2382 var last = exprList[end - 1];
2383 if (last && last.type == "RestElement") {
2384 --end;
2385 } else if (last && last.type == "SpreadElement") {
2386 last.type = "RestElement";
2387 var arg = last.argument;
2388 this.toAssignable(arg, isBinding);
2389 if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
2390 --end;
2391 }
2392
2393 if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start);
2394 }
2395 for (var i = 0; i < end; i++) {
2396 var elt = exprList[i];
2397 if (elt) this.toAssignable(elt, isBinding);
2398 }
2399 return exprList;
2400 };
2401
2402 // Parses spread element.
2403
2404 pp$2.parseSpread = function (refShorthandDefaultPos) {
2405 var node = this.startNode();
2406 this.next();
2407 node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
2408 return this.finishNode(node, "SpreadElement");
2409 };
2410
2411 pp$2.parseRest = function (allowNonIdent) {
2412 var node = this.startNode();
2413 this.next();
2414
2415 // RestElement inside of a function parameter must be an identifier
2416 if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected();else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected();
2417
2418 return this.finishNode(node, "RestElement");
2419 };
2420
2421 // Parses lvalue (assignable) atom.
2422
2423 pp$2.parseBindingAtom = function () {
2424 if (this.options.ecmaVersion < 6) return this.parseIdent();
2425 switch (this.type) {
2426 case tt.name:
2427 return this.parseIdent();
2428
2429 case tt.bracketL:
2430 var node = this.startNode();
2431 this.next();
2432 node.elements = this.parseBindingList(tt.bracketR, true, true);
2433 return this.finishNode(node, "ArrayPattern");
2434
2435 case tt.braceL:
2436 return this.parseObj(true);
2437
2438 default:
2439 this.unexpected();
2440 }
2441 };
2442
2443 pp$2.parseBindingList = function (close, allowEmpty, allowTrailingComma, allowNonIdent) {
2444 var elts = [],
2445 first = true;
2446 while (!this.eat(close)) {
2447 if (first) first = false;else this.expect(tt.comma);
2448 if (allowEmpty && this.type === tt.comma) {
2449 elts.push(null);
2450 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
2451 break;
2452 } else if (this.type === tt.ellipsis) {
2453 var rest = this.parseRest(allowNonIdent);
2454 this.parseBindingListItem(rest);
2455 elts.push(rest);
2456 this.expect(close);
2457 break;
2458 } else {
2459 var elem = this.parseMaybeDefault(this.start, this.startLoc);
2460 this.parseBindingListItem(elem);
2461 elts.push(elem);
2462 }
2463 }
2464 return elts;
2465 };
2466
2467 pp$2.parseBindingListItem = function (param) {
2468 return param;
2469 };
2470
2471 // Parses assignment pattern around given atom if possible.
2472
2473 pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
2474 left = left || this.parseBindingAtom();
2475 if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left;
2476 var node = this.startNodeAt(startPos, startLoc);
2477 node.left = left;
2478 node.right = this.parseMaybeAssign();
2479 return this.finishNode(node, "AssignmentPattern");
2480 };
2481
2482 // Verify that a node is an lval — something that can be assigned
2483 // to.
2484
2485 pp$2.checkLVal = function (expr, isBinding, checkClashes) {
2486 switch (expr.type) {
2487 case "Identifier":
2488 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
2489 if (checkClashes) {
2490 if (has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash");
2491 checkClashes[expr.name] = true;
2492 }
2493 break;
2494
2495 case "MemberExpression":
2496 if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
2497 break;
2498
2499 case "ObjectPattern":
2500 for (var i = 0; i < expr.properties.length; i++) {
2501 this.checkLVal(expr.properties[i].value, isBinding, checkClashes);
2502 }break;
2503
2504 case "ArrayPattern":
2505 for (var i = 0; i < expr.elements.length; i++) {
2506 var elem = expr.elements[i];
2507 if (elem) this.checkLVal(elem, isBinding, checkClashes);
2508 }
2509 break;
2510
2511 case "AssignmentPattern":
2512 this.checkLVal(expr.left, isBinding, checkClashes);
2513 break;
2514
2515 case "RestElement":
2516 this.checkLVal(expr.argument, isBinding, checkClashes);
2517 break;
2518
2519 case "ParenthesizedExpression":
2520 this.checkLVal(expr.expression, isBinding, checkClashes);
2521 break;
2522
2523 default:
2524 this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
2525 }
2526 };
2527
2528 var pp$3 = Parser.prototype;
2529
2530 // Check if property name clashes with already added.
2531 // Object/class getters and setters are not allowed to clash —
2532 // either with each other or with an init property — and in
2533 // strict mode, init properties are also not allowed to be repeated.
2534
2535 pp$3.checkPropClash = function (prop, propHash) {
2536 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
2537 var key = prop.key;var name = undefined;
2538 switch (key.type) {
2539 case "Identifier":
2540 name = key.name;break;
2541 case "Literal":
2542 name = String(key.value);break;
2543 default:
2544 return;
2545 }
2546 var kind = prop.kind;
2547
2548 if (this.options.ecmaVersion >= 6) {
2549 if (name === "__proto__" && kind === "init") {
2550 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
2551 propHash.proto = true;
2552 }
2553 return;
2554 }
2555 name = "$" + name;
2556 var other = propHash[name];
2557 if (other) {
2558 var isGetSet = kind !== "init";
2559 if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
2560 } else {
2561 other = propHash[name] = {
2562 init: false,
2563 get: false,
2564 set: false
2565 };
2566 }
2567 other[kind] = true;
2568 };
2569
2570 // ### Expression parsing
2571
2572 // These nest, from the most general expression type at the top to
2573 // 'atomic', nondivisible expression types at the bottom. Most of
2574 // the functions will simply let the function(s) below them parse,
2575 // and, *if* the syntactic construct they handle is present, wrap
2576 // the AST node that the inner parser gave them in another node.
2577
2578 // Parse a full expression. The optional arguments are used to
2579 // forbid the `in` operator (in for loops initalization expressions)
2580 // and provide reference for storing '=' operator inside shorthand
2581 // property assignment in contexts where both object expression
2582 // and object pattern might appear (so it's possible to raise
2583 // delayed syntax error at correct position).
2584
2585 pp$3.parseExpression = function (noIn, refShorthandDefaultPos) {
2586 var startPos = this.start,
2587 startLoc = this.startLoc;
2588 var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
2589 if (this.type === tt.comma) {
2590 var node = this.startNodeAt(startPos, startLoc);
2591 node.expressions = [expr];
2592 while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
2593 return this.finishNode(node, "SequenceExpression");
2594 }
2595 return expr;
2596 };
2597
2598 // Parse an assignment expression. This includes applications of
2599 // operators like `+=`.
2600
2601 pp$3.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) {
2602 if (this.type == tt._yield && this.inGenerator) return this.parseYield();
2603
2604 var failOnShorthandAssign = undefined;
2605 if (!refShorthandDefaultPos) {
2606 refShorthandDefaultPos = { start: 0 };
2607 failOnShorthandAssign = true;
2608 } else {
2609 failOnShorthandAssign = false;
2610 }
2611 var startPos = this.start,
2612 startLoc = this.startLoc;
2613 if (this.type == tt.parenL || this.type == tt.name) this.potentialArrowAt = this.start;
2614 var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos);
2615 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
2616 if (this.type.isAssign) {
2617 var node = this.startNodeAt(startPos, startLoc);
2618 node.operator = this.value;
2619 node.left = this.type === tt.eq ? this.toAssignable(left) : left;
2620 refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
2621 this.checkLVal(left);
2622 this.next();
2623 node.right = this.parseMaybeAssign(noIn);
2624 return this.finishNode(node, "AssignmentExpression");
2625 } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
2626 this.unexpected(refShorthandDefaultPos.start);
2627 }
2628 return left;
2629 };
2630
2631 // Parse a ternary conditional (`?:`) operator.
2632
2633 pp$3.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
2634 var startPos = this.start,
2635 startLoc = this.startLoc;
2636 var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
2637 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2638 if (this.eat(tt.question)) {
2639 var node = this.startNodeAt(startPos, startLoc);
2640 node.test = expr;
2641 node.consequent = this.parseMaybeAssign();
2642 this.expect(tt.colon);
2643 node.alternate = this.parseMaybeAssign(noIn);
2644 return this.finishNode(node, "ConditionalExpression");
2645 }
2646 return expr;
2647 };
2648
2649 // Start the precedence parser.
2650
2651 pp$3.parseExprOps = function (noIn, refShorthandDefaultPos) {
2652 var startPos = this.start,
2653 startLoc = this.startLoc;
2654 var expr = this.parseMaybeUnary(refShorthandDefaultPos);
2655 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2656 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
2657 };
2658
2659 // Parse binary operators with the operator precedence parsing
2660 // algorithm. `left` is the left-hand side of the operator.
2661 // `minPrec` provides context that allows the function to stop and
2662 // defer further parser to one of its callers when it encounters an
2663 // operator that has a lower precedence than the set it is parsing.
2664
2665 pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
2666 var prec = this.type.binop;
2667 if (prec != null && (!noIn || this.type !== tt._in)) {
2668 if (prec > minPrec) {
2669 var node = this.startNodeAt(leftStartPos, leftStartLoc);
2670 node.left = left;
2671 node.operator = this.value;
2672 var op = this.type;
2673 this.next();
2674 var startPos = this.start,
2675 startLoc = this.startLoc;
2676 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
2677 this.finishNode(node, op === tt.logicalOR || op === tt.logicalAND ? "LogicalExpression" : "BinaryExpression");
2678 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
2679 }
2680 }
2681 return left;
2682 };
2683
2684 // Parse unary operators, both prefix and postfix.
2685
2686 pp$3.parseMaybeUnary = function (refShorthandDefaultPos) {
2687 if (this.type.prefix) {
2688 var node = this.startNode(),
2689 update = this.type === tt.incDec;
2690 node.operator = this.value;
2691 node.prefix = true;
2692 this.next();
2693 node.argument = this.parseMaybeUnary();
2694 if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
2695 if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode");
2696 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
2697 }
2698 var startPos = this.start,
2699 startLoc = this.startLoc;
2700 var expr = this.parseExprSubscripts(refShorthandDefaultPos);
2701 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2702 while (this.type.postfix && !this.canInsertSemicolon()) {
2703 var node = this.startNodeAt(startPos, startLoc);
2704 node.operator = this.value;
2705 node.prefix = false;
2706 node.argument = expr;
2707 this.checkLVal(expr);
2708 this.next();
2709 expr = this.finishNode(node, "UpdateExpression");
2710 }
2711 return expr;
2712 };
2713
2714 // Parse call, dot, and `[]`-subscript expressions.
2715
2716 pp$3.parseExprSubscripts = function (refShorthandDefaultPos) {
2717 var startPos = this.start,
2718 startLoc = this.startLoc;
2719 var expr = this.parseExprAtom(refShorthandDefaultPos);
2720 var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
2721 if (refShorthandDefaultPos && refShorthandDefaultPos.start || skipArrowSubscripts) return expr;
2722 return this.parseSubscripts(expr, startPos, startLoc);
2723 };
2724
2725 pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
2726 for (;;) {
2727 if (this.eat(tt.dot)) {
2728 var node = this.startNodeAt(startPos, startLoc);
2729 node.object = base;
2730 node.property = this.parseIdent(true);
2731 node.computed = false;
2732 base = this.finishNode(node, "MemberExpression");
2733 } else if (this.eat(tt.bracketL)) {
2734 var node = this.startNodeAt(startPos, startLoc);
2735 node.object = base;
2736 node.property = this.parseExpression();
2737 node.computed = true;
2738 this.expect(tt.bracketR);
2739 base = this.finishNode(node, "MemberExpression");
2740 } else if (!noCalls && this.eat(tt.parenL)) {
2741 var node = this.startNodeAt(startPos, startLoc);
2742 node.callee = base;
2743 node.arguments = this.parseExprList(tt.parenR, false);
2744 base = this.finishNode(node, "CallExpression");
2745 } else if (this.type === tt.backQuote) {
2746 var node = this.startNodeAt(startPos, startLoc);
2747 node.tag = base;
2748 node.quasi = this.parseTemplate();
2749 base = this.finishNode(node, "TaggedTemplateExpression");
2750 } else {
2751 return base;
2752 }
2753 }
2754 };
2755
2756 // Parse an atomic expression — either a single token that is an
2757 // expression, an expression started by a keyword like `function` or
2758 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
2759 // or `{}`.
2760
2761 pp$3.parseExprAtom = function (refShorthandDefaultPos) {
2762 var node = undefined,
2763 canBeArrow = this.potentialArrowAt == this.start;
2764 switch (this.type) {
2765 case tt._super:
2766 if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
2767 case tt._this:
2768 var type = this.type === tt._this ? "ThisExpression" : "Super";
2769 node = this.startNode();
2770 this.next();
2771 return this.finishNode(node, type);
2772
2773 case tt._yield:
2774 if (this.inGenerator) this.unexpected();
2775
2776 case tt.name:
2777 var startPos = this.start,
2778 startLoc = this.startLoc;
2779 var id = this.parseIdent(this.type !== tt.name);
2780 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]);
2781 return id;
2782
2783 case tt.regexp:
2784 var value = this.value;
2785 node = this.parseLiteral(value.value);
2786 node.regex = { pattern: value.pattern, flags: value.flags };
2787 return node;
2788
2789 case tt.num:case tt.string:
2790 return this.parseLiteral(this.value);
2791
2792 case tt._null:case tt._true:case tt._false:
2793 node = this.startNode();
2794 node.value = this.type === tt._null ? null : this.type === tt._true;
2795 node.raw = this.type.keyword;
2796 this.next();
2797 return this.finishNode(node, "Literal");
2798
2799 case tt.parenL:
2800 return this.parseParenAndDistinguishExpression(canBeArrow);
2801
2802 case tt.bracketL:
2803 node = this.startNode();
2804 this.next();
2805 // check whether this is array comprehension or regular array
2806 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2807 return this.parseComprehension(node, false);
2808 }
2809 node.elements = this.parseExprList(tt.bracketR, true, true, refShorthandDefaultPos);
2810 return this.finishNode(node, "ArrayExpression");
2811
2812 case tt.braceL:
2813 return this.parseObj(false, refShorthandDefaultPos);
2814
2815 case tt._function:
2816 node = this.startNode();
2817 this.next();
2818 return this.parseFunction(node, false);
2819
2820 case tt._class:
2821 return this.parseClass(this.startNode(), false);
2822
2823 case tt._new:
2824 return this.parseNew();
2825
2826 case tt.backQuote:
2827 return this.parseTemplate();
2828
2829 default:
2830 this.unexpected();
2831 }
2832 };
2833
2834 pp$3.parseLiteral = function (value) {
2835 var node = this.startNode();
2836 node.value = value;
2837 node.raw = this.input.slice(this.start, this.end);
2838 this.next();
2839 return this.finishNode(node, "Literal");
2840 };
2841
2842 pp$3.parseParenExpression = function () {
2843 this.expect(tt.parenL);
2844 var val = this.parseExpression();
2845 this.expect(tt.parenR);
2846 return val;
2847 };
2848
2849 pp$3.parseParenAndDistinguishExpression = function (canBeArrow) {
2850 var startPos = this.start,
2851 startLoc = this.startLoc,
2852 val = undefined;
2853 if (this.options.ecmaVersion >= 6) {
2854 this.next();
2855
2856 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2857 return this.parseComprehension(this.startNodeAt(startPos, startLoc), true);
2858 }
2859
2860 var innerStartPos = this.start,
2861 innerStartLoc = this.startLoc;
2862 var exprList = [],
2863 first = true;
2864 var refShorthandDefaultPos = { start: 0 },
2865 spreadStart = undefined,
2866 innerParenStart = undefined;
2867 while (this.type !== tt.parenR) {
2868 first ? first = false : this.expect(tt.comma);
2869 if (this.type === tt.ellipsis) {
2870 spreadStart = this.start;
2871 exprList.push(this.parseParenItem(this.parseRest()));
2872 break;
2873 } else {
2874 if (this.type === tt.parenL && !innerParenStart) {
2875 innerParenStart = this.start;
2876 }
2877 exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem));
2878 }
2879 }
2880 var innerEndPos = this.start,
2881 innerEndLoc = this.startLoc;
2882 this.expect(tt.parenR);
2883
2884 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
2885 if (innerParenStart) this.unexpected(innerParenStart);
2886 return this.parseParenArrowList(startPos, startLoc, exprList);
2887 }
2888
2889 if (!exprList.length) this.unexpected(this.lastTokStart);
2890 if (spreadStart) this.unexpected(spreadStart);
2891 if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
2892
2893 if (exprList.length > 1) {
2894 val = this.startNodeAt(innerStartPos, innerStartLoc);
2895 val.expressions = exprList;
2896 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
2897 } else {
2898 val = exprList[0];
2899 }
2900 } else {
2901 val = this.parseParenExpression();
2902 }
2903
2904 if (this.options.preserveParens) {
2905 var par = this.startNodeAt(startPos, startLoc);
2906 par.expression = val;
2907 return this.finishNode(par, "ParenthesizedExpression");
2908 } else {
2909 return val;
2910 }
2911 };
2912
2913 pp$3.parseParenItem = function (item) {
2914 return item;
2915 };
2916
2917 pp$3.parseParenArrowList = function (startPos, startLoc, exprList) {
2918 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
2919 };
2920
2921 // New's precedence is slightly tricky. It must allow its argument
2922 // to be a `[]` or dot subscript expression, but not a call — at
2923 // least, not without wrapping it in parentheses. Thus, it uses the
2924
2925 var empty$1 = [];
2926
2927 pp$3.parseNew = function () {
2928 var node = this.startNode();
2929 var meta = this.parseIdent(true);
2930 if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
2931 node.meta = meta;
2932 node.property = this.parseIdent(true);
2933 if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
2934 if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions");
2935 return this.finishNode(node, "MetaProperty");
2936 }
2937 var startPos = this.start,
2938 startLoc = this.startLoc;
2939 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
2940 if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false);else node.arguments = empty$1;
2941 return this.finishNode(node, "NewExpression");
2942 };
2943
2944 // Parse template expression.
2945
2946 pp$3.parseTemplateElement = function () {
2947 var elem = this.startNode();
2948 elem.value = {
2949 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
2950 cooked: this.value
2951 };
2952 this.next();
2953 elem.tail = this.type === tt.backQuote;
2954 return this.finishNode(elem, "TemplateElement");
2955 };
2956
2957 pp$3.parseTemplate = function () {
2958 var node = this.startNode();
2959 this.next();
2960 node.expressions = [];
2961 var curElt = this.parseTemplateElement();
2962 node.quasis = [curElt];
2963 while (!curElt.tail) {
2964 this.expect(tt.dollarBraceL);
2965 node.expressions.push(this.parseExpression());
2966 this.expect(tt.braceR);
2967 node.quasis.push(curElt = this.parseTemplateElement());
2968 }
2969 this.next();
2970 return this.finishNode(node, "TemplateLiteral");
2971 };
2972
2973 // Parse an object literal or binding pattern.
2974
2975 pp$3.parseObj = function (isPattern, refShorthandDefaultPos) {
2976 var node = this.startNode(),
2977 first = true,
2978 propHash = {};
2979 node.properties = [];
2980 this.next();
2981 while (!this.eat(tt.braceR)) {
2982 if (!first) {
2983 this.expect(tt.comma);
2984 if (this.afterTrailingComma(tt.braceR)) break;
2985 } else first = false;
2986
2987 var prop = this.startNode(),
2988 isGenerator = undefined,
2989 startPos = undefined,
2990 startLoc = undefined;
2991 if (this.options.ecmaVersion >= 6) {
2992 prop.method = false;
2993 prop.shorthand = false;
2994 if (isPattern || refShorthandDefaultPos) {
2995 startPos = this.start;
2996 startLoc = this.startLoc;
2997 }
2998 if (!isPattern) isGenerator = this.eat(tt.star);
2999 }
3000 this.parsePropertyName(prop);
3001 this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos);
3002 this.checkPropClash(prop, propHash);
3003 node.properties.push(this.finishNode(prop, "Property"));
3004 }
3005 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
3006 };
3007
3008 pp$3.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos) {
3009 if (this.eat(tt.colon)) {
3010 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
3011 prop.kind = "init";
3012 } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
3013 if (isPattern) this.unexpected();
3014 prop.kind = "init";
3015 prop.method = true;
3016 prop.value = this.parseMethod(isGenerator);
3017 } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type != tt.comma && this.type != tt.braceR) {
3018 if (isGenerator || isPattern) this.unexpected();
3019 prop.kind = prop.key.name;
3020 this.parsePropertyName(prop);
3021 prop.value = this.parseMethod(false);
3022 var paramCount = prop.kind === "get" ? 0 : 1;
3023 if (prop.value.params.length !== paramCount) {
3024 var start = prop.value.start;
3025 if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
3026 }
3027 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
3028 prop.kind = "init";
3029 if (isPattern) {
3030 if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
3031 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3032 } else if (this.type === tt.eq && refShorthandDefaultPos) {
3033 if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start;
3034 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3035 } else {
3036 prop.value = prop.key;
3037 }
3038 prop.shorthand = true;
3039 } else this.unexpected();
3040 };
3041
3042 pp$3.parsePropertyName = function (prop) {
3043 if (this.options.ecmaVersion >= 6) {
3044 if (this.eat(tt.bracketL)) {
3045 prop.computed = true;
3046 prop.key = this.parseMaybeAssign();
3047 this.expect(tt.bracketR);
3048 return prop.key;
3049 } else {
3050 prop.computed = false;
3051 }
3052 }
3053 return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true);
3054 };
3055
3056 // Initialize empty function node.
3057
3058 pp$3.initFunction = function (node) {
3059 node.id = null;
3060 if (this.options.ecmaVersion >= 6) {
3061 node.generator = false;
3062 node.expression = false;
3063 }
3064 };
3065
3066 // Parse object or class method.
3067
3068 pp$3.parseMethod = function (isGenerator) {
3069 var node = this.startNode();
3070 this.initFunction(node);
3071 this.expect(tt.parenL);
3072 node.params = this.parseBindingList(tt.parenR, false, false);
3073 if (this.options.ecmaVersion >= 6) node.generator = isGenerator;
3074 this.parseFunctionBody(node, false);
3075 return this.finishNode(node, "FunctionExpression");
3076 };
3077
3078 // Parse arrow function expression with given parameters.
3079
3080 pp$3.parseArrowExpression = function (node, params) {
3081 this.initFunction(node);
3082 node.params = this.toAssignableList(params, true);
3083 this.parseFunctionBody(node, true);
3084 return this.finishNode(node, "ArrowFunctionExpression");
3085 };
3086
3087 // Parse function body and check parameters.
3088
3089 pp$3.parseFunctionBody = function (node, isArrowFunction) {
3090 var isExpression = isArrowFunction && this.type !== tt.braceL;
3091
3092 if (isExpression) {
3093 node.body = this.parseMaybeAssign();
3094 node.expression = true;
3095 } else {
3096 // Start a new scope with regard to labels and the `inFunction`
3097 // flag (restore them to their old value afterwards).
3098 var oldInFunc = this.inFunction,
3099 oldInGen = this.inGenerator,
3100 oldLabels = this.labels;
3101 this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
3102 node.body = this.parseBlock(true);
3103 node.expression = false;
3104 this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
3105 }
3106
3107 // If this is a strict mode function, verify that argument names
3108 // are not repeated, and it does not try to bind the words `eval`
3109 // or `arguments`.
3110 if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
3111 var oldStrict = this.strict;
3112 this.strict = true;
3113 if (node.id) this.checkLVal(node.id, true);
3114 this.checkParams(node);
3115 this.strict = oldStrict;
3116 } else if (isArrowFunction) {
3117 this.checkParams(node);
3118 }
3119 };
3120
3121 // Checks function params for various disallowed patterns such as using "eval"
3122 // or "arguments" and duplicate parameters.
3123
3124 pp$3.checkParams = function (node) {
3125 var nameHash = {};
3126 for (var i = 0; i < node.params.length; i++) {
3127 this.checkLVal(node.params[i], true, nameHash);
3128 }
3129 };
3130
3131 // Parses a comma-separated list of expressions, and returns them as
3132 // an array. `close` is the token type that ends the list, and
3133 // `allowEmpty` can be turned on to allow subsequent commas with
3134 // nothing in between them to be parsed as `null` (which is needed
3135 // for array literals).
3136
3137 pp$3.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
3138 var elts = [],
3139 first = true;
3140 while (!this.eat(close)) {
3141 if (!first) {
3142 this.expect(tt.comma);
3143 if (allowTrailingComma && this.afterTrailingComma(close)) break;
3144 } else first = false;
3145
3146 var elt = undefined;
3147 if (allowEmpty && this.type === tt.comma) elt = null;else if (this.type === tt.ellipsis) elt = this.parseSpread(refShorthandDefaultPos);else elt = this.parseMaybeAssign(false, refShorthandDefaultPos);
3148 elts.push(elt);
3149 }
3150 return elts;
3151 };
3152
3153 // Parse the next token as an identifier. If `liberal` is true (used
3154 // when parsing properties), it will also convert keywords into
3155 // identifiers.
3156
3157 pp$3.parseIdent = function (liberal) {
3158 var node = this.startNode();
3159 if (liberal && this.options.allowReserved == "never") liberal = false;
3160 if (this.type === tt.name) {
3161 if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
3162 node.name = this.value;
3163 } else if (liberal && this.type.keyword) {
3164 node.name = this.type.keyword;
3165 } else {
3166 this.unexpected();
3167 }
3168 this.next();
3169 return this.finishNode(node, "Identifier");
3170 };
3171
3172 // Parses yield expression inside generator.
3173
3174 pp$3.parseYield = function () {
3175 var node = this.startNode();
3176 this.next();
3177 if (this.type == tt.semi || this.canInsertSemicolon() || this.type != tt.star && !this.type.startsExpr) {
3178 node.delegate = false;
3179 node.argument = null;
3180 } else {
3181 node.delegate = this.eat(tt.star);
3182 node.argument = this.parseMaybeAssign();
3183 }
3184 return this.finishNode(node, "YieldExpression");
3185 };
3186
3187 // Parses array and generator comprehensions.
3188
3189 pp$3.parseComprehension = function (node, isGenerator) {
3190 node.blocks = [];
3191 while (this.type === tt._for) {
3192 var block = this.startNode();
3193 this.next();
3194 this.expect(tt.parenL);
3195 block.left = this.parseBindingAtom();
3196 this.checkLVal(block.left, true);
3197 this.expectContextual("of");
3198 block.right = this.parseExpression();
3199 this.expect(tt.parenR);
3200 node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
3201 }
3202 node.filter = this.eat(tt._if) ? this.parseParenExpression() : null;
3203 node.body = this.parseExpression();
3204 this.expect(isGenerator ? tt.parenR : tt.bracketR);
3205 node.generator = isGenerator;
3206 return this.finishNode(node, "ComprehensionExpression");
3207 };
3208
3209 var pp$4 = Parser.prototype;
3210
3211 // This function is used to raise exceptions on parse errors. It
3212 // takes an offset integer (into the current `input`) to indicate
3213 // the location of the error, attaches the position to the end
3214 // of the error message, and then raises a `SyntaxError` with that
3215 // message.
3216
3217 pp$4.raise = function (pos, message) {
3218 var loc = getLineInfo(this.input, pos);
3219 message += " (" + loc.line + ":" + loc.column + ")";
3220 var err = new SyntaxError(message);
3221 err.pos = pos;err.loc = loc;err.raisedAt = this.pos;
3222 throw err;
3223 };
3224
3225 pp$4.curPosition = function () {
3226 if (this.options.locations) {
3227 return new Position(this.curLine, this.pos - this.lineStart);
3228 }
3229 };
3230
3231 var Node = function Node(parser, pos, loc) {
3232 babelHelpers.classCallCheck(this, Node);
3233
3234 this.type = "";
3235 this.start = pos;
3236 this.end = 0;
3237 if (parser.options.locations) this.loc = new SourceLocation(parser, loc);
3238 if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
3239 if (parser.options.ranges) this.range = [pos, 0];
3240 }
3241
3242 // Start an AST node, attaching a start offset.
3243
3244 ;
3245
3246 var pp$5 = Parser.prototype;
3247
3248 pp$5.startNode = function () {
3249 return new Node(this, this.start, this.startLoc);
3250 };
3251
3252 pp$5.startNodeAt = function (pos, loc) {
3253 return new Node(this, pos, loc);
3254 };
3255
3256 // Finish an AST node, adding `type` and `end` properties.
3257
3258 function finishNodeAt(node, type, pos, loc) {
3259 node.type = type;
3260 node.end = pos;
3261 if (this.options.locations) node.loc.end = loc;
3262 if (this.options.ranges) node.range[1] = pos;
3263 return node;
3264 }
3265
3266 pp$5.finishNode = function (node, type) {
3267 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
3268 };
3269
3270 // Finish node at given position
3271
3272 pp$5.finishNodeAt = function (node, type, pos, loc) {
3273 return finishNodeAt.call(this, node, type, pos, loc);
3274 };
3275
3276 var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
3277 babelHelpers.classCallCheck(this, TokContext);
3278
3279 this.token = token;
3280 this.isExpr = !!isExpr;
3281 this.preserveSpace = !!preserveSpace;
3282 this.override = override;
3283 };
3284
3285 var types = {
3286 b_stat: new TokContext("{", false),
3287 b_expr: new TokContext("{", true),
3288 b_tmpl: new TokContext("${", true),
3289 p_stat: new TokContext("(", false),
3290 p_expr: new TokContext("(", true),
3291 q_tmpl: new TokContext("`", true, true, function (p) {
3292 return p.readTmplToken();
3293 }),
3294 f_expr: new TokContext("function", true)
3295 };
3296
3297 var pp$6 = Parser.prototype;
3298
3299 pp$6.initialContext = function () {
3300 return [types.b_stat];
3301 };
3302
3303 pp$6.braceIsBlock = function (prevType) {
3304 if (prevType === tt.colon) {
3305 var _parent = this.curContext();
3306 if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr;
3307 }
3308 if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
3309 if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true;
3310 if (prevType == tt.braceL) return this.curContext() === types.b_stat;
3311 return !this.exprAllowed;
3312 };
3313
3314 pp$6.updateContext = function (prevType) {
3315 var update = undefined,
3316 type = this.type;
3317 if (type.keyword && prevType == tt.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
3318 };
3319
3320 // Token-specific context update code
3321
3322 tt.parenR.updateContext = tt.braceR.updateContext = function () {
3323 if (this.context.length == 1) {
3324 this.exprAllowed = true;
3325 return;
3326 }
3327 var out = this.context.pop();
3328 if (out === types.b_stat && this.curContext() === types.f_expr) {
3329 this.context.pop();
3330 this.exprAllowed = false;
3331 } else if (out === types.b_tmpl) {
3332 this.exprAllowed = true;
3333 } else {
3334 this.exprAllowed = !out.isExpr;
3335 }
3336 };
3337
3338 tt.braceL.updateContext = function (prevType) {
3339 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
3340 this.exprAllowed = true;
3341 };
3342
3343 tt.dollarBraceL.updateContext = function () {
3344 this.context.push(types.b_tmpl);
3345 this.exprAllowed = true;
3346 };
3347
3348 tt.parenL.updateContext = function (prevType) {
3349 var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
3350 this.context.push(statementParens ? types.p_stat : types.p_expr);
3351 this.exprAllowed = true;
3352 };
3353
3354 tt.incDec.updateContext = function () {
3355 // tokExprAllowed stays unchanged
3356 };
3357
3358 tt._function.updateContext = function () {
3359 if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
3360 this.exprAllowed = false;
3361 };
3362
3363 tt.backQuote.updateContext = function () {
3364 if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
3365 this.exprAllowed = false;
3366 };
3367
3368 // Object type used to represent tokens. Note that normally, tokens
3369 // simply exist as properties on the parser object. This is only
3370 // used for the onToken callback and the external tokenizer.
3371
3372 var Token = function Token(p) {
3373 babelHelpers.classCallCheck(this, Token);
3374
3375 this.type = p.type;
3376 this.value = p.value;
3377 this.start = p.start;
3378 this.end = p.end;
3379 if (p.options.locations) this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
3380 if (p.options.ranges) this.range = [p.start, p.end];
3381 }
3382
3383 // ## Tokenizer
3384
3385 ;
3386
3387 var pp$7 = Parser.prototype;
3388
3389 // Are we running under Rhino?
3390 var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
3391
3392 // Move to the next token
3393
3394 pp$7.next = function () {
3395 if (this.options.onToken) this.options.onToken(new Token(this));
3396
3397 this.lastTokEnd = this.end;
3398 this.lastTokStart = this.start;
3399 this.lastTokEndLoc = this.endLoc;
3400 this.lastTokStartLoc = this.startLoc;
3401 this.nextToken();
3402 };
3403
3404 pp$7.getToken = function () {
3405 this.next();
3406 return new Token(this);
3407 };
3408
3409 // If we're in an ES6 environment, make parsers iterable
3410 if (typeof Symbol !== "undefined") pp$7[Symbol.iterator] = function () {
3411 var self = this;
3412 return { next: function () {
3413 var token = self.getToken();
3414 return {
3415 done: token.type === tt.eof,
3416 value: token
3417 };
3418 } };
3419 };
3420
3421 // Toggle strict mode. Re-reads the next number or string to please
3422 // pedantic tests (`"use strict"; 010;` should fail).
3423
3424 pp$7.setStrict = function (strict) {
3425 this.strict = strict;
3426 if (this.type !== tt.num && this.type !== tt.string) return;
3427 this.pos = this.start;
3428 if (this.options.locations) {
3429 while (this.pos < this.lineStart) {
3430 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
3431 --this.curLine;
3432 }
3433 }
3434 this.nextToken();
3435 };
3436
3437 pp$7.curContext = function () {
3438 return this.context[this.context.length - 1];
3439 };
3440
3441 // Read a single token, updating the parser object's token-related
3442 // properties.
3443
3444 pp$7.nextToken = function () {
3445 var curContext = this.curContext();
3446 if (!curContext || !curContext.preserveSpace) this.skipSpace();
3447
3448 this.start = this.pos;
3449 if (this.options.locations) this.startLoc = this.curPosition();
3450 if (this.pos >= this.input.length) return this.finishToken(tt.eof);
3451
3452 if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
3453 };
3454
3455 pp$7.readToken = function (code) {
3456 // Identifier or keyword. '\uXXXX' sequences are allowed in
3457 // identifiers, so '\' also dispatches to that.
3458 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
3459
3460 return this.getTokenFromCode(code);
3461 };
3462
3463 pp$7.fullCharCodeAtPos = function () {
3464 var code = this.input.charCodeAt(this.pos);
3465 if (code <= 0xd7ff || code >= 0xe000) return code;
3466 var next = this.input.charCodeAt(this.pos + 1);
3467 return (code << 10) + next - 0x35fdc00;
3468 };
3469
3470 pp$7.skipBlockComment = function () {
3471 var startLoc = this.options.onComment && this.curPosition();
3472 var start = this.pos,
3473 end = this.input.indexOf("*/", this.pos += 2);
3474 if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
3475 this.pos = end + 2;
3476 if (this.options.locations) {
3477 lineBreakG.lastIndex = start;
3478 var match = undefined;
3479 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
3480 ++this.curLine;
3481 this.lineStart = match.index + match[0].length;
3482 }
3483 }
3484 if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
3485 };
3486
3487 pp$7.skipLineComment = function (startSkip) {
3488 var start = this.pos;
3489 var startLoc = this.options.onComment && this.curPosition();
3490 var ch = this.input.charCodeAt(this.pos += startSkip);
3491 while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
3492 ++this.pos;
3493 ch = this.input.charCodeAt(this.pos);
3494 }
3495 if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
3496 };
3497
3498 // Called at the start of the parse and after every token. Skips
3499 // whitespace and comments, and.
3500
3501 pp$7.skipSpace = function () {
3502 loop: while (this.pos < this.input.length) {
3503 var ch = this.input.charCodeAt(this.pos);
3504 switch (ch) {
3505 case 32:case 160:
3506 // ' '
3507 ++this.pos;
3508 break;
3509 case 13:
3510 if (this.input.charCodeAt(this.pos + 1) === 10) {
3511 ++this.pos;
3512 }
3513 case 10:case 8232:case 8233:
3514 ++this.pos;
3515 if (this.options.locations) {
3516 ++this.curLine;
3517 this.lineStart = this.pos;
3518 }
3519 break;
3520 case 47:
3521 // '/'
3522 switch (this.input.charCodeAt(this.pos + 1)) {
3523 case 42:
3524 // '*'
3525 this.skipBlockComment();
3526 break;
3527 case 47:
3528 this.skipLineComment(2);
3529 break;
3530 default:
3531 break loop;
3532 }
3533 break;
3534 default:
3535 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
3536 ++this.pos;
3537 } else {
3538 break loop;
3539 }
3540 }
3541 }
3542 };
3543
3544 // Called at the end of every token. Sets `end`, `val`, and
3545 // maintains `context` and `exprAllowed`, and skips the space after
3546 // the token, so that the next one's `start` will point at the
3547 // right position.
3548
3549 pp$7.finishToken = function (type, val) {
3550 this.end = this.pos;
3551 if (this.options.locations) this.endLoc = this.curPosition();
3552 var prevType = this.type;
3553 this.type = type;
3554 this.value = val;
3555
3556 this.updateContext(prevType);
3557 };
3558
3559 // ### Token reading
3560
3561 // This is the function that is called to fetch the next token. It
3562 // is somewhat obscure, because it works in character codes rather
3563 // than characters, and because operator parsing has been inlined
3564 // into it.
3565 //
3566 // All in the name of speed.
3567 //
3568 pp$7.readToken_dot = function () {
3569 var next = this.input.charCodeAt(this.pos + 1);
3570 if (next >= 48 && next <= 57) return this.readNumber(true);
3571 var next2 = this.input.charCodeAt(this.pos + 2);
3572 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
3573 // 46 = dot '.'
3574 this.pos += 3;
3575 return this.finishToken(tt.ellipsis);
3576 } else {
3577 ++this.pos;
3578 return this.finishToken(tt.dot);
3579 }
3580 };
3581
3582 pp$7.readToken_slash = function () {
3583 // '/'
3584 var next = this.input.charCodeAt(this.pos + 1);
3585 if (this.exprAllowed) {
3586 ++this.pos;return this.readRegexp();
3587 }
3588 if (next === 61) return this.finishOp(tt.assign, 2);
3589 return this.finishOp(tt.slash, 1);
3590 };
3591
3592 pp$7.readToken_mult_modulo = function (code) {
3593 // '%*'
3594 var next = this.input.charCodeAt(this.pos + 1);
3595 if (next === 61) return this.finishOp(tt.assign, 2);
3596 return this.finishOp(code === 42 ? tt.star : tt.modulo, 1);
3597 };
3598
3599 pp$7.readToken_pipe_amp = function (code) {
3600 // '|&'
3601 var next = this.input.charCodeAt(this.pos + 1);
3602 if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2);
3603 if (next === 61) return this.finishOp(tt.assign, 2);
3604 return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1);
3605 };
3606
3607 pp$7.readToken_caret = function () {
3608 // '^'
3609 var next = this.input.charCodeAt(this.pos + 1);
3610 if (next === 61) return this.finishOp(tt.assign, 2);
3611 return this.finishOp(tt.bitwiseXOR, 1);
3612 };
3613
3614 pp$7.readToken_plus_min = function (code) {
3615 // '+-'
3616 var next = this.input.charCodeAt(this.pos + 1);
3617 if (next === code) {
3618 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
3619 // A `-->` line comment
3620 this.skipLineComment(3);
3621 this.skipSpace();
3622 return this.nextToken();
3623 }
3624 return this.finishOp(tt.incDec, 2);
3625 }
3626 if (next === 61) return this.finishOp(tt.assign, 2);
3627 return this.finishOp(tt.plusMin, 1);
3628 };
3629
3630 pp$7.readToken_lt_gt = function (code) {
3631 // '<>'
3632 var next = this.input.charCodeAt(this.pos + 1);
3633 var size = 1;
3634 if (next === code) {
3635 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
3636 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1);
3637 return this.finishOp(tt.bitShift, size);
3638 }
3639 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
3640 if (this.inModule) this.unexpected();
3641 // `<!--`, an XML-style comment that should be interpreted as a line comment
3642 this.skipLineComment(4);
3643 this.skipSpace();
3644 return this.nextToken();
3645 }
3646 if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
3647 return this.finishOp(tt.relational, size);
3648 };
3649
3650 pp$7.readToken_eq_excl = function (code) {
3651 // '=!'
3652 var next = this.input.charCodeAt(this.pos + 1);
3653 if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
3654 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
3655 // '=>'
3656 this.pos += 2;
3657 return this.finishToken(tt.arrow);
3658 }
3659 return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1);
3660 };
3661
3662 pp$7.getTokenFromCode = function (code) {
3663 switch (code) {
3664 // The interpretation of a dot depends on whether it is followed
3665 // by a digit or another two dots.
3666 case 46:
3667 // '.'
3668 return this.readToken_dot();
3669
3670 // Punctuation tokens.
3671 case 40:
3672 ++this.pos;return this.finishToken(tt.parenL);
3673 case 41:
3674 ++this.pos;return this.finishToken(tt.parenR);
3675 case 59:
3676 ++this.pos;return this.finishToken(tt.semi);
3677 case 44:
3678 ++this.pos;return this.finishToken(tt.comma);
3679 case 91:
3680 ++this.pos;return this.finishToken(tt.bracketL);
3681 case 93:
3682 ++this.pos;return this.finishToken(tt.bracketR);
3683 case 123:
3684 ++this.pos;return this.finishToken(tt.braceL);
3685 case 125:
3686 ++this.pos;return this.finishToken(tt.braceR);
3687 case 58:
3688 ++this.pos;return this.finishToken(tt.colon);
3689 case 63:
3690 ++this.pos;return this.finishToken(tt.question);
3691
3692 case 96:
3693 // '`'
3694 if (this.options.ecmaVersion < 6) break;
3695 ++this.pos;
3696 return this.finishToken(tt.backQuote);
3697
3698 case 48:
3699 // '0'
3700 var next = this.input.charCodeAt(this.pos + 1);
3701 if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
3702 if (this.options.ecmaVersion >= 6) {
3703 if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
3704 if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
3705 }
3706 // Anything else beginning with a digit is an integer, octal
3707 // number, or float.
3708 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
3709 // 1-9
3710 return this.readNumber(false);
3711
3712 // Quotes produce strings.
3713 case 34:case 39:
3714 // '"', "'"
3715 return this.readString(code);
3716
3717 // Operators are parsed inline in tiny state machines. '=' (61) is
3718 // often referred to. `finishOp` simply skips the amount of
3719 // characters it is given as second argument, and returns a token
3720 // of the type given by its first argument.
3721
3722 case 47:
3723 // '/'
3724 return this.readToken_slash();
3725
3726 case 37:case 42:
3727 // '%*'
3728 return this.readToken_mult_modulo(code);
3729
3730 case 124:case 38:
3731 // '|&'
3732 return this.readToken_pipe_amp(code);
3733
3734 case 94:
3735 // '^'
3736 return this.readToken_caret();
3737
3738 case 43:case 45:
3739 // '+-'
3740 return this.readToken_plus_min(code);
3741
3742 case 60:case 62:
3743 // '<>'
3744 return this.readToken_lt_gt(code);
3745
3746 case 61:case 33:
3747 // '=!'
3748 return this.readToken_eq_excl(code);
3749
3750 case 126:
3751 // '~'
3752 return this.finishOp(tt.prefix, 1);
3753 }
3754
3755 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
3756 };
3757
3758 pp$7.finishOp = function (type, size) {
3759 var str = this.input.slice(this.pos, this.pos + size);
3760 this.pos += size;
3761 return this.finishToken(type, str);
3762 };
3763
3764 // Parse a regular expression. Some context-awareness is necessary,
3765 // since a '/' inside a '[]' set does not end the expression.
3766
3767 function tryCreateRegexp(src, flags, throwErrorAt, parser) {
3768 try {
3769 return new RegExp(src, flags);
3770 } catch (e) {
3771 if (throwErrorAt !== undefined) {
3772 if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
3773 throw e;
3774 }
3775 }
3776 }
3777
3778 var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
3779
3780 pp$7.readRegexp = function () {
3781 var _this = this;
3782
3783 var escaped = undefined,
3784 inClass = undefined,
3785 start = this.pos;
3786 for (;;) {
3787 if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
3788 var ch = this.input.charAt(this.pos);
3789 if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
3790 if (!escaped) {
3791 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;
3792 escaped = ch === "\\";
3793 } else escaped = false;
3794 ++this.pos;
3795 }
3796 var content = this.input.slice(start, this.pos);
3797 ++this.pos;
3798 // Need to use `readWord1` because '\uXXXX' sequences are allowed
3799 // here (don't ask).
3800 var mods = this.readWord1();
3801 var tmp = content;
3802 if (mods) {
3803 var validFlags = /^[gmsiy]*$/;
3804 if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
3805 if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
3806 if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
3807 // Replace each astral symbol and every Unicode escape sequence that
3808 // possibly represents an astral symbol or a paired surrogate with a
3809 // single ASCII symbol to avoid throwing on regular expressions that
3810 // are only valid in combination with the `/u` flag.
3811 // Note: replacing with the ASCII symbol `x` might cause false
3812 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
3813 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
3814 // be replaced by `[x-b]` which throws an error.
3815 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
3816 code = Number("0x" + code);
3817 if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
3818 return "x";
3819 });
3820 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
3821 }
3822 }
3823 // Detect invalid regular expressions.
3824 var value = null;
3825 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
3826 // so don't do detection if we are running under Rhino
3827 if (!isRhino) {
3828 tryCreateRegexp(tmp, undefined, start, this);
3829 // Get a regular expression object for this pattern-flag pair, or `null` in
3830 // case the current environment doesn't support the flags it uses.
3831 value = tryCreateRegexp(content, mods);
3832 }
3833 return this.finishToken(tt.regexp, { pattern: content, flags: mods, value: value });
3834 };
3835
3836 // Read an integer in the given radix. Return null if zero digits
3837 // were read, the integer value otherwise. When `len` is given, this
3838 // will return `null` unless the integer has exactly `len` digits.
3839
3840 pp$7.readInt = function (radix, len) {
3841 var start = this.pos,
3842 total = 0;
3843 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
3844 var code = this.input.charCodeAt(this.pos),
3845 val = undefined;
3846 if (code >= 97) val = code - 97 + 10; // a
3847 else if (code >= 65) val = code - 65 + 10; // A
3848 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
3849 else val = Infinity;
3850 if (val >= radix) break;
3851 ++this.pos;
3852 total = total * radix + val;
3853 }
3854 if (this.pos === start || len != null && this.pos - start !== len) return null;
3855
3856 return total;
3857 };
3858
3859 pp$7.readRadixNumber = function (radix) {
3860 this.pos += 2; // 0x
3861 var val = this.readInt(radix);
3862 if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
3863 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3864 return this.finishToken(tt.num, val);
3865 };
3866
3867 // Read an integer, octal integer, or floating-point number.
3868
3869 pp$7.readNumber = function (startsWithDot) {
3870 var start = this.pos,
3871 isFloat = false,
3872 octal = this.input.charCodeAt(this.pos) === 48;
3873 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
3874 var next = this.input.charCodeAt(this.pos);
3875 if (next === 46) {
3876 // '.'
3877 ++this.pos;
3878 this.readInt(10);
3879 isFloat = true;
3880 next = this.input.charCodeAt(this.pos);
3881 }
3882 if (next === 69 || next === 101) {
3883 // 'eE'
3884 next = this.input.charCodeAt(++this.pos);
3885 if (next === 43 || next === 45) ++this.pos; // '+-'
3886 if (this.readInt(10) === null) this.raise(start, "Invalid number");
3887 isFloat = true;
3888 }
3889 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3890
3891 var str = this.input.slice(start, this.pos),
3892 val = undefined;
3893 if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number");else val = parseInt(str, 8);
3894 return this.finishToken(tt.num, val);
3895 };
3896
3897 // Read a string value, interpreting backslash-escapes.
3898
3899 pp$7.readCodePoint = function () {
3900 var ch = this.input.charCodeAt(this.pos),
3901 code = undefined;
3902
3903 if (ch === 123) {
3904 if (this.options.ecmaVersion < 6) this.unexpected();
3905 var codePos = ++this.pos;
3906 code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
3907 ++this.pos;
3908 if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
3909 } else {
3910 code = this.readHexChar(4);
3911 }
3912 return code;
3913 };
3914
3915 function codePointToString(code) {
3916 // UTF-16 Decoding
3917 if (code <= 0xFFFF) return String.fromCharCode(code);
3918 code -= 0x10000;
3919 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
3920 }
3921
3922 pp$7.readString = function (quote) {
3923 var out = "",
3924 chunkStart = ++this.pos;
3925 for (;;) {
3926 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
3927 var ch = this.input.charCodeAt(this.pos);
3928 if (ch === quote) break;
3929 if (ch === 92) {
3930 // '\'
3931 out += this.input.slice(chunkStart, this.pos);
3932 out += this.readEscapedChar(false);
3933 chunkStart = this.pos;
3934 } else {
3935 if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
3936 ++this.pos;
3937 }
3938 }
3939 out += this.input.slice(chunkStart, this.pos++);
3940 return this.finishToken(tt.string, out);
3941 };
3942
3943 // Reads template string tokens.
3944
3945 pp$7.readTmplToken = function () {
3946 var out = "",
3947 chunkStart = this.pos;
3948 for (;;) {
3949 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
3950 var ch = this.input.charCodeAt(this.pos);
3951 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
3952 // '`', '${'
3953 if (this.pos === this.start && this.type === tt.template) {
3954 if (ch === 36) {
3955 this.pos += 2;
3956 return this.finishToken(tt.dollarBraceL);
3957 } else {
3958 ++this.pos;
3959 return this.finishToken(tt.backQuote);
3960 }
3961 }
3962 out += this.input.slice(chunkStart, this.pos);
3963 return this.finishToken(tt.template, out);
3964 }
3965 if (ch === 92) {
3966 // '\'
3967 out += this.input.slice(chunkStart, this.pos);
3968 out += this.readEscapedChar(true);
3969 chunkStart = this.pos;
3970 } else if (isNewLine(ch)) {
3971 out += this.input.slice(chunkStart, this.pos);
3972 ++this.pos;
3973 switch (ch) {
3974 case 13:
3975 if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
3976 case 10:
3977 out += "\n";
3978 break;
3979 default:
3980 out += String.fromCharCode(ch);
3981 break;
3982 }
3983 if (this.options.locations) {
3984 ++this.curLine;
3985 this.lineStart = this.pos;
3986 }
3987 chunkStart = this.pos;
3988 } else {
3989 ++this.pos;
3990 }
3991 }
3992 };
3993
3994 // Used to read escaped characters
3995
3996 pp$7.readEscapedChar = function (inTemplate) {
3997 var ch = this.input.charCodeAt(++this.pos);
3998 ++this.pos;
3999 switch (ch) {
4000 case 110:
4001 return "\n"; // 'n' -> '\n'
4002 case 114:
4003 return "\r"; // 'r' -> '\r'
4004 case 120:
4005 return String.fromCharCode(this.readHexChar(2)); // 'x'
4006 case 117:
4007 return codePointToString(this.readCodePoint()); // 'u'
4008 case 116:
4009 return "\t"; // 't' -> '\t'
4010 case 98:
4011 return "\b"; // 'b' -> '\b'
4012 case 118:
4013 return "\u000b"; // 'v' -> '\u000b'
4014 case 102:
4015 return "\f"; // 'f' -> '\f'
4016 case 13:
4017 if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
4018 case 10:
4019 // ' \n'
4020 if (this.options.locations) {
4021 this.lineStart = this.pos;++this.curLine;
4022 }
4023 return "";
4024 default:
4025 if (ch >= 48 && ch <= 55) {
4026 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
4027 var octal = parseInt(octalStr, 8);
4028 if (octal > 255) {
4029 octalStr = octalStr.slice(0, -1);
4030 octal = parseInt(octalStr, 8);
4031 }
4032 if (octal > 0 && (this.strict || inTemplate)) {
4033 this.raise(this.pos - 2, "Octal literal in strict mode");
4034 }
4035 this.pos += octalStr.length - 1;
4036 return String.fromCharCode(octal);
4037 }
4038 return String.fromCharCode(ch);
4039 }
4040 };
4041
4042 // Used to read character escape sequences ('\x', '\u', '\U').
4043
4044 pp$7.readHexChar = function (len) {
4045 var codePos = this.pos;
4046 var n = this.readInt(16, len);
4047 if (n === null) this.raise(codePos, "Bad character escape sequence");
4048 return n;
4049 };
4050
4051 // Read an identifier, and return it as a string. Sets `this.containsEsc`
4052 // to whether the word contained a '\u' escape.
4053 //
4054 // Incrementally adds only escaped chars, adding other chunks as-is
4055 // as a micro-optimization.
4056
4057 pp$7.readWord1 = function () {
4058 this.containsEsc = false;
4059 var word = "",
4060 first = true,
4061 chunkStart = this.pos;
4062 var astral = this.options.ecmaVersion >= 6;
4063 while (this.pos < this.input.length) {
4064 var ch = this.fullCharCodeAtPos();
4065 if (isIdentifierChar(ch, astral)) {
4066 this.pos += ch <= 0xffff ? 1 : 2;
4067 } else if (ch === 92) {
4068 // "\"
4069 this.containsEsc = true;
4070 word += this.input.slice(chunkStart, this.pos);
4071 var escStart = this.pos;
4072 if (this.input.charCodeAt(++this.pos) != 117) // "u"
4073 this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
4074 ++this.pos;
4075 var esc = this.readCodePoint();
4076 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
4077 word += codePointToString(esc);
4078 chunkStart = this.pos;
4079 } else {
4080 break;
4081 }
4082 first = false;
4083 }
4084 return word + this.input.slice(chunkStart, this.pos);
4085 };
4086
4087 // Read an identifier or keyword token. Will check for reserved
4088 // words when necessary.
4089
4090 pp$7.readWord = function () {
4091 var word = this.readWord1();
4092 var type = tt.name;
4093 if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = keywordTypes[word];
4094 return this.finishToken(type, word);
4095 };
4096
4097 // The main exported interface (under `self.acorn` when in the
4098 // browser) is a `parse` function that takes a code string and
4099 // returns an abstract syntax tree as specified by [Mozilla parser
4100 // API][api].
4101 //
4102 // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
4103
4104 function parse(input, options) {
4105 return new Parser(options, input).parse();
4106 }
4107
4108 function walk(ast, _ref) {
4109 var enter = _ref.enter;
4110 var leave = _ref.leave;
4111
4112 visit(ast, null, enter, leave);
4113 }
4114
4115 var context = {
4116 skip: function skip() {
4117 return context.shouldSkip = true;
4118 }
4119 };
4120
4121 var childKeys = {};
4122
4123 var toString = Object.prototype.toString;
4124
4125 function isArray(thing) {
4126 return toString.call(thing) === '[object Array]';
4127 }
4128
4129 function visit(node, parent, enter, leave, prop, index) {
4130 if (!node) return;
4131
4132 if (enter) {
4133 context.shouldSkip = false;
4134 enter.call(context, node, parent, prop, index);
4135 if (context.shouldSkip) return;
4136 }
4137
4138 var keys = childKeys[node.type] || (childKeys[node.type] = Object.keys(node).filter(function (prop) {
4139 return typeof node[prop] === 'object';
4140 }));
4141
4142 var key = undefined,
4143 value = undefined,
4144 i = undefined,
4145 j = undefined;
4146
4147 i = keys.length;
4148 while (i--) {
4149 key = keys[i];
4150 value = node[key];
4151
4152 if (isArray(value)) {
4153 j = value.length;
4154 while (j--) {
4155 visit(value[j], node, enter, leave, key, j);
4156 }
4157 } else if (value && value.type) {
4158 visit(value, node, enter, leave, key, null);
4159 }
4160 }
4161
4162 if (leave) {
4163 leave(node, parent, prop, index);
4164 }
4165 }
4166
4167 var modifierNodes = {
4168 AssignmentExpression: 'left',
4169 UpdateExpression: 'argument'
4170 };
4171
4172 function isReference(node, parent) {
4173 if (node.type === 'MemberExpression') {
4174 return !node.computed && isReference(node.object, node);
4175 }
4176
4177 if (node.type === 'Identifier') {
4178 // TODO is this right?
4179 if (parent.type === 'MemberExpression') return parent.computed || node === parent.object;
4180
4181 // disregard the `bar` in { bar: foo }
4182 if (parent.type === 'Property' && node !== parent.value) return false;
4183
4184 // disregard the `bar` in `class Foo { bar () {...} }`
4185 if (parent.type === 'MethodDefinition') return false;
4186
4187 // disregard the `bar` in `export { foo as bar }`
4188 if (parent.type === 'ExportSpecifier' && node !== parent.local) return;
4189
4190 return true;
4191 }
4192 }
4193
4194 function flatten(node) {
4195 var parts = [];
4196 while (node.type === 'MemberExpression') {
4197 if (node.computed) return null;
4198 parts.unshift(node.property.name);
4199
4200 node = node.object;
4201 }
4202
4203 if (node.type !== 'Identifier') return null;
4204
4205 var name = node.name;
4206 parts.unshift(name);
4207
4208 return { name: name, keypath: parts.join('.') };
4209 }
4210
4211 var pureFunctions = {};
4212
4213 var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
4214 var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
4215 var simdMethods = 'abs add and bool check div equal extractLane fromFloat32x4 fromFloat32x4Bits fromFloat64x2 fromFloat64x2Bits fromInt16x8Bits fromInt32x4 fromInt32x4Bits fromInt8x16Bits greaterThan greaterThanOrEqual lessThan lessThanOrEqual load max maxNum min minNum mul neg not notEqual or reciprocalApproximation reciprocalSqrtApproximation replaceLane select selectBits shiftLeftByScalar shiftRightArithmeticByScalar shiftRightLogicalByScalar shuffle splat sqrt store sub swizzle xor'.split(' ');
4216 var allSimdMethods = [];
4217 simdTypes.forEach(function (t) {
4218 simdMethods.forEach(function (m) {
4219 allSimdMethods.push('SIMD.' + t + '.' + m);
4220 });
4221 });
4222
4223 ['Array.isArray', 'Error', 'EvalError', 'InternalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'unescape', 'Object', 'Object.create', 'Object.getNotifier', 'Object.getOwn', 'Object.getOwnPropertyDescriptor', 'Object.getOwnPropertyNames', 'Object.getOwnPropertySymbols', 'Object.getPrototypeOf', 'Object.is', 'Object.isExtensible', 'Object.isFrozen', 'Object.isSealed', 'Object.keys', 'Function', 'Boolean', 'Number', 'Number.isFinite', 'Number.isInteger', 'Number.isNaN', 'Number.isSafeInteger', 'Number.parseFloat', 'Number.parseInt', 'Symbol', 'Symbol.for', 'Symbol.keyFor', 'Math.abs', 'Math.acos', 'Math.acosh', 'Math.asin', 'Math.asinh', 'Math.atan', 'Math.atan2', 'Math.atanh', 'Math.cbrt', 'Math.ceil', 'Math.clz32', 'Math.cos', 'Math.cosh', 'Math.exp', 'Math.expm1', 'Math.floor', 'Math.fround', 'Math.hypot', 'Math.imul', 'Math.log', 'Math.log10', 'Math.log1p', 'Math.log2', 'Math.max', 'Math.min', 'Math.pow', 'Math.random', 'Math.round', 'Math.sign', 'Math.sin', 'Math.sinh', 'Math.sqrt', 'Math.tan', 'Math.tanh', 'Math.trunc', 'Date', 'Date.UTC', 'Date.now', 'Date.parse', 'String', 'String.fromCharCode', 'String.fromCodePoint', 'String.raw', 'RegExp', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'ArrayBuffer.isView', 'DataView', 'JSON.parse', 'JSON.stringify', 'Promise', 'Promise.all', 'Promise.race', 'Promise.reject', 'Promise.resolve', 'Intl.Collator', 'Intl.Collator.supportedLocalesOf', 'Intl.DateTimeFormat', 'Intl.DateTimeFormat.supportedLocalesOf', 'Intl.NumberFormat', 'Intl.NumberFormat.supportedLocalesOf'
4224
4225 // TODO properties of e.g. window...
4226 ].concat(arrayTypes, arrayTypes.map(function (t) {
4227 return t + '.from';
4228 }), arrayTypes.map(function (t) {
4229 return t + '.of';
4230 }), simdTypes.map(function (t) {
4231 return 'SIMD.' + t;
4232 }), allSimdMethods).forEach(function (name) {
4233 return pureFunctions[name] = true;
4234 });
4235 // TODO add others to this list from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
4236
4237 function run(node, scope, statement, strongDependencies, force) {
4238 var hasSideEffect = false;
4239
4240 walk(node, {
4241 enter: function (node, parent) {
4242 if (!force && /Function/.test(node.type)) return this.skip();
4243
4244 if (node._scope) scope = node._scope;
4245
4246 if (isReference(node, parent)) {
4247 var flattened = flatten(node);
4248
4249 if (flattened.name === 'arguments') {
4250 hasSideEffect = true;
4251 }if (!scope.contains(flattened.name)) {
4252 var declaration = statement.module.trace(flattened.name);
4253 if (declaration && !declaration.isExternal) {
4254 var _module = declaration.module || declaration.statement.module; // TODO is this right?
4255 if (!_module.isExternal && ! ~strongDependencies.indexOf(_module)) strongDependencies.push(_module);
4256 }
4257 }
4258 } else if (node.type === 'ThrowStatement') {
4259 // we only care about errors thrown at the top level, otherwise
4260 // any function with error checking gets included if called
4261 if (scope.isTopLevel) hasSideEffect = true;
4262 } else if (node.type === 'CallExpression' || node.type === 'NewExpression') {
4263 if (node.callee.type === 'Identifier') {
4264 var declaration = scope.findDeclaration(node.callee.name) || statement.module.trace(node.callee.name);
4265
4266 if (declaration) {
4267 if (declaration.isExternal || declaration.run(strongDependencies)) {
4268 hasSideEffect = true;
4269 }
4270 } else if (!pureFunctions[node.callee.name]) {
4271 hasSideEffect = true;
4272 }
4273 } else if (node.callee.type === 'MemberExpression') {
4274 var flattened = flatten(node.callee);
4275
4276 if (flattened) {
4277 // if we're calling e.g. Object.keys(thing), there are no side-effects
4278 // TODO make pureFunctions configurable
4279 var declaration = scope.findDeclaration(flattened.name) || statement.module.trace(flattened.name);
4280
4281 if (!!declaration || !pureFunctions[flattened.keypath]) {
4282 hasSideEffect = true;
4283 }
4284 } else {
4285 // is not a keypath like `foo.bar.baz` – could be e.g.
4286 // `(a || b).foo()`. Err on the side of caution
4287 hasSideEffect = true;
4288 }
4289 }
4290
4291 // otherwise we're probably dealing with a function expression
4292 else if (run(node.callee, scope, statement, strongDependencies, true)) {
4293 hasSideEffect = true;
4294 }
4295 } else if (node.type in modifierNodes) {
4296 var subject = node[modifierNodes[node.type]];
4297 while (subject.type === 'MemberExpression') subject = subject.object;
4298
4299 var declaration = scope.findDeclaration(subject.name);
4300
4301 if (declaration) {
4302 if (declaration.isParam) hasSideEffect = true;
4303 } else {
4304 declaration = statement.module.trace(subject.name);
4305
4306 if (!declaration || declaration.isExternal || declaration.isUsed) {
4307 hasSideEffect = true;
4308 }
4309 }
4310 }
4311 },
4312 leave: function (node) {
4313 if (node._scope) scope = scope.parent;
4314 }
4315 });
4316
4317 return hasSideEffect;
4318 }
4319
4320 var Declaration = (function () {
4321 function Declaration(node, isParam) {
4322 babelHelpers.classCallCheck(this, Declaration);
4323
4324 if (node) {
4325 if (node.type === 'FunctionDeclaration') {
4326 this.isFunctionDeclaration = true;
4327 this.functionNode = node;
4328 } else if (node.type === 'VariableDeclarator' && node.init && /FunctionExpression/.test(node.init.type)) {
4329 this.isFunctionDeclaration = true;
4330 this.functionNode = node.init;
4331 }
4332 }
4333
4334 this.statement = null;
4335 this.name = null;
4336 this.isParam = isParam;
4337
4338 this.isReassigned = false;
4339 this.aliases = [];
4340 }
4341
4342 Declaration.prototype.addAlias = function addAlias(declaration) {
4343 this.aliases.push(declaration);
4344 };
4345
4346 Declaration.prototype.addReference = function addReference(reference) {
4347 reference.declaration = this;
4348 this.name = reference.name; // TODO handle differences of opinion
4349
4350 if (reference.isReassignment) this.isReassigned = true;
4351 };
4352
4353 Declaration.prototype.render = function render(es6) {
4354 if (es6) return this.name;
4355 if (!this.isReassigned || !this.isExported) return this.name;
4356
4357 return 'exports.' + this.name;
4358 };
4359
4360 Declaration.prototype.run = function run$$(strongDependencies) {
4361 if (this.tested) return this.hasSideEffects;
4362 this.tested = true;
4363
4364 if (!this.statement || !this.functionNode) {
4365 this.hasSideEffects = true; // err on the side of caution. TODO handle unambiguous `var x; x = y => z` cases
4366 } else {
4367 this.hasSideEffects = run(this.functionNode.body, this.functionNode._scope, this.statement, strongDependencies);
4368 }
4369
4370 return this.hasSideEffects;
4371 };
4372
4373 Declaration.prototype.use = function use() {
4374 this.isUsed = true;
4375 if (this.statement) this.statement.mark();
4376
4377 this.aliases.forEach(function (alias) {
4378 return alias.use();
4379 });
4380 };
4381
4382 return Declaration;
4383 })();
4384
4385 var SyntheticDefaultDeclaration = (function () {
4386 function SyntheticDefaultDeclaration(node, statement, name) {
4387 babelHelpers.classCallCheck(this, SyntheticDefaultDeclaration);
4388
4389 this.node = node;
4390 this.statement = statement;
4391 this.name = name;
4392
4393 this.original = null;
4394 this.isExported = false;
4395 this.aliases = [];
4396 }
4397
4398 SyntheticDefaultDeclaration.prototype.addAlias = function addAlias(declaration) {
4399 this.aliases.push(declaration);
4400 };
4401
4402 SyntheticDefaultDeclaration.prototype.addReference = function addReference(reference) {
4403 // Don't change the name to `default`; it's not a valid identifier name.
4404 if (reference.name === 'default') return;
4405
4406 reference.declaration = this;
4407 this.name = reference.name;
4408 };
4409
4410 SyntheticDefaultDeclaration.prototype.bind = function bind(declaration) {
4411 this.original = declaration;
4412 };
4413
4414 SyntheticDefaultDeclaration.prototype.render = function render() {
4415 return !this.original || this.original.isReassigned ? this.name : this.original.render();
4416 };
4417
4418 SyntheticDefaultDeclaration.prototype.run = function run$$(strongDependencies) {
4419 if (this.original) {
4420 return this.original.run(strongDependencies);
4421 }
4422
4423 if (/FunctionExpression/.test(this.node.declaration.type)) {
4424 return run(this.node.declaration.body, this.statement.scope, this.statement, strongDependencies);
4425 }
4426 };
4427
4428 SyntheticDefaultDeclaration.prototype.use = function use() {
4429 this.isUsed = true;
4430 this.statement.mark();
4431
4432 if (this.original) this.original.use();
4433
4434 this.aliases.forEach(function (alias) {
4435 return alias.use();
4436 });
4437 };
4438
4439 return SyntheticDefaultDeclaration;
4440 })();
4441
4442 var SyntheticNamespaceDeclaration = (function () {
4443 function SyntheticNamespaceDeclaration(module) {
4444 var _this = this;
4445
4446 babelHelpers.classCallCheck(this, SyntheticNamespaceDeclaration);
4447
4448 this.module = module;
4449 this.name = null;
4450
4451 this.needsNamespaceBlock = false;
4452 this.aliases = [];
4453
4454 this.originals = blank();
4455 module.getExports().forEach(function (name) {
4456 _this.originals[name] = module.traceExport(name);
4457 });
4458 }
4459
4460 SyntheticNamespaceDeclaration.prototype.addAlias = function addAlias(declaration) {
4461 this.aliases.push(declaration);
4462 };
4463
4464 SyntheticNamespaceDeclaration.prototype.addReference = function addReference(reference) {
4465 // if we have e.g. `foo.bar`, we can optimise
4466 // the reference by pointing directly to `bar`
4467 if (reference.parts.length) {
4468 reference.name = reference.parts.shift();
4469
4470 reference.end += reference.name.length + 1; // TODO this is brittle
4471
4472 var original = this.originals[reference.name];
4473
4474 // throw with an informative error message if the reference doesn't exist.
4475 if (!original) {
4476 this.module.bundle.onwarn('Export \'' + reference.name + '\' is not defined by \'' + this.module.id + '\'');
4477 reference.isUndefined = true;
4478 return;
4479 }
4480
4481 original.addReference(reference);
4482 return;
4483 }
4484
4485 // otherwise we're accessing the namespace directly,
4486 // which means we need to mark all of this module's
4487 // exports and render a namespace block in the bundle
4488 if (!this.needsNamespaceBlock) {
4489 this.needsNamespaceBlock = true;
4490 this.module.bundle.internalNamespaces.push(this);
4491 }
4492
4493 reference.declaration = this;
4494 this.name = reference.name;
4495 };
4496
4497 SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock(indentString) {
4498 var _this2 = this;
4499
4500 var members = keys(this.originals).map(function (name) {
4501 var original = _this2.originals[name];
4502
4503 if (original.isReassigned) {
4504 return indentString + 'get ' + name + ' () { return ' + original.render() + '; }';
4505 }
4506
4507 return '' + indentString + name + ': ' + original.render();
4508 });
4509
4510 return 'var ' + this.render() + ' = Object.freeze({\n' + members.join(',\n') + '\n});\n\n';
4511 };
4512
4513 SyntheticNamespaceDeclaration.prototype.render = function render() {
4514 return this.name;
4515 };
4516
4517 SyntheticNamespaceDeclaration.prototype.use = function use() {
4518 var _this3 = this;
4519
4520 keys(this.originals).forEach(function (name) {
4521 _this3.originals[name].use();
4522 });
4523
4524 this.aliases.forEach(function (alias) {
4525 return alias.use();
4526 });
4527 };
4528
4529 return SyntheticNamespaceDeclaration;
4530 })();
4531
4532 var ExternalDeclaration = (function () {
4533 function ExternalDeclaration(module, name) {
4534 babelHelpers.classCallCheck(this, ExternalDeclaration);
4535
4536 this.module = module;
4537 this.name = name;
4538 this.isExternal = true;
4539 }
4540
4541 ExternalDeclaration.prototype.addAlias = function addAlias() {
4542 // noop
4543 };
4544
4545 ExternalDeclaration.prototype.addReference = function addReference(reference) {
4546 reference.declaration = this;
4547
4548 if (this.name === 'default' || this.name === '*') {
4549 this.module.suggestName(reference.name);
4550 }
4551 };
4552
4553 ExternalDeclaration.prototype.render = function render(es6) {
4554 if (this.name === '*') {
4555 return this.module.name;
4556 }
4557
4558 if (this.name === 'default') {
4559 return !es6 && this.module.exportsNames ? this.module.name + '__default' : this.module.name;
4560 }
4561
4562 return es6 ? this.name : this.module.name + '.' + this.name;
4563 };
4564
4565 ExternalDeclaration.prototype.use = function use() {
4566 // noop?
4567 };
4568
4569 return ExternalDeclaration;
4570 })();
4571
4572 var extractors = {
4573 Identifier: function (names, param) {
4574 names.push(param.name);
4575 },
4576
4577 ObjectPattern: function (names, param) {
4578 param.properties.forEach(function (prop) {
4579 extractors[prop.key.type](names, prop.key);
4580 });
4581 },
4582
4583 ArrayPattern: function (names, param) {
4584 param.elements.forEach(function (element) {
4585 if (element) extractors[element.type](names, element);
4586 });
4587 },
4588
4589 RestElement: function (names, param) {
4590 extractors[param.argument.type](names, param.argument);
4591 },
4592
4593 AssignmentPattern: function (names, param) {
4594 return extractors[param.left.type](names, param.left);
4595 }
4596 };
4597
4598 function extractNames(param) {
4599 var names = [];
4600
4601 extractors[param.type](names, param);
4602 return names;
4603 }
4604
4605 var Scope = (function () {
4606 function Scope(options) {
4607 var _this = this;
4608
4609 babelHelpers.classCallCheck(this, Scope);
4610
4611 options = options || {};
4612
4613 this.parent = options.parent;
4614 this.isBlockScope = !!options.block;
4615 this.isTopLevel = !this.parent || this.parent.isTopLevel && this.isBlockScope;
4616
4617 this.declarations = blank();
4618
4619 if (options.params) {
4620 options.params.forEach(function (param) {
4621 extractNames(param).forEach(function (name) {
4622 _this.declarations[name] = new Declaration(param, true);
4623 });
4624 });
4625 }
4626 }
4627
4628 Scope.prototype.addDeclaration = function addDeclaration(node, isBlockDeclaration, isVar) {
4629 var _this2 = this;
4630
4631 if (!isBlockDeclaration && this.isBlockScope) {
4632 // it's a `var` or function node, and this
4633 // is a block scope, so we need to go up
4634 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
4635 } else {
4636 extractNames(node.id).forEach(function (name) {
4637 _this2.declarations[name] = new Declaration(node);
4638 });
4639 }
4640 };
4641
4642 Scope.prototype.contains = function contains(name) {
4643 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
4644 };
4645
4646 Scope.prototype.eachDeclaration = function eachDeclaration(fn) {
4647 var _this3 = this;
4648
4649 keys(this.declarations).forEach(function (key) {
4650 fn(key, _this3.declarations[key]);
4651 });
4652 };
4653
4654 Scope.prototype.findDeclaration = function findDeclaration(name) {
4655 return this.declarations[name] || this.parent && this.parent.findDeclaration(name);
4656 };
4657
4658 return Scope;
4659 })();
4660
4661 var blockDeclarations = {
4662 'const': true,
4663 'let': true
4664 };
4665 function attachScopes(statement) {
4666 var node = statement.node;
4667 var scope = statement.scope;
4668
4669 walk(node, {
4670 enter: function (node, parent) {
4671 // function foo () {...}
4672 // class Foo {...}
4673 if (/(Function|Class)Declaration/.test(node.type)) {
4674 scope.addDeclaration(node, false, false);
4675 }
4676
4677 // var foo = 1, bar = 2
4678 if (node.type === 'VariableDeclaration') {
4679 (function () {
4680 var isBlockDeclaration = blockDeclarations[node.kind];
4681
4682 node.declarations.forEach(function (declarator) {
4683 scope.addDeclaration(declarator, isBlockDeclaration, true);
4684 });
4685 })();
4686 }
4687
4688 var newScope = undefined;
4689
4690 // create new function scope
4691 if (/Function/.test(node.type)) {
4692 newScope = new Scope({
4693 parent: scope,
4694 block: false,
4695 params: node.params
4696 });
4697
4698 // named function expressions - the name is considered
4699 // part of the function's scope
4700 if (node.type === 'FunctionExpression' && node.id) {
4701 newScope.addDeclaration(node, false, false);
4702 }
4703 }
4704
4705 // create new block scope
4706 if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
4707 newScope = new Scope({
4708 parent: scope,
4709 block: true
4710 });
4711 }
4712
4713 // catch clause has its own block scope
4714 if (node.type === 'CatchClause') {
4715 newScope = new Scope({
4716 parent: scope,
4717 params: [node.param],
4718 block: true
4719 });
4720 }
4721
4722 if (newScope) {
4723 Object.defineProperty(node, '_scope', {
4724 value: newScope,
4725 configurable: true
4726 });
4727
4728 scope = newScope;
4729 }
4730 },
4731 leave: function (node) {
4732 if (node._scope) {
4733 scope = scope.parent;
4734 }
4735 }
4736 });
4737 }
4738
4739 function isFunctionDeclaration(node) {
4740 if (!node) return false;
4741
4742 return node.type === 'FunctionDeclaration' || node.type === 'VariableDeclaration' && node.init && /FunctionExpression/.test(node.init.type);
4743 }
4744
4745 function getLocation$1(source, charIndex) {
4746 var lines = source.split('\n');
4747 var len = lines.length;
4748
4749 var lineStart = 0;
4750 var i = undefined;
4751
4752 for (i = 0; i < len; i += 1) {
4753 var line = lines[i];
4754 var lineEnd = lineStart + line.length + 1; // +1 for newline
4755
4756 if (lineEnd > charIndex) {
4757 return { line: i + 1, column: charIndex - lineStart };
4758 }
4759
4760 lineStart = lineEnd;
4761 }
4762
4763 throw new Error('Could not determine location of character');
4764 }
4765
4766 var Reference = function Reference(node, scope, statement) {
4767 babelHelpers.classCallCheck(this, Reference);
4768
4769 this.node = node;
4770 this.scope = scope;
4771 this.statement = statement;
4772
4773 this.declaration = null; // bound later
4774
4775 this.parts = [];
4776
4777 var root = node;
4778 while (root.type === 'MemberExpression') {
4779 this.parts.unshift(root.property.name);
4780 root = root.object;
4781 }
4782
4783 this.name = root.name;
4784
4785 this.start = node.start;
4786 this.end = node.start + this.name.length; // can be overridden in the case of namespace members
4787 this.rewritten = false;
4788 };
4789
4790 var Statement = (function () {
4791 function Statement(node, module, start, end) {
4792 babelHelpers.classCallCheck(this, Statement);
4793
4794 this.node = node;
4795 this.module = module;
4796 this.start = start;
4797 this.end = end;
4798 this.next = null; // filled in later
4799
4800 this.scope = new Scope();
4801
4802 this.references = [];
4803 this.stringLiteralRanges = [];
4804
4805 this.isIncluded = false;
4806 this.ran = false;
4807
4808 this.isImportDeclaration = node.type === 'ImportDeclaration';
4809 this.isExportDeclaration = /^Export/.test(node.type);
4810 this.isReexportDeclaration = this.isExportDeclaration && !!node.source;
4811
4812 this.isFunctionDeclaration = isFunctionDeclaration(node) || this.isExportDeclaration && isFunctionDeclaration(node.declaration);
4813 }
4814
4815 Statement.prototype.firstPass = function firstPass() {
4816 var _this = this;
4817
4818 if (this.isImportDeclaration) return; // nothing to analyse
4819
4820 // attach scopes
4821 attachScopes(this);
4822
4823 // attach statement to each top-level declaration,
4824 // so we can mark statements easily
4825 this.scope.eachDeclaration(function (name, declaration) {
4826 declaration.statement = _this;
4827 });
4828
4829 // find references
4830 var statement = this;
4831 var module = this.module;
4832 var references = this.references;
4833 var scope = this.scope;
4834 var stringLiteralRanges = this.stringLiteralRanges;
4835
4836 var readDepth = 0;
4837
4838 walk(this.node, {
4839 enter: function (node, parent) {
4840 // warn about eval
4841 if (node.type === 'CallExpression' && node.callee.name === 'eval' && !scope.contains('eval')) {
4842 module.bundle.onwarn('Use of `eval` (in ' + module.id + ') is discouraged, as it may cause issues with minification. See https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval for more details');
4843 }
4844
4845 // skip re-export declarations
4846 if (node.type === 'ExportNamedDeclaration' && node.source) return this.skip();
4847
4848 if (node.type === 'TemplateElement') stringLiteralRanges.push([node.start, node.end]);
4849 if (node.type === 'Literal' && typeof node.value === 'string' && /\n/.test(node.raw)) {
4850 stringLiteralRanges.push([node.start + 1, node.end - 1]);
4851 }
4852
4853 if (node._scope) scope = node._scope;
4854 if (/Function/.test(node.type)) readDepth += 1;
4855
4856 // special case – shorthand properties. because node.key === node.value,
4857 // we can't differentiate once we've descended into the node
4858 if (node.type === 'Property' && node.shorthand) {
4859 var reference = new Reference(node.key, scope);
4860 reference.isShorthandProperty = true; // TODO feels a bit kludgy
4861 references.push(reference);
4862 return this.skip();
4863 }
4864
4865 var isReassignment = undefined;
4866
4867 if (parent && parent.type in modifierNodes) {
4868 var subject = parent[modifierNodes[parent.type]];
4869 var depth = 0;
4870
4871 while (subject.type === 'MemberExpression') {
4872 subject = subject.object;
4873 depth += 1;
4874 }
4875
4876 var importDeclaration = module.imports[subject.name];
4877
4878 if (!scope.contains(subject.name) && importDeclaration) {
4879 var minDepth = importDeclaration.name === '*' ? 2 : // cannot do e.g. `namespace.foo = bar`
4880 1; // cannot do e.g. `foo = bar`, but `foo.bar = bar` is fine
4881
4882 if (depth < minDepth) {
4883 var err = new Error('Illegal reassignment to import \'' + subject.name + '\'');
4884 err.file = module.id;
4885 err.loc = getLocation$1(module.magicString.toString(), subject.start);
4886 throw err;
4887 }
4888 }
4889
4890 isReassignment = !depth;
4891 }
4892
4893 if (isReference(node, parent)) {
4894 // function declaration IDs are a special case – they're associated
4895 // with the parent scope
4896 var referenceScope = parent.type === 'FunctionDeclaration' && node === parent.id ? scope.parent : scope;
4897
4898 var reference = new Reference(node, referenceScope, statement);
4899 reference.isReassignment = isReassignment;
4900
4901 references.push(reference);
4902
4903 this.skip(); // don't descend from `foo.bar.baz` into `foo.bar`
4904 }
4905 },
4906 leave: function (node) {
4907 if (node._scope) scope = scope.parent;
4908 if (/Function/.test(node.type)) readDepth -= 1;
4909 }
4910 });
4911 };
4912
4913 Statement.prototype.mark = function mark() {
4914 if (this.isIncluded) return; // prevent infinite loops
4915 this.isIncluded = true;
4916
4917 this.references.forEach(function (reference) {
4918 if (reference.declaration) reference.declaration.use();
4919 });
4920 };
4921
4922 Statement.prototype.run = function run$$(strongDependencies) {
4923 if (this.ran && this.isIncluded || this.isImportDeclaration || this.isFunctionDeclaration) return;
4924 this.ran = true;
4925
4926 if (run(this.node, this.scope, this, strongDependencies)) {
4927 this.mark();
4928 return true;
4929 }
4930 };
4931
4932 Statement.prototype.source = function source() {
4933 return this.module.source.slice(this.start, this.end);
4934 };
4935
4936 Statement.prototype.toString = function toString() {
4937 return this.module.magicString.slice(this.start, this.end);
4938 };
4939
4940 return Statement;
4941 })();
4942
4943 var 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(' ');
4944 var 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(' ');
4945
4946 var blacklisted = blank();
4947 reservedWords.concat(builtins).forEach(function (word) {
4948 return blacklisted[word] = true;
4949 });
4950 function makeLegalIdentifier(str) {
4951 str = str.replace(/-(\w)/g, function (_, letter) {
4952 return letter.toUpperCase();
4953 }).replace(/[^$_a-zA-Z0-9]/g, '_');
4954
4955 if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str;
4956
4957 return str;
4958 }
4959
4960 function isTruthy(node) {
4961 if (node.type === 'Literal') return !!node.value;
4962 if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
4963 if (node.operator in operators) return operators[node.operator](node);
4964 }
4965
4966 function isFalsy(node) {
4967 return not(isTruthy(node));
4968 }
4969
4970 function not(value) {
4971 return value === undefined ? value : !value;
4972 }
4973
4974 function equals(a, b, strict) {
4975 if (a.type !== b.type) return undefined;
4976 if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
4977 }
4978
4979 var operators = {
4980 '==': function (x) {
4981 return equals(x.left, x.right, false);
4982 },
4983
4984 '!=': function (x) {
4985 return not(operators['=='](x));
4986 },
4987
4988 '===': function (x) {
4989 return equals(x.left, x.right, true);
4990 },
4991
4992 '!==': function (x) {
4993 return not(operators['==='](x));
4994 },
4995
4996 '!': function (x) {
4997 return isFalsy(x.argument);
4998 },
4999
5000 '&&': function (x) {
5001 return isTruthy(x.left) && isTruthy(x.right);
5002 },
5003
5004 '||': function (x) {
5005 return isTruthy(x.left) || isTruthy(x.right);
5006 }
5007 };
5008
5009 function emptyBlockStatement(start, end) {
5010 return {
5011 start: start, end: end,
5012 type: 'BlockStatement',
5013 body: []
5014 };
5015 }
5016
5017 var Module = (function () {
5018 function Module(_ref) {
5019 var id = _ref.id;
5020 var code = _ref.code;
5021 var originalCode = _ref.originalCode;
5022 var ast = _ref.ast;
5023 var sourceMapChain = _ref.sourceMapChain;
5024 var bundle = _ref.bundle;
5025 babelHelpers.classCallCheck(this, Module);
5026
5027 this.code = code;
5028 this.originalCode = originalCode;
5029 this.sourceMapChain = sourceMapChain;
5030
5031 this.bundle = bundle;
5032 this.id = id;
5033
5034 // all dependencies
5035 this.dependencies = [];
5036 this.resolvedIds = blank();
5037
5038 // imports and exports, indexed by local name
5039 this.imports = blank();
5040 this.exports = blank();
5041 this.reexports = blank();
5042
5043 this.exportAllSources = [];
5044 this.exportAllModules = null;
5045
5046 // By default, `id` is the filename. Custom resolvers and loaders
5047 // can change that, but it makes sense to use it for the source filename
5048 this.magicString = new MagicString(code, {
5049 filename: id,
5050 indentExclusionRanges: []
5051 });
5052
5053 // remove existing sourceMappingURL comments
5054 var pattern = new RegExp('\\/\\/#\\s+' + SOURCEMAPPING_URL$1 + '=.+\\n?', 'g');
5055 var match = undefined;
5056 while (match = pattern.exec(code)) {
5057 this.magicString.remove(match.index, match.index + match[0].length);
5058 }
5059
5060 this.comments = [];
5061 this.statements = this.parse(ast);
5062
5063 this.declarations = blank();
5064 this.analyse();
5065
5066 this.strongDependencies = [];
5067 }
5068
5069 Module.prototype.addExport = function addExport(statement) {
5070 var _this = this;
5071
5072 var node = statement.node;
5073 var source = node.source && node.source.value;
5074
5075 // export { name } from './other.js'
5076 if (source) {
5077 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
5078
5079 if (node.type === 'ExportAllDeclaration') {
5080 // Store `export * from '...'` statements in an array of delegates.
5081 // When an unknown import is encountered, we see if one of them can satisfy it.
5082 this.exportAllSources.push(source);
5083 } else {
5084 node.specifiers.forEach(function (specifier) {
5085 _this.reexports[specifier.exported.name] = {
5086 start: specifier.start,
5087 source: source,
5088 localName: specifier.local.name,
5089 module: null // filled in later
5090 };
5091 });
5092 }
5093 }
5094
5095 // export default function foo () {}
5096 // export default foo;
5097 // export default 42;
5098 else if (node.type === 'ExportDefaultDeclaration') {
5099 var identifier = node.declaration.id && node.declaration.id.name || node.declaration.name;
5100
5101 this.exports.default = {
5102 localName: 'default',
5103 identifier: identifier
5104 };
5105
5106 // create a synthetic declaration
5107 this.declarations.default = new SyntheticDefaultDeclaration(node, statement, identifier || this.basename());
5108 }
5109
5110 // export { foo, bar, baz }
5111 // export var foo = 42;
5112 // export var a = 1, b = 2, c = 3;
5113 // export function foo () {}
5114 else if (node.type === 'ExportNamedDeclaration') {
5115 if (node.specifiers.length) {
5116 // export { foo, bar, baz }
5117 node.specifiers.forEach(function (specifier) {
5118 var localName = specifier.local.name;
5119 var exportedName = specifier.exported.name;
5120
5121 _this.exports[exportedName] = { localName: localName };
5122 });
5123 } else {
5124 var declaration = node.declaration;
5125
5126 var _name = undefined;
5127
5128 if (declaration.type === 'VariableDeclaration') {
5129 // export var foo = 42
5130 _name = declaration.declarations[0].id.name;
5131 } else {
5132 // export function foo () {}
5133 _name = declaration.id.name;
5134 }
5135
5136 this.exports[_name] = { localName: _name };
5137 }
5138 }
5139 };
5140
5141 Module.prototype.addImport = function addImport(statement) {
5142 var _this2 = this;
5143
5144 var node = statement.node;
5145 var source = node.source.value;
5146
5147 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
5148
5149 node.specifiers.forEach(function (specifier) {
5150 var localName = specifier.local.name;
5151
5152 if (_this2.imports[localName]) {
5153 var err = new Error('Duplicated import \'' + localName + '\'');
5154 err.file = _this2.id;
5155 err.loc = getLocation$1(_this2.code, specifier.start);
5156 throw err;
5157 }
5158
5159 var isDefault = specifier.type === 'ImportDefaultSpecifier';
5160 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
5161
5162 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
5163 _this2.imports[localName] = { source: source, name: name, module: null };
5164 });
5165 };
5166
5167 Module.prototype.analyse = function analyse() {
5168 var _this3 = this;
5169
5170 // discover this module's imports and exports
5171 this.statements.forEach(function (statement) {
5172 if (statement.isImportDeclaration) _this3.addImport(statement);else if (statement.isExportDeclaration) _this3.addExport(statement);
5173
5174 statement.firstPass();
5175
5176 statement.scope.eachDeclaration(function (name, declaration) {
5177 _this3.declarations[name] = declaration;
5178 });
5179 });
5180 };
5181
5182 Module.prototype.basename = function basename() {
5183 var base = _basename(this.id);
5184 var ext = extname(this.id);
5185
5186 return makeLegalIdentifier(ext ? base.slice(0, -ext.length) : base);
5187 };
5188
5189 Module.prototype.bindAliases = function bindAliases() {
5190 var _this4 = this;
5191
5192 keys(this.declarations).forEach(function (name) {
5193 if (name === '*') return;
5194
5195 var declaration = _this4.declarations[name];
5196 var statement = declaration.statement;
5197
5198 if (statement.node.type !== 'VariableDeclaration') return;
5199
5200 var init = statement.node.declarations[0].init;
5201 if (!init || init.type === 'FunctionExpression') return;
5202
5203 statement.references.forEach(function (reference) {
5204 if (reference.name === name) return;
5205
5206 var otherDeclaration = _this4.trace(reference.name);
5207 if (otherDeclaration) otherDeclaration.addAlias(declaration);
5208 });
5209 });
5210 };
5211
5212 Module.prototype.bindImportSpecifiers = function bindImportSpecifiers() {
5213 var _this5 = this;
5214
5215 [this.imports, this.reexports].forEach(function (specifiers) {
5216 keys(specifiers).forEach(function (name) {
5217 var specifier = specifiers[name];
5218
5219 var id = _this5.resolvedIds[specifier.source];
5220 specifier.module = _this5.bundle.moduleById[id];
5221 });
5222 });
5223
5224 this.exportAllModules = this.exportAllSources.map(function (source) {
5225 var id = _this5.resolvedIds[source];
5226 return _this5.bundle.moduleById[id];
5227 });
5228 };
5229
5230 Module.prototype.bindReferences = function bindReferences() {
5231 var _this6 = this;
5232
5233 if (this.declarations.default) {
5234 if (this.exports.default.identifier) {
5235 var declaration = this.trace(this.exports.default.identifier);
5236 if (declaration) this.declarations.default.bind(declaration);
5237 }
5238 }
5239
5240 this.statements.forEach(function (statement) {
5241 // skip `export { foo, bar, baz }`...
5242 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length) {
5243 // ...unless this is the entry module
5244 if (_this6 !== _this6.bundle.entryModule) return;
5245 }
5246
5247 statement.references.forEach(function (reference) {
5248 var declaration = reference.scope.findDeclaration(reference.name) || _this6.trace(reference.name);
5249
5250 if (declaration) {
5251 declaration.addReference(reference);
5252 } else {
5253 // TODO handle globals
5254 _this6.bundle.assumedGlobals[reference.name] = true;
5255 }
5256 });
5257 });
5258 };
5259
5260 Module.prototype.consolidateDependencies = function consolidateDependencies() {
5261 var _this7 = this;
5262
5263 var strongDependencies = [];
5264 var weakDependencies = [];
5265
5266 // treat all imports as weak dependencies
5267 this.dependencies.forEach(function (source) {
5268 var id = _this7.resolvedIds[source];
5269 var dependency = _this7.bundle.moduleById[id];
5270
5271 if (!dependency.isExternal && ! ~weakDependencies.indexOf(dependency)) {
5272 weakDependencies.push(dependency);
5273 }
5274 });
5275
5276 strongDependencies = this.strongDependencies.filter(function (module) {
5277 return module !== _this7;
5278 });
5279
5280 return { strongDependencies: strongDependencies, weakDependencies: weakDependencies };
5281 };
5282
5283 Module.prototype.getExports = function getExports() {
5284 var exports = blank();
5285
5286 keys(this.exports).forEach(function (name) {
5287 exports[name] = true;
5288 });
5289
5290 keys(this.reexports).forEach(function (name) {
5291 exports[name] = true;
5292 });
5293
5294 this.exportAllModules.forEach(function (module) {
5295 module.getExports().forEach(function (name) {
5296 if (name !== 'default') exports[name] = true;
5297 });
5298 });
5299
5300 return keys(exports);
5301 };
5302
5303 Module.prototype.namespace = function namespace() {
5304 if (!this.declarations['*']) {
5305 this.declarations['*'] = new SyntheticNamespaceDeclaration(this);
5306 }
5307
5308 return this.declarations['*'];
5309 };
5310
5311 Module.prototype.parse = function parse$$(ast) {
5312 var _this8 = this;
5313
5314 // The ast can be supplied programmatically (but usually won't be)
5315 if (!ast) {
5316 // Try to extract a list of top-level statements/declarations. If
5317 // the parse fails, attach file info and abort
5318 try {
5319 ast = parse(this.code, {
5320 ecmaVersion: 6,
5321 sourceType: 'module',
5322 onComment: function (block, text, start, end) {
5323 return _this8.comments.push({ block: block, text: text, start: start, end: end });
5324 },
5325 preserveParens: true
5326 });
5327 } catch (err) {
5328 err.code = 'PARSE_ERROR';
5329 err.file = this.id; // see above - not necessarily true, but true enough
5330 err.message += ' in ' + this.id;
5331 throw err;
5332 }
5333 }
5334
5335 walk(ast, {
5336 enter: function (node) {
5337 // eliminate dead branches early
5338 if (node.type === 'IfStatement') {
5339 if (isFalsy(node.test)) {
5340 _this8.magicString.overwrite(node.consequent.start, node.consequent.end, '{}');
5341 node.consequent = emptyBlockStatement(node.consequent.start, node.consequent.end);
5342 } else if (node.alternate && isTruthy(node.test)) {
5343 _this8.magicString.overwrite(node.alternate.start, node.alternate.end, '{}');
5344 node.alternate = emptyBlockStatement(node.alternate.start, node.alternate.end);
5345 }
5346 }
5347
5348 _this8.magicString.addSourcemapLocation(node.start);
5349 _this8.magicString.addSourcemapLocation(node.end);
5350 }
5351 });
5352
5353 var statements = [];
5354 var lastChar = 0;
5355 var commentIndex = 0;
5356
5357 ast.body.forEach(function (node) {
5358 if (node.type === 'EmptyStatement') return;
5359
5360 if (node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'VariableDeclaration' && node.declaration.declarations && node.declaration.declarations.length > 1) {
5361 // push a synthetic export declaration
5362 var syntheticNode = {
5363 type: 'ExportNamedDeclaration',
5364 specifiers: node.declaration.declarations.map(function (declarator) {
5365 var id = { name: declarator.id.name };
5366 return {
5367 local: id,
5368 exported: id
5369 };
5370 }),
5371 isSynthetic: true
5372 };
5373
5374 var statement = new Statement(syntheticNode, _this8, node.start, node.start);
5375 statements.push(statement);
5376
5377 _this8.magicString.remove(node.start, node.declaration.start);
5378 node = node.declaration;
5379 }
5380
5381 // special case - top-level var declarations with multiple declarators
5382 // should be split up. Otherwise, we may end up including code we
5383 // don't need, just because an unwanted declarator is included
5384 if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
5385 // remove the leading var/let/const... UNLESS the previous node
5386 // was also a synthetic node, in which case it'll get removed anyway
5387 var lastStatement = statements[statements.length - 1];
5388 if (!lastStatement || !lastStatement.node.isSynthetic) {
5389 _this8.magicString.remove(node.start, node.declarations[0].start);
5390 }
5391
5392 node.declarations.forEach(function (declarator) {
5393 var start = declarator.start;
5394 var end = declarator.end;
5395
5396 var syntheticNode = {
5397 type: 'VariableDeclaration',
5398 kind: node.kind,
5399 start: start,
5400 end: end,
5401 declarations: [declarator],
5402 isSynthetic: true
5403 };
5404
5405 var statement = new Statement(syntheticNode, _this8, start, end);
5406 statements.push(statement);
5407 });
5408
5409 lastChar = node.end; // TODO account for trailing line comment
5410 } else {
5411 var comment = undefined;
5412 do {
5413 comment = _this8.comments[commentIndex];
5414 if (!comment) break;
5415 if (comment.start > node.start) break;
5416 commentIndex += 1;
5417 } while (comment.end < lastChar);
5418
5419 var start = comment ? Math.min(comment.start, node.start) : node.start;
5420 var end = node.end; // TODO account for trailing line comment
5421
5422 var statement = new Statement(node, _this8, start, end);
5423 statements.push(statement);
5424
5425 lastChar = end;
5426 }
5427 });
5428
5429 var i = statements.length;
5430 var next = this.code.length;
5431 while (i--) {
5432 statements[i].next = next;
5433 if (!statements[i].isSynthetic) next = statements[i].start;
5434 }
5435
5436 return statements;
5437 };
5438
5439 Module.prototype.render = function render(es6) {
5440 var _this9 = this;
5441
5442 var magicString = this.magicString.clone();
5443
5444 this.statements.forEach(function (statement) {
5445 if (!statement.isIncluded) {
5446 magicString.remove(statement.start, statement.next);
5447 return;
5448 }
5449
5450 statement.stringLiteralRanges.forEach(function (range) {
5451 return magicString.indentExclusionRanges.push(range);
5452 });
5453
5454 // skip `export { foo, bar, baz }`
5455 if (statement.node.type === 'ExportNamedDeclaration') {
5456 if (statement.node.isSynthetic) return;
5457
5458 // skip `export { foo, bar, baz }`
5459 if (statement.node.specifiers.length) {
5460 magicString.remove(statement.start, statement.next);
5461 return;
5462 }
5463 }
5464
5465 // split up/remove var declarations as necessary
5466 if (statement.node.isSynthetic) {
5467 // insert `var/let/const` if necessary
5468 var declaration = _this9.declarations[statement.node.declarations[0].id.name];
5469 if (!(declaration.isExported && declaration.isReassigned)) {
5470 // TODO encapsulate this
5471 magicString.insert(statement.start, statement.node.kind + ' ');
5472 }
5473
5474 magicString.overwrite(statement.end, statement.next, ';\n'); // TODO account for trailing newlines
5475 }
5476
5477 var toDeshadow = blank();
5478
5479 statement.references.forEach(function (reference) {
5480 var start = reference.start;
5481 var end = reference.end;
5482
5483 if (reference.isUndefined) {
5484 magicString.overwrite(start, end, 'undefined', true);
5485 }
5486
5487 var declaration = reference.declaration;
5488
5489 if (declaration) {
5490 var _name2 = declaration.render(es6);
5491
5492 // the second part of this check is necessary because of
5493 // namespace optimisation – name of `foo.bar` could be `bar`
5494 if (reference.name === _name2 && _name2.length === end - start) return;
5495
5496 reference.rewritten = true;
5497
5498 // prevent local variables from shadowing renamed references
5499 var identifier = _name2.match(/[^\.]+/)[0];
5500 if (reference.scope.contains(identifier)) {
5501 toDeshadow[identifier] = identifier + '$$'; // TODO more robust mechanism
5502 }
5503
5504 if (reference.isShorthandProperty) {
5505 magicString.insert(end, ': ' + _name2);
5506 } else {
5507 magicString.overwrite(start, end, _name2, true);
5508 }
5509 }
5510 });
5511
5512 if (keys(toDeshadow).length) {
5513 statement.references.forEach(function (reference) {
5514 if (!reference.rewritten && reference.name in toDeshadow) {
5515 magicString.overwrite(reference.start, reference.end, toDeshadow[reference.name], true);
5516 }
5517 });
5518 }
5519
5520 // modify exports as necessary
5521 if (statement.isExportDeclaration) {
5522 // remove `export` from `export var foo = 42`
5523 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration') {
5524 var _name3 = statement.node.declaration.declarations[0].id.name;
5525 var declaration = _this9.declarations[_name3];
5526
5527 var end = declaration.isExported && declaration.isReassigned ? statement.node.declaration.declarations[0].start : statement.node.declaration.start;
5528
5529 magicString.remove(statement.node.start, end);
5530 } else if (statement.node.type === 'ExportAllDeclaration') {
5531 // TODO: remove once `export * from 'external'` is supported.
5532 magicString.remove(statement.start, statement.next);
5533 }
5534
5535 // remove `export` from `export class Foo {...}` or `export default Foo`
5536 // TODO default exports need different treatment
5537 else if (statement.node.declaration.id) {
5538 magicString.remove(statement.node.start, statement.node.declaration.start);
5539 } else if (statement.node.type === 'ExportDefaultDeclaration') {
5540 var defaultDeclaration = _this9.declarations.default;
5541
5542 // prevent `var foo = foo`
5543 if (defaultDeclaration.original && !defaultDeclaration.original.isReassigned) {
5544 magicString.remove(statement.start, statement.next);
5545 return;
5546 }
5547
5548 var defaultName = defaultDeclaration.render();
5549
5550 // prevent `var undefined = sideEffectyDefault(foo)`
5551 if (!defaultDeclaration.isExported && !defaultDeclaration.isUsed) {
5552 magicString.remove(statement.start, statement.node.declaration.start);
5553 return;
5554 }
5555
5556 // anonymous functions should be converted into declarations
5557 if (statement.node.declaration.type === 'FunctionExpression') {
5558 magicString.overwrite(statement.node.start, statement.node.declaration.start + 8, 'function ' + defaultName);
5559 } else {
5560 magicString.overwrite(statement.node.start, statement.node.declaration.start, 'var ' + defaultName + ' = ');
5561 }
5562 } else {
5563 throw new Error('Unhandled export');
5564 }
5565 }
5566 });
5567
5568 // add namespace block if necessary
5569 var namespace = this.declarations['*'];
5570 if (namespace && namespace.needsNamespaceBlock) {
5571 magicString.append('\n\n' + namespace.renderBlock(magicString.getIndentString()));
5572 }
5573
5574 return magicString.trim();
5575 };
5576
5577 Module.prototype.run = function run() {
5578 var _this10 = this;
5579
5580 var marked = false;
5581
5582 this.statements.forEach(function (statement) {
5583 marked = marked || statement.run(_this10.strongDependencies);
5584 });
5585
5586 return marked;
5587 };
5588
5589 Module.prototype.trace = function trace(name) {
5590 if (name in this.declarations) return this.declarations[name];
5591 if (name in this.imports) {
5592 var importDeclaration = this.imports[name];
5593 var otherModule = importDeclaration.module;
5594
5595 if (importDeclaration.name === '*' && !otherModule.isExternal) {
5596 return otherModule.namespace();
5597 }
5598
5599 var declaration = otherModule.traceExport(importDeclaration.name);
5600
5601 if (!declaration) throw new Error('Module ' + otherModule.id + ' does not export ' + importDeclaration.name + ' (imported by ' + this.id + ')');
5602 return declaration;
5603 }
5604
5605 return null;
5606 };
5607
5608 Module.prototype.traceExport = function traceExport(name) {
5609 // export { foo } from './other.js'
5610 var reexportDeclaration = this.reexports[name];
5611 if (reexportDeclaration) {
5612 var declaration = reexportDeclaration.module.traceExport(reexportDeclaration.localName);
5613
5614 if (!declaration) {
5615 var err = new Error('\'' + reexportDeclaration.localName + '\' is not exported by \'' + reexportDeclaration.module.id + '\' (imported by \'' + this.id + '\')');
5616 err.file = this.id;
5617 err.loc = getLocation$1(this.code, reexportDeclaration.start);
5618 throw err;
5619 }
5620
5621 return declaration;
5622 }
5623
5624 var exportDeclaration = this.exports[name];
5625 if (exportDeclaration) {
5626 return this.trace(exportDeclaration.localName);
5627 }
5628
5629 for (var i = 0; i < this.exportAllModules.length; i += 1) {
5630 var _module = this.exportAllModules[i];
5631 var declaration = _module.traceExport(name);
5632
5633 if (declaration) return declaration;
5634 }
5635 };
5636
5637 return Module;
5638 })();
5639
5640 var ExternalModule = (function () {
5641 function ExternalModule(id) {
5642 babelHelpers.classCallCheck(this, ExternalModule);
5643
5644 this.id = id;
5645 this.name = makeLegalIdentifier(id);
5646
5647 this.nameSuggestions = blank();
5648 this.mostCommonSuggestion = 0;
5649
5650 this.isExternal = true;
5651 this.declarations = blank();
5652
5653 this.exportsNames = false;
5654 }
5655
5656 ExternalModule.prototype.suggestName = function suggestName(name) {
5657 if (!this.nameSuggestions[name]) this.nameSuggestions[name] = 0;
5658 this.nameSuggestions[name] += 1;
5659
5660 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
5661 this.mostCommonSuggestion = this.nameSuggestions[name];
5662 this.name = name;
5663 }
5664 };
5665
5666 ExternalModule.prototype.traceExport = function traceExport(name) {
5667 if (name !== 'default' && name !== '*') {
5668 this.exportsNames = true;
5669 }
5670
5671 return this.declarations[name] || (this.declarations[name] = new ExternalDeclaration(this, name));
5672 };
5673
5674 return ExternalModule;
5675 })();
5676
5677 function getName(x) {
5678 return x.name;
5679 }
5680
5681 function quoteId(x) {
5682 return "'" + x.id + "'";
5683 }
5684
5685 function req(x) {
5686 return "require('" + x.id + "')";
5687 }
5688
5689 function getInteropBlock(bundle) {
5690 return bundle.externalModules.map(function (module) {
5691 return module.declarations.default ? module.exportsNames ? 'var ' + module.name + '__default = \'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';' : module.name + ' = \'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';' : null;
5692 }).filter(Boolean).join('\n');
5693 }
5694
5695 function getExportBlock(entryModule, exportMode) {
5696 var mechanism = arguments.length <= 2 || arguments[2] === undefined ? 'return' : arguments[2];
5697
5698 if (exportMode === 'default') {
5699 return mechanism + ' ' + entryModule.declarations.default.render(false) + ';';
5700 }
5701
5702 return entryModule.getExports().map(function (name) {
5703 var prop = name === 'default' ? '[\'default\']' : '.' + name;
5704 var declaration = entryModule.traceExport(name);
5705
5706 var lhs = 'exports' + prop;
5707 var rhs = declaration.render(false);
5708
5709 // prevent `exports.count = exports.count`
5710 if (lhs === rhs) return null;
5711
5712 return lhs + ' = ' + rhs + ';';
5713 }).filter(Boolean).join('\n');
5714 }
5715
5716 function umd(bundle, magicString, _ref, options) {
5717 var exportMode = _ref.exportMode;
5718 var indentString = _ref.indentString;
5719
5720 if (exportMode !== 'none' && !options.moduleName) {
5721 throw new Error('You must supply options.moduleName for UMD bundles');
5722 }
5723
5724 var globalNames = options.globals || blank();
5725
5726 var amdDeps = bundle.externalModules.map(quoteId);
5727 var cjsDeps = bundle.externalModules.map(req);
5728 var globalDeps = bundle.externalModules.map(function (module) {
5729 return 'global.' + (globalNames[module.id] || module.name);
5730 });
5731
5732 var args = bundle.externalModules.map(getName);
5733
5734 if (exportMode === 'named') {
5735 amdDeps.unshift('\'exports\'');
5736 cjsDeps.unshift('exports');
5737 globalDeps.unshift('(global.' + options.moduleName + ' = {})');
5738
5739 args.unshift('exports');
5740 }
5741
5742 var amdParams = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (amdDeps.length ? '[' + amdDeps.join(', ') + '], ' : '');
5743
5744 var cjsExport = exportMode === 'default' ? 'module.exports = ' : '';
5745 var defaultExport = exportMode === 'default' ? 'global.' + options.moduleName + ' = ' : '';
5746
5747 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5748
5749 var intro = ('(function (global, factory) {\n\t\t\ttypeof exports === \'object\' && typeof module !== \'undefined\' ? ' + cjsExport + 'factory(' + cjsDeps.join(', ') + ') :\n\t\t\ttypeof define === \'function\' && define.amd ? define(' + amdParams + 'factory) :\n\t\t\t' + defaultExport + 'factory(' + globalDeps + ');\n\t\t}(this, function (' + args + ') {' + useStrict + '\n\n\t\t').replace(/^\t\t/gm, '').replace(/^\t/gm, magicString.getIndentString());
5750
5751 // var foo__default = 'default' in foo ? foo['default'] : foo;
5752 var interopBlock = getInteropBlock(bundle);
5753 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5754
5755 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5756 if (exportBlock) magicString.append('\n\n' + exportBlock);
5757
5758 return magicString.trim().indent(indentString).append('\n\n}));').prepend(intro);
5759 }
5760
5761 function iife(bundle, magicString, _ref, options) {
5762 var exportMode = _ref.exportMode;
5763 var indentString = _ref.indentString;
5764
5765 var globalNames = options.globals || blank();
5766
5767 var dependencies = bundle.externalModules.map(function (module) {
5768 return globalNames[module.id] || module.name;
5769 });
5770
5771 var args = bundle.externalModules.map(getName);
5772
5773 if (exportMode !== 'none' && !options.moduleName) {
5774 throw new Error('You must supply options.moduleName for IIFE bundles');
5775 }
5776
5777 if (exportMode === 'named') {
5778 dependencies.unshift('(this.' + options.moduleName + ' = {})');
5779 args.unshift('exports');
5780 }
5781
5782 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5783 var intro = '(function (' + args + ') {' + useStrict + '\n\n';
5784 var outro = '\n\n})(' + dependencies + ');';
5785
5786 if (exportMode === 'default') {
5787 intro = 'var ' + options.moduleName + ' = ' + intro;
5788 }
5789
5790 // var foo__default = 'default' in foo ? foo['default'] : foo;
5791 var interopBlock = getInteropBlock(bundle);
5792 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5793
5794 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5795 if (exportBlock) magicString.append('\n\n' + exportBlock);
5796
5797 return magicString.indent(indentString).prepend(intro).append(outro);
5798 }
5799
5800 function notDefault(name) {
5801 return name !== 'default';
5802 }
5803 function es6(bundle, magicString) {
5804 var importBlock = bundle.externalModules.map(function (module) {
5805 var specifiers = [];
5806 var importedNames = keys(module.declarations).filter(function (name) {
5807 return name !== '*' && name !== 'default';
5808 });
5809
5810 if (module.declarations.default) {
5811 specifiers.push(module.name);
5812 }
5813
5814 if (module.declarations['*']) {
5815 specifiers.push('* as ' + module.name);
5816 }
5817
5818 if (importedNames.length) {
5819 specifiers.push('{ ' + importedNames.join(', ') + ' }');
5820 }
5821
5822 return specifiers.length ? 'import ' + specifiers.join(', ') + ' from \'' + module.id + '\';' : 'import \'' + module.id + '\';';
5823 }).join('\n');
5824
5825 if (importBlock) {
5826 magicString.prepend(importBlock + '\n\n');
5827 }
5828
5829 var module = bundle.entryModule;
5830
5831 var specifiers = module.getExports().filter(notDefault).map(function (name) {
5832 var declaration = module.traceExport(name);
5833
5834 return declaration.name === name ? name : declaration.name + ' as ' + name;
5835 });
5836
5837 var exportBlock = specifiers.length ? 'export { ' + specifiers.join(', ') + ' };' : '';
5838
5839 var defaultExport = module.exports.default || module.reexports.default;
5840 if (defaultExport) {
5841 exportBlock += 'export default ' + module.traceExport('default').name + ';';
5842 }
5843
5844 if (exportBlock) {
5845 magicString.append('\n\n' + exportBlock.trim());
5846 }
5847
5848 return magicString.trim();
5849 }
5850
5851 function cjs(bundle, magicString, _ref, options) {
5852 var exportMode = _ref.exportMode;
5853
5854 var intro = options.useStrict === false ? '' : '\'use strict\';\n\n';
5855
5856 // TODO handle empty imports, once they're supported
5857 var importBlock = bundle.externalModules.map(function (module) {
5858 var requireStatement = 'var ' + module.name + ' = require(\'' + module.id + '\');';
5859
5860 if (module.declarations.default) {
5861 requireStatement += '\n' + (module.exportsNames ? 'var ' + module.name + '__default = ' : module.name + ' = ') + ('\'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';');
5862 }
5863
5864 return requireStatement;
5865 }).join('\n');
5866
5867 if (importBlock) {
5868 intro += importBlock + '\n\n';
5869 }
5870
5871 magicString.prepend(intro);
5872
5873 var exportBlock = getExportBlock(bundle.entryModule, exportMode, 'module.exports =');
5874 if (exportBlock) magicString.append('\n\n' + exportBlock);
5875
5876 return magicString;
5877 }
5878
5879 function amd(bundle, magicString, _ref, options) {
5880 var exportMode = _ref.exportMode;
5881 var indentString = _ref.indentString;
5882
5883 var deps = bundle.externalModules.map(quoteId);
5884 var args = bundle.externalModules.map(getName);
5885
5886 if (exportMode === 'named') {
5887 args.unshift('exports');
5888 deps.unshift('\'exports\'');
5889 }
5890
5891 var params = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (deps.length ? '[' + deps.join(', ') + '], ' : '');
5892
5893 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5894 var intro = 'define(' + params + 'function (' + args.join(', ') + ') {' + useStrict + '\n\n';
5895
5896 // var foo__default = 'default' in foo ? foo['default'] : foo;
5897 var interopBlock = getInteropBlock(bundle);
5898 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5899
5900 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5901 if (exportBlock) magicString.append('\n\n' + exportBlock);
5902
5903 return magicString.indent(indentString).append('\n\n});').prepend(intro);
5904 }
5905
5906 var finalisers = { amd: amd, cjs: cjs, es6: es6, iife: iife, umd: umd };
5907
5908 function ensureArray(thing) {
5909 if (Array.isArray(thing)) return thing;
5910 if (thing == undefined) return [];
5911 return [thing];
5912 }
5913
5914 function load(id) {
5915 return readFileSync(id, 'utf-8');
5916 }
5917
5918 function addJsExtensionIfNecessary(file) {
5919 if (isFile(file)) return file;
5920
5921 file += '.js';
5922 if (isFile(file)) return file;
5923
5924 return null;
5925 }
5926
5927 function resolveId(importee, importer) {
5928 // absolute paths are left untouched
5929 if (isAbsolute(importee)) return addJsExtensionIfNecessary(importee);
5930
5931 // if this is the entry point, resolve against cwd
5932 if (importer === undefined) return addJsExtensionIfNecessary(resolve(process.cwd(), importee));
5933
5934 // external modules are skipped at this stage
5935 if (importee[0] !== '.') return null;
5936
5937 return addJsExtensionIfNecessary(resolve(dirname(importer), importee));
5938 }
5939
5940 function onwarn(msg) {
5941 console.error(msg); //eslint-disable-line no-console
5942 }
5943
5944 function badExports(option, keys) {
5945 throw new Error('\'' + option + '\' was specified for options.exports, but entry module has following exports: ' + keys.join(', '));
5946 }
5947 function getExportMode(bundle, exportMode) {
5948 var exportKeys = keys(bundle.entryModule.exports).concat(keys(bundle.entryModule.reexports)).concat(bundle.entryModule.exportAllSources); // not keys, but makes our job easier this way
5949
5950 if (exportMode === 'default') {
5951 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
5952 badExports('default', exportKeys);
5953 }
5954 } else if (exportMode === 'none' && exportKeys.length) {
5955 badExports('none', exportKeys);
5956 }
5957
5958 if (!exportMode || exportMode === 'auto') {
5959 if (exportKeys.length === 0) {
5960 exportMode = 'none';
5961 } else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
5962 exportMode = 'default';
5963 } else {
5964 exportMode = 'named';
5965 }
5966 }
5967
5968 if (!/(?:default|named|none)/.test(exportMode)) {
5969 throw new Error('options.exports must be \'default\', \'named\', \'none\', \'auto\', or left unspecified (defaults to \'auto\')');
5970 }
5971
5972 return exportMode;
5973 }
5974
5975 function getIndentString(magicString, options) {
5976 if (!('indent' in options) || options.indent === true) {
5977 return magicString.getIndentString();
5978 }
5979
5980 return options.indent || '';
5981 }
5982
5983 function unixizePath(path) {
5984 return path.split(/[\/\\]/).join('/');
5985 }
5986
5987 function transform(source, id, transformers) {
5988 var sourceMapChain = [];
5989
5990 if (typeof source === 'string') {
5991 source = {
5992 code: source,
5993 ast: null
5994 };
5995 }
5996
5997 var originalCode = source.code;
5998 var ast = source.ast;
5999
6000 return transformers.reduce(function (promise, transformer) {
6001 return promise.then(function (previous) {
6002 return Promise.resolve(transformer(previous, id)).then(function (result) {
6003 if (result == null) return previous;
6004
6005 if (typeof result === 'string') {
6006 result = {
6007 code: result,
6008 ast: null,
6009 map: null
6010 };
6011 }
6012
6013 sourceMapChain.push(result.map);
6014 ast = result.ast;
6015
6016 return result.code;
6017 });
6018 });
6019 }, Promise.resolve(source.code)).then(function (code) {
6020 return { code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain };
6021 });
6022 }
6023
6024 var charToInteger$1 = {};
6025 var integerToChar$1 = {};
6026
6027 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach(function (char, i) {
6028 charToInteger$1[char] = i;
6029 integerToChar$1[i] = char;
6030 });
6031
6032 function decode$1(string) {
6033 var result = [],
6034 len = string.length,
6035 i,
6036 hasContinuationBit,
6037 shift = 0,
6038 value = 0,
6039 integer,
6040 shouldNegate;
6041
6042 for (i = 0; i < len; i += 1) {
6043 integer = charToInteger$1[string[i]];
6044
6045 if (integer === undefined) {
6046 throw new Error('Invalid character (' + string[i] + ')');
6047 }
6048
6049 hasContinuationBit = integer & 32;
6050
6051 integer &= 31;
6052 value += integer << shift;
6053
6054 if (hasContinuationBit) {
6055 shift += 5;
6056 } else {
6057 shouldNegate = value & 1;
6058 value >>= 1;
6059
6060 result.push(shouldNegate ? -value : value);
6061
6062 // reset
6063 value = shift = 0;
6064 }
6065 }
6066
6067 return result;
6068 }
6069
6070 function encode$1(value) {
6071 var result, i;
6072
6073 if (typeof value === 'number') {
6074 result = encodeInteger$1(value);
6075 } else {
6076 result = '';
6077 for (i = 0; i < value.length; i += 1) {
6078 result += encodeInteger$1(value[i]);
6079 }
6080 }
6081
6082 return result;
6083 }
6084
6085 function encodeInteger$1(num) {
6086 var result = '',
6087 clamped;
6088
6089 if (num < 0) {
6090 num = -num << 1 | 1;
6091 } else {
6092 num <<= 1;
6093 }
6094
6095 do {
6096 clamped = num & 31;
6097 num >>= 5;
6098
6099 if (num > 0) {
6100 clamped |= 32;
6101 }
6102
6103 result += integerToChar$1[clamped];
6104 } while (num > 0);
6105
6106 return result;
6107 }
6108
6109 function decodeSegments(encodedSegments) {
6110 var i = encodedSegments.length;
6111 var segments = new Array(i);
6112
6113 while (i--) segments[i] = decode$1(encodedSegments[i]);
6114 return segments;
6115 }
6116
6117 function decode$1$1(mappings) {
6118 var sourceFileIndex = 0; // second field
6119 var sourceCodeLine = 0; // third field
6120 var sourceCodeColumn = 0; // fourth field
6121 var nameIndex = 0; // fifth field
6122
6123 var lines = mappings.split(';');
6124 var numLines = lines.length;
6125 var decoded = new Array(numLines);
6126
6127 var i = undefined;
6128 var j = undefined;
6129 var line = undefined;
6130 var generatedCodeColumn = undefined;
6131 var decodedLine = undefined;
6132 var segments = undefined;
6133 var segment = undefined;
6134 var result = undefined;
6135
6136 for (i = 0; i < numLines; i += 1) {
6137 line = lines[i];
6138
6139 generatedCodeColumn = 0; // first field - reset each time
6140 decodedLine = [];
6141
6142 segments = decodeSegments(line.split(','));
6143
6144 for (j = 0; j < segments.length; j += 1) {
6145 segment = segments[j];
6146
6147 if (!segment.length) {
6148 break;
6149 }
6150
6151 generatedCodeColumn += segment[0];
6152
6153 result = [generatedCodeColumn];
6154 decodedLine.push(result);
6155
6156 if (segment.length === 1) {
6157 // only one field!
6158 continue;
6159 }
6160
6161 sourceFileIndex += segment[1];
6162 sourceCodeLine += segment[2];
6163 sourceCodeColumn += segment[3];
6164
6165 result.push(sourceFileIndex, sourceCodeLine, sourceCodeColumn);
6166
6167 if (segment.length === 5) {
6168 nameIndex += segment[4];
6169 result.push(nameIndex);
6170 }
6171 }
6172
6173 decoded[i] = decodedLine;
6174 }
6175
6176 return decoded;
6177 }
6178
6179 function encode$1$1(decoded) {
6180 var offsets = {
6181 generatedCodeColumn: 0,
6182 sourceFileIndex: 0, // second field
6183 sourceCodeLine: 0, // third field
6184 sourceCodeColumn: 0, // fourth field
6185 nameIndex: 0 // fifth field
6186 };
6187
6188 return decoded.map(function (line) {
6189 offsets.generatedCodeColumn = 0; // first field - reset each time
6190 return line.map(encodeSegment).join(',');
6191 }).join(';');
6192
6193 function encodeSegment(segment) {
6194 if (!segment.length) {
6195 return segment;
6196 }
6197
6198 var result = new Array(segment.length);
6199
6200 result[0] = segment[0] - offsets.generatedCodeColumn;
6201 offsets.generatedCodeColumn = segment[0];
6202
6203 if (segment.length === 1) {
6204 // only one field!
6205 return encode$1(result);
6206 }
6207
6208 result[1] = segment[1] - offsets.sourceFileIndex;
6209 result[2] = segment[2] - offsets.sourceCodeLine;
6210 result[3] = segment[3] - offsets.sourceCodeColumn;
6211
6212 offsets.sourceFileIndex = segment[1];
6213 offsets.sourceCodeLine = segment[2];
6214 offsets.sourceCodeColumn = segment[3];
6215
6216 if (segment.length === 5) {
6217 result[4] = segment[4] - offsets.nameIndex;
6218 offsets.nameIndex = segment[4];
6219 }
6220
6221 return encode$1(result);
6222 }
6223 }
6224
6225 function traceSegment(loc, mappings) {
6226 var line = loc[0];
6227 var column = loc[1];
6228
6229 var segments = mappings[line];
6230
6231 if (!segments) return null;
6232
6233 for (var i = 0; i < segments.length; i += 1) {
6234 var segment = segments[i];
6235
6236 if (segment[0] > column) return null;
6237
6238 if (segment[0] === column) {
6239 if (segment[1] !== 0) {
6240 throw new Error('Bad sourcemap');
6241 }
6242
6243 return [segment[2], segment[3]];
6244 }
6245 }
6246
6247 return null;
6248 }
6249 function collapseSourcemaps(map, modules) {
6250 var chains = modules.map(function (module) {
6251 return module.sourceMapChain.map(function (map) {
6252 if (!map) throw new Error('Cannot generate a sourcemap if non-sourcemap-generating transformers are used');
6253 return decode$1$1(map.mappings);
6254 });
6255 });
6256
6257 var decodedMappings = decode$1$1(map.mappings);
6258
6259 var tracedMappings = decodedMappings.map(function (line) {
6260 var tracedLine = [];
6261
6262 line.forEach(function (segment) {
6263 var sourceIndex = segment[1];
6264 var sourceCodeLine = segment[2];
6265 var sourceCodeColumn = segment[3];
6266
6267 var chain = chains[sourceIndex];
6268
6269 var i = chain.length;
6270 var traced = [sourceCodeLine, sourceCodeColumn];
6271
6272 while (i-- && traced) {
6273 traced = traceSegment(traced, chain[i]);
6274 }
6275
6276 if (traced) {
6277 tracedLine.push([segment[0], segment[1], traced[0], traced[1]
6278 // TODO name?
6279 ]);
6280 }
6281 });
6282
6283 return tracedLine;
6284 });
6285
6286 map.sourcesContent = modules.map(function (module) {
6287 return module.originalCode;
6288 });
6289 map.mappings = encode$1$1(tracedMappings);
6290 return map;
6291 }
6292
6293 function callIfFunction(thing) {
6294 return typeof thing === 'function' ? thing() : thing;
6295 }
6296
6297 var Bundle = (function () {
6298 function Bundle(options) {
6299 var _this = this;
6300
6301 babelHelpers.classCallCheck(this, Bundle);
6302
6303 this.entry = options.entry;
6304 this.entryModule = null;
6305
6306 this.plugins = ensureArray(options.plugins);
6307
6308 this.resolveId = first$1(this.plugins.map(function (plugin) {
6309 return plugin.resolveId;
6310 }).filter(Boolean).concat(resolveId));
6311
6312 this.load = first$1(this.plugins.map(function (plugin) {
6313 return plugin.load;
6314 }).filter(Boolean).concat(load));
6315
6316 this.transformers = this.plugins.map(function (plugin) {
6317 return plugin.transform;
6318 }).filter(Boolean);
6319
6320 this.moduleById = blank();
6321 this.modules = [];
6322
6323 this.externalModules = [];
6324 this.internalNamespaces = [];
6325
6326 this.assumedGlobals = blank();
6327
6328 this.external = options.external || [];
6329 this.onwarn = options.onwarn || onwarn;
6330 this.aggressive = options.aggressive;
6331
6332 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
6333 ['module', 'exports'].forEach(function (global) {
6334 return _this.assumedGlobals[global] = true;
6335 });
6336 }
6337
6338 Bundle.prototype.build = function build() {
6339 var _this2 = this;
6340
6341 // Phase 1 – discovery. We load the entry module and find which
6342 // modules it imports, and import those, until we have all
6343 // of the entry module's dependencies
6344 return Promise.resolve(this.resolveId(this.entry, undefined)).then(function (id) {
6345 return _this2.fetchModule(id, undefined);
6346 }).then(function (entryModule) {
6347 _this2.entryModule = entryModule;
6348
6349 // Phase 2 – binding. We link references to their declarations
6350 // to generate a complete picture of the bundle
6351 _this2.modules.forEach(function (module) {
6352 return module.bindImportSpecifiers();
6353 });
6354 _this2.modules.forEach(function (module) {
6355 return module.bindAliases();
6356 });
6357 _this2.modules.forEach(function (module) {
6358 return module.bindReferences();
6359 });
6360
6361 // Phase 3 – marking. We 'run' each statement to see which ones
6362 // need to be included in the generated bundle
6363
6364 // mark all export statements
6365 entryModule.getExports().forEach(function (name) {
6366 var declaration = entryModule.traceExport(name);
6367 declaration.isExported = true;
6368
6369 declaration.use();
6370 });
6371
6372 // mark statements that should appear in the bundle
6373 var settled = false;
6374 while (!settled) {
6375 settled = true;
6376
6377 if (_this2.aggressive) {
6378 settled = !entryModule.run();
6379 } else {
6380 _this2.modules.forEach(function (module) {
6381 if (module.run()) settled = false;
6382 });
6383 }
6384 }
6385
6386 // Phase 4 – final preparation. We order the modules with an
6387 // enhanced topological sort that accounts for cycles, then
6388 // ensure that names are deconflicted throughout the bundle
6389 _this2.orderedModules = _this2.sort();
6390 _this2.deconflict();
6391 });
6392 };
6393
6394 Bundle.prototype.deconflict = function deconflict() {
6395 var used = blank();
6396
6397 // ensure no conflicts with globals
6398 keys(this.assumedGlobals).forEach(function (name) {
6399 return used[name] = 1;
6400 });
6401
6402 function getSafeName(name) {
6403 while (used[name]) {
6404 name += '$' + used[name]++;
6405 }
6406
6407 used[name] = 1;
6408 return name;
6409 }
6410
6411 this.externalModules.forEach(function (module) {
6412 module.name = getSafeName(module.name);
6413 });
6414
6415 this.modules.forEach(function (module) {
6416 keys(module.declarations).forEach(function (originalName) {
6417 var declaration = module.declarations[originalName];
6418
6419 if (originalName === 'default') {
6420 if (declaration.original && !declaration.original.isReassigned) return;
6421 }
6422
6423 declaration.name = getSafeName(declaration.name);
6424 });
6425 });
6426 };
6427
6428 Bundle.prototype.fetchModule = function fetchModule(id, importer) {
6429 var _this3 = this;
6430
6431 // short-circuit cycles
6432 if (id in this.moduleById) return null;
6433 this.moduleById[id] = null;
6434
6435 return Promise.resolve(this.load(id)).catch(function (err) {
6436 var msg = 'Could not load ' + id;
6437 if (importer) msg += ' (imported by ' + importer + ')';
6438
6439 msg += ': ' + err.message;
6440 throw new Error(msg);
6441 }).then(function (source) {
6442 return transform(source, id, _this3.transformers);
6443 }).then(function (source) {
6444 var code = source.code;
6445 var originalCode = source.originalCode;
6446 var ast = source.ast;
6447 var sourceMapChain = source.sourceMapChain;
6448
6449 var module = new Module({ id: id, code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain, bundle: _this3 });
6450
6451 _this3.modules.push(module);
6452 _this3.moduleById[id] = module;
6453
6454 return _this3.fetchAllDependencies(module).then(function () {
6455 return module;
6456 });
6457 });
6458 };
6459
6460 Bundle.prototype.fetchAllDependencies = function fetchAllDependencies(module) {
6461 var _this4 = this;
6462
6463 var promises = module.dependencies.map(function (source) {
6464 return Promise.resolve(_this4.resolveId(source, module.id)).then(function (resolvedId) {
6465 if (!resolvedId) {
6466 if (! ~_this4.external.indexOf(source)) _this4.onwarn('Treating \'' + source + '\' as external dependency');
6467 module.resolvedIds[source] = source;
6468
6469 if (!_this4.moduleById[source]) {
6470 var _module = new ExternalModule(source);
6471 _this4.externalModules.push(_module);
6472 _this4.moduleById[source] = _module;
6473 }
6474 } else {
6475 if (resolvedId === module.id) {
6476 throw new Error('A module cannot import itself (' + resolvedId + ')');
6477 }
6478
6479 module.resolvedIds[source] = resolvedId;
6480 return _this4.fetchModule(resolvedId, module.id);
6481 }
6482 });
6483 });
6484
6485 return Promise.all(promises);
6486 };
6487
6488 Bundle.prototype.render = function render() {
6489 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
6490
6491 var format = options.format || 'es6';
6492
6493 // Determine export mode - 'default', 'named', 'none'
6494 var exportMode = getExportMode(this, options.exports);
6495
6496 var magicString = new MagicString.Bundle({ separator: '\n\n' });
6497 var usedModules = [];
6498
6499 this.orderedModules.forEach(function (module) {
6500 var source = module.render(format === 'es6');
6501 if (source.toString().length) {
6502 magicString.addSource(source);
6503 usedModules.push(module);
6504 }
6505 });
6506
6507 var intro = [options.intro].concat(this.plugins.map(function (plugin) {
6508 return plugin.intro && plugin.intro();
6509 })).filter(Boolean).join('\n\n');
6510
6511 if (intro) magicString.prepend(intro + '\n');
6512 if (options.outro) magicString.append('\n' + options.outro);
6513
6514 var indentString = getIndentString(magicString, options);
6515
6516 var finalise = finalisers[format];
6517 if (!finalise) throw new Error('You must specify an output type - valid options are ' + keys(finalisers).join(', '));
6518
6519 magicString = finalise(this, magicString.trim(), { exportMode: exportMode, indentString: indentString }, options);
6520
6521 var banner = [options.banner].concat(this.plugins.map(function (plugin) {
6522 return plugin.banner;
6523 })).map(callIfFunction).filter(Boolean).join('\n');
6524
6525 var footer = [options.footer].concat(this.plugins.map(function (plugin) {
6526 return plugin.footer;
6527 })).map(callIfFunction).filter(Boolean).join('\n');
6528
6529 if (banner) magicString.prepend(banner + '\n');
6530 if (footer) magicString.append('\n' + footer);
6531
6532 var code = magicString.toString();
6533 var map = null;
6534
6535 if (options.sourceMap) {
6536 var file = options.sourceMapFile || options.dest;
6537 map = magicString.generateMap({
6538 includeContent: true,
6539 file: file
6540 // TODO
6541 });
6542
6543 if (this.transformers.length) map = collapseSourcemaps(map, usedModules);
6544 map.sources = map.sources.map(unixizePath);
6545 }
6546
6547 return { code: code, map: map };
6548 };
6549
6550 Bundle.prototype.sort = function sort() {
6551 var seen = {};
6552 var ordered = [];
6553 var hasCycles = undefined;
6554
6555 var strongDeps = {};
6556 var stronglyDependsOn = {};
6557
6558 function visit(module) {
6559 if (seen[module.id]) return;
6560 seen[module.id] = true;
6561
6562 var _module$consolidateDependencies = module.consolidateDependencies();
6563
6564 var strongDependencies = _module$consolidateDependencies.strongDependencies;
6565 var weakDependencies = _module$consolidateDependencies.weakDependencies;
6566
6567 strongDeps[module.id] = [];
6568 stronglyDependsOn[module.id] = {};
6569
6570 strongDependencies.forEach(function (imported) {
6571 strongDeps[module.id].push(imported);
6572
6573 if (seen[imported.id]) {
6574 // we need to prevent an infinite loop, and note that
6575 // we need to check for strong/weak dependency relationships
6576 hasCycles = true;
6577 return;
6578 }
6579
6580 visit(imported);
6581 });
6582
6583 weakDependencies.forEach(function (imported) {
6584 if (seen[imported.id]) {
6585 // we need to prevent an infinite loop, and note that
6586 // we need to check for strong/weak dependency relationships
6587 hasCycles = true;
6588 return;
6589 }
6590
6591 visit(imported);
6592 });
6593
6594 // add second (and third...) order dependencies
6595 function addStrongDependencies(dependency) {
6596 if (stronglyDependsOn[module.id][dependency.id]) return;
6597
6598 stronglyDependsOn[module.id][dependency.id] = true;
6599 strongDeps[dependency.id].forEach(addStrongDependencies);
6600 }
6601
6602 strongDeps[module.id].forEach(addStrongDependencies);
6603
6604 ordered.push(module);
6605 }
6606
6607 this.modules.forEach(visit);
6608
6609 if (hasCycles) {
6610 var unordered = ordered;
6611 ordered = [];
6612
6613 // unordered is actually semi-ordered, as [ fewer dependencies ... more dependencies ]
6614 unordered.forEach(function (module) {
6615 // ensure strong dependencies of `module` that don't strongly depend on `module` go first
6616 strongDeps[module.id].forEach(place);
6617
6618 function place(dep) {
6619 if (!stronglyDependsOn[dep.id][module.id] && ! ~ordered.indexOf(dep)) {
6620 strongDeps[dep.id].forEach(place);
6621 ordered.push(dep);
6622 }
6623 }
6624
6625 if (! ~ordered.indexOf(module)) {
6626 ordered.push(module);
6627 }
6628 });
6629 }
6630
6631 return ordered;
6632 };
6633
6634 return Bundle;
6635 })();
6636
6637 var VERSION = '0.21.0';
6638
6639 function rollup(options) {
6640 if (!options || !options.entry) {
6641 return Promise.reject(new Error('You must supply options.entry to rollup'));
6642 }
6643
6644 if (options.transform || options.load || options.resolveId || options.resolveExternal) {
6645 return Promise.reject(new Error('The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://github.com/rollup/rollup/wiki/Plugins for details'));
6646 }
6647
6648 var bundle = new Bundle(options);
6649
6650 return bundle.build().then(function () {
6651 return {
6652 imports: bundle.externalModules.map(function (module) {
6653 return module.id;
6654 }),
6655 exports: keys(bundle.entryModule.exports),
6656 modules: bundle.orderedModules.map(function (module) {
6657 return { id: module.id };
6658 }),
6659
6660 generate: function (options) {
6661 return bundle.render(options);
6662 },
6663 write: function (options) {
6664 if (!options || !options.dest) {
6665 throw new Error('You must supply options.dest to bundle.write');
6666 }
6667
6668 var dest = options.dest;
6669
6670 var _bundle$render = bundle.render(options);
6671
6672 var code = _bundle$render.code;
6673 var map = _bundle$render.map;
6674
6675 var promises = [];
6676
6677 if (options.sourceMap) {
6678 var url = undefined;
6679
6680 if (options.sourceMap === 'inline') {
6681 url = map.toUrl();
6682 } else {
6683 url = _basename(dest) + '.map';
6684 promises.push(writeFile(dest + '.map', map.toString()));
6685 }
6686
6687 code += '\n//# ' + SOURCEMAPPING_URL$1 + '=' + url;
6688 }
6689
6690 promises.push(writeFile(dest, code));
6691 return Promise.all(promises);
6692 }
6693 };
6694 });
6695 }
6696
6697 exports.rollup = rollup;
6698 exports.VERSION = VERSION;
6699
6700}));
6701//# sourceMappingURL=rollup.browser.js.map
\No newline at end of file