UNPKG

213 kBJavaScriptView Raw
1/*
2 Rollup.js v0.20.4
3 Wed Nov 04 2015 15:28:47 GMT-0500 (EST) - commit 6593d5824c550b89bc005c2ec6748839507adf92
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 function makePredicate(words) {
1101 words = words.split(" ");
1102 var f = "",
1103 cats = [];
1104 out: for (var i = 0; i < words.length; ++i) {
1105 for (var j = 0; j < cats.length; ++j) {
1106 if (cats[j][0].length == words[i].length) {
1107 cats[j].push(words[i]);
1108 continue out;
1109 }
1110 }cats.push([words[i]]);
1111 }
1112 function compareTo(arr) {
1113 if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
1114 f += "switch(str){";
1115 for (var i = 0; i < arr.length; ++i) {
1116 f += "case " + JSON.stringify(arr[i]) + ":";
1117 }f += "return true}return false;";
1118 }
1119
1120 // When there are more than three length categories, an outer
1121 // switch first dispatches on the lengths, to save on comparisons.
1122
1123 if (cats.length > 3) {
1124 cats.sort(function (a, b) {
1125 return b.length - a.length;
1126 });
1127 f += "switch(str.length){";
1128 for (var i = 0; i < cats.length; ++i) {
1129 var cat = cats[i];
1130 f += "case " + cat[0].length + ":";
1131 compareTo(cat);
1132 }
1133 f += "}";
1134
1135 // Otherwise, simply generate a flat `switch` statement.
1136 } else {
1137 compareTo(words);
1138 }
1139 return new Function("str", f);
1140 }
1141
1142 // Reserved word lists for various dialects of the language
1143
1144 var reservedWords$1 = {
1145 3: makePredicate("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"),
1146 5: makePredicate("class enum extends super const export import"),
1147 6: makePredicate("enum await"),
1148 strict: makePredicate("implements interface let package private protected public static yield"),
1149 strictBind: makePredicate("eval arguments")
1150 };
1151
1152 // And the keywords
1153
1154 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";
1155
1156 var keywords = {
1157 5: makePredicate(ecma5AndLessKeywords),
1158 6: makePredicate(ecma5AndLessKeywords + " let const class extends export import yield super")
1159 };
1160
1161 // ## Character categories
1162
1163 // Big ugly regular expressions that match characters in the
1164 // whitespace, identifier, and identifier-start categories. These
1165 // are only applied when a character is found to actually have a
1166 // code point above 128.
1167 // Generated by `tools/generate-identifier-regex.js`.
1168
1169 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";
1170 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";
1171
1172 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1173 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1174
1175 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1176
1177 // These are a run-length and offset encoded representation of the
1178 // >0xffff code points that are a valid part of identifiers. The
1179 // offset starts at 0x10000, and each pair of numbers represents an
1180 // offset to the next range, and then a size of the range. They were
1181 // generated by tools/generate-identifier-regex.js
1182 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];
1183 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];
1184
1185 // This has a complexity linear to the value of the code. The
1186 // assumption is that looking up astral identifier characters is
1187 // rare.
1188 function isInAstralSet(code, set) {
1189 var pos = 0x10000;
1190 for (var i = 0; i < set.length; i += 2) {
1191 pos += set[i];
1192 if (pos > code) return false;
1193 pos += set[i + 1];
1194 if (pos >= code) return true;
1195 }
1196 }
1197
1198 // Test whether a given character code starts an identifier.
1199
1200 function isIdentifierStart(code, astral) {
1201 if (code < 65) return code === 36;
1202 if (code < 91) return true;
1203 if (code < 97) return code === 95;
1204 if (code < 123) return true;
1205 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
1206 if (astral === false) return false;
1207 return isInAstralSet(code, astralIdentifierStartCodes);
1208 }
1209
1210 // Test whether a given character is part of an identifier.
1211
1212 function isIdentifierChar(code, astral) {
1213 if (code < 48) return code === 36;
1214 if (code < 58) return true;
1215 if (code < 65) return false;
1216 if (code < 91) return true;
1217 if (code < 97) return code === 95;
1218 if (code < 123) return true;
1219 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
1220 if (astral === false) return false;
1221 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1222 }
1223
1224 // ## Token types
1225
1226 // The assignment of fine-grained, information-carrying type objects
1227 // allows the tokenizer to store the information it has about a
1228 // token in a way that is very cheap for the parser to look up.
1229
1230 // All token type variables start with an underscore, to make them
1231 // easy to recognize.
1232
1233 // The `beforeExpr` property is used to disambiguate between regular
1234 // expressions and divisions. It is set on all token types that can
1235 // be followed by an expression (thus, a slash after them would be a
1236 // regular expression).
1237 //
1238 // `isLoop` marks a keyword as starting a loop, which is important
1239 // to know when parsing a label, in order to allow or disallow
1240 // continue jumps to that label.
1241
1242 var TokenType = function TokenType(label) {
1243 var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1244 babelHelpers.classCallCheck(this, TokenType);
1245
1246 this.label = label;
1247 this.keyword = conf.keyword;
1248 this.beforeExpr = !!conf.beforeExpr;
1249 this.startsExpr = !!conf.startsExpr;
1250 this.isLoop = !!conf.isLoop;
1251 this.isAssign = !!conf.isAssign;
1252 this.prefix = !!conf.prefix;
1253 this.postfix = !!conf.postfix;
1254 this.binop = conf.binop || null;
1255 this.updateContext = null;
1256 };
1257
1258 function binop(name, prec) {
1259 return new TokenType(name, { beforeExpr: true, binop: prec });
1260 }
1261 var beforeExpr = { beforeExpr: true };
1262 var startsExpr = { startsExpr: true };
1263 var tt = {
1264 num: new TokenType("num", startsExpr),
1265 regexp: new TokenType("regexp", startsExpr),
1266 string: new TokenType("string", startsExpr),
1267 name: new TokenType("name", startsExpr),
1268 eof: new TokenType("eof"),
1269
1270 // Punctuation token types.
1271 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
1272 bracketR: new TokenType("]"),
1273 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
1274 braceR: new TokenType("}"),
1275 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
1276 parenR: new TokenType(")"),
1277 comma: new TokenType(",", beforeExpr),
1278 semi: new TokenType(";", beforeExpr),
1279 colon: new TokenType(":", beforeExpr),
1280 dot: new TokenType("."),
1281 question: new TokenType("?", beforeExpr),
1282 arrow: new TokenType("=>", beforeExpr),
1283 template: new TokenType("template"),
1284 ellipsis: new TokenType("...", beforeExpr),
1285 backQuote: new TokenType("`", startsExpr),
1286 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
1287
1288 // Operators. These carry several kinds of properties to help the
1289 // parser use them properly (the presence of these properties is
1290 // what categorizes them as operators).
1291 //
1292 // `binop`, when present, specifies that this operator is a binary
1293 // operator, and will refer to its precedence.
1294 //
1295 // `prefix` and `postfix` mark the operator as a prefix or postfix
1296 // unary operator.
1297 //
1298 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1299 // binary operators with a very low precedence, that should result
1300 // in AssignmentExpression nodes.
1301
1302 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
1303 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
1304 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
1305 prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }),
1306 logicalOR: binop("||", 1),
1307 logicalAND: binop("&&", 2),
1308 bitwiseOR: binop("|", 3),
1309 bitwiseXOR: binop("^", 4),
1310 bitwiseAND: binop("&", 5),
1311 equality: binop("==/!=", 6),
1312 relational: binop("</>", 7),
1313 bitShift: binop("<</>>", 8),
1314 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
1315 modulo: binop("%", 10),
1316 star: binop("*", 10),
1317 slash: binop("/", 10)
1318 };
1319
1320 // Map keyword names to token types.
1321
1322 var keywordTypes = {};
1323
1324 // Succinct definitions of keyword token types
1325 function kw(name) {
1326 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1327
1328 options.keyword = name;
1329 keywordTypes[name] = tt["_" + name] = new TokenType(name, options);
1330 }
1331
1332 kw("break");
1333 kw("case", beforeExpr);
1334 kw("catch");
1335 kw("continue");
1336 kw("debugger");
1337 kw("default", beforeExpr);
1338 kw("do", { isLoop: true });
1339 kw("else", beforeExpr);
1340 kw("finally");
1341 kw("for", { isLoop: true });
1342 kw("function", startsExpr);
1343 kw("if");
1344 kw("return", beforeExpr);
1345 kw("switch");
1346 kw("throw", beforeExpr);
1347 kw("try");
1348 kw("var");
1349 kw("let");
1350 kw("const");
1351 kw("while", { isLoop: true });
1352 kw("with");
1353 kw("new", { beforeExpr: true, startsExpr: true });
1354 kw("this", startsExpr);
1355 kw("super", startsExpr);
1356 kw("class");
1357 kw("extends", beforeExpr);
1358 kw("export");
1359 kw("import");
1360 kw("yield", { beforeExpr: true, startsExpr: true });
1361 kw("null", startsExpr);
1362 kw("true", startsExpr);
1363 kw("false", startsExpr);
1364 kw("in", { beforeExpr: true, binop: 7 });
1365 kw("instanceof", { beforeExpr: true, binop: 7 });
1366 kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
1367 kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
1368 kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });
1369
1370 // Matches a whole line break (where CRLF is considered a single
1371 // line break). Used to count lines.
1372
1373 var lineBreak = /\r\n?|\n|\u2028|\u2029/;
1374 var lineBreakG = new RegExp(lineBreak.source, "g");
1375
1376 function isNewLine(code) {
1377 return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
1378 }
1379
1380 var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
1381
1382 function isArray$1(obj) {
1383 return Object.prototype.toString.call(obj) === "[object Array]";
1384 }
1385
1386 // Checks if an object has a property.
1387
1388 function has(obj, propName) {
1389 return Object.prototype.hasOwnProperty.call(obj, propName);
1390 }
1391
1392 // These are used when `options.locations` is on, for the
1393 // `startLoc` and `endLoc` properties.
1394
1395 var Position = (function () {
1396 function Position(line, col) {
1397 babelHelpers.classCallCheck(this, Position);
1398
1399 this.line = line;
1400 this.column = col;
1401 }
1402
1403 Position.prototype.offset = function offset(n) {
1404 return new Position(this.line, this.column + n);
1405 };
1406
1407 return Position;
1408 })();
1409
1410 var SourceLocation = function SourceLocation(p, start, end) {
1411 babelHelpers.classCallCheck(this, SourceLocation);
1412
1413 this.start = start;
1414 this.end = end;
1415 if (p.sourceFile !== null) this.source = p.sourceFile;
1416 }
1417
1418 // The `getLineInfo` function is mostly useful when the
1419 // `locations` option is off (for performance reasons) and you
1420 // want to find the line/column position for a given character
1421 // offset. `input` should be the code string that the offset refers
1422 // into.
1423
1424 ;
1425
1426 function getLineInfo(input, offset) {
1427 for (var line = 1, cur = 0;;) {
1428 lineBreakG.lastIndex = cur;
1429 var match = lineBreakG.exec(input);
1430 if (match && match.index < offset) {
1431 ++line;
1432 cur = match.index + match[0].length;
1433 } else {
1434 return new Position(line, offset - cur);
1435 }
1436 }
1437 }
1438
1439 // A second optional argument can be given to further configure
1440 // the parser process. These options are recognized:
1441
1442 var defaultOptions = {
1443 // `ecmaVersion` indicates the ECMAScript version to parse. Must
1444 // be either 3, or 5, or 6. This influences support for strict
1445 // mode, the set of reserved words, support for getters and
1446 // setters and other features.
1447 ecmaVersion: 5,
1448 // Source type ("script" or "module") for different semantics
1449 sourceType: "script",
1450 // `onInsertedSemicolon` can be a callback that will be called
1451 // when a semicolon is automatically inserted. It will be passed
1452 // th position of the comma as an offset, and if `locations` is
1453 // enabled, it is given the location as a `{line, column}` object
1454 // as second argument.
1455 onInsertedSemicolon: null,
1456 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
1457 // trailing commas.
1458 onTrailingComma: null,
1459 // By default, reserved words are not enforced. Disable
1460 // `allowReserved` to enforce them. When this option has the
1461 // value "never", reserved words and keywords can also not be
1462 // used as property names.
1463 allowReserved: true,
1464 // When enabled, a return at the top level is not considered an
1465 // error.
1466 allowReturnOutsideFunction: false,
1467 // When enabled, import/export statements are not constrained to
1468 // appearing at the top of the program.
1469 allowImportExportEverywhere: false,
1470 // When enabled, hashbang directive in the beginning of file
1471 // is allowed and treated as a line comment.
1472 allowHashBang: false,
1473 // When `locations` is on, `loc` properties holding objects with
1474 // `start` and `end` properties in `{line, column}` form (with
1475 // line being 1-based and column 0-based) will be attached to the
1476 // nodes.
1477 locations: false,
1478 // A function can be passed as `onToken` option, which will
1479 // cause Acorn to call that function with object in the same
1480 // format as tokenize() returns. Note that you are not
1481 // allowed to call the parser from the callback—that will
1482 // corrupt its internal state.
1483 onToken: null,
1484 // A function can be passed as `onComment` option, which will
1485 // cause Acorn to call that function with `(block, text, start,
1486 // end)` parameters whenever a comment is skipped. `block` is a
1487 // boolean indicating whether this is a block (`/* */`) comment,
1488 // `text` is the content of the comment, and `start` and `end` are
1489 // character offsets that denote the start and end of the comment.
1490 // When the `locations` option is on, two more parameters are
1491 // passed, the full `{line, column}` locations of the start and
1492 // end of the comments. Note that you are not allowed to call the
1493 // parser from the callback—that will corrupt its internal state.
1494 onComment: null,
1495 // Nodes have their start and end characters offsets recorded in
1496 // `start` and `end` properties (directly on the node, rather than
1497 // the `loc` object, which holds line/column data. To also add a
1498 // [semi-standardized][range] `range` property holding a `[start,
1499 // end]` array with the same numbers, set the `ranges` option to
1500 // `true`.
1501 //
1502 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
1503 ranges: false,
1504 // It is possible to parse multiple files into a single AST by
1505 // passing the tree produced by parsing the first file as
1506 // `program` option in subsequent parses. This will add the
1507 // toplevel forms of the parsed file to the `Program` (top) node
1508 // of an existing parse tree.
1509 program: null,
1510 // When `locations` is on, you can pass this to record the source
1511 // file in every node's `loc` object.
1512 sourceFile: null,
1513 // This value, if given, is stored in every node, whether
1514 // `locations` is on or off.
1515 directSourceFile: null,
1516 // When enabled, parenthesized expressions are represented by
1517 // (non-standard) ParenthesizedExpression nodes
1518 preserveParens: false,
1519 plugins: {}
1520 };
1521
1522 // Interpret and default an options object
1523
1524 function getOptions(opts) {
1525 var options = {};
1526 for (var opt in defaultOptions) {
1527 options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
1528 }if (isArray$1(options.onToken)) {
1529 (function () {
1530 var tokens = options.onToken;
1531 options.onToken = function (token) {
1532 return tokens.push(token);
1533 };
1534 })();
1535 }
1536 if (isArray$1(options.onComment)) options.onComment = pushComment(options, options.onComment);
1537
1538 return options;
1539 }
1540
1541 function pushComment(options, array) {
1542 return function (block, text, start, end, startLoc, endLoc) {
1543 var comment = {
1544 type: block ? 'Block' : 'Line',
1545 value: text,
1546 start: start,
1547 end: end
1548 };
1549 if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc);
1550 if (options.ranges) comment.range = [start, end];
1551 array.push(comment);
1552 };
1553 }
1554
1555 // Registered plugins
1556 var plugins = {};
1557
1558 var Parser = (function () {
1559 function Parser(options, input, startPos) {
1560 babelHelpers.classCallCheck(this, Parser);
1561
1562 this.options = getOptions(options);
1563 this.sourceFile = this.options.sourceFile;
1564 this.isKeyword = keywords[this.options.ecmaVersion >= 6 ? 6 : 5];
1565 this.isReservedWord = reservedWords$1[this.options.ecmaVersion];
1566 this.input = String(input);
1567
1568 // Used to signal to callers of `readWord1` whether the word
1569 // contained any escape sequences. This is needed because words with
1570 // escape sequences must not be interpreted as keywords.
1571 this.containsEsc = false;
1572
1573 // Load plugins
1574 this.loadPlugins(this.options.plugins);
1575
1576 // Set up token state
1577
1578 // The current position of the tokenizer in the input.
1579 if (startPos) {
1580 this.pos = startPos;
1581 this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
1582 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
1583 } else {
1584 this.pos = this.lineStart = 0;
1585 this.curLine = 1;
1586 }
1587
1588 // Properties of the current token:
1589 // Its type
1590 this.type = tt.eof;
1591 // For tokens that include more information than their type, the value
1592 this.value = null;
1593 // Its start and end offset
1594 this.start = this.end = this.pos;
1595 // And, if locations are used, the {line, column} object
1596 // corresponding to those offsets
1597 this.startLoc = this.endLoc = this.curPosition();
1598
1599 // Position information for the previous token
1600 this.lastTokEndLoc = this.lastTokStartLoc = null;
1601 this.lastTokStart = this.lastTokEnd = this.pos;
1602
1603 // The context stack is used to superficially track syntactic
1604 // context to predict whether a regular expression is allowed in a
1605 // given position.
1606 this.context = this.initialContext();
1607 this.exprAllowed = true;
1608
1609 // Figure out if it's a module code.
1610 this.strict = this.inModule = this.options.sourceType === "module";
1611
1612 // Used to signify the start of a potential arrow function
1613 this.potentialArrowAt = -1;
1614
1615 // Flags to track whether we are in a function, a generator.
1616 this.inFunction = this.inGenerator = false;
1617 // Labels in scope.
1618 this.labels = [];
1619
1620 // If enabled, skip leading hashbang line.
1621 if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2);
1622 }
1623
1624 Parser.prototype.extend = function extend(name, f) {
1625 this[name] = f(this[name]);
1626 };
1627
1628 Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
1629 for (var _name in pluginConfigs) {
1630 var plugin = plugins[_name];
1631 if (!plugin) throw new Error("Plugin '" + _name + "' not found");
1632 plugin(this, pluginConfigs[_name]);
1633 }
1634 };
1635
1636 Parser.prototype.parse = function parse() {
1637 var node = this.options.program || this.startNode();
1638 this.nextToken();
1639 return this.parseTopLevel(node);
1640 };
1641
1642 return Parser;
1643 })();
1644
1645 var pp = Parser.prototype;
1646
1647 // ## Parser utilities
1648
1649 // Test whether a statement node is the string literal `"use strict"`.
1650
1651 pp.isUseStrict = function (stmt) {
1652 return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict";
1653 };
1654
1655 // Predicate that tests whether the next token is of the given
1656 // type, and if yes, consumes it as a side effect.
1657
1658 pp.eat = function (type) {
1659 if (this.type === type) {
1660 this.next();
1661 return true;
1662 } else {
1663 return false;
1664 }
1665 };
1666
1667 // Tests whether parsed token is a contextual keyword.
1668
1669 pp.isContextual = function (name) {
1670 return this.type === tt.name && this.value === name;
1671 };
1672
1673 // Consumes contextual keyword if possible.
1674
1675 pp.eatContextual = function (name) {
1676 return this.value === name && this.eat(tt.name);
1677 };
1678
1679 // Asserts that following token is given contextual keyword.
1680
1681 pp.expectContextual = function (name) {
1682 if (!this.eatContextual(name)) this.unexpected();
1683 };
1684
1685 // Test whether a semicolon can be inserted at the current position.
1686
1687 pp.canInsertSemicolon = function () {
1688 return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
1689 };
1690
1691 pp.insertSemicolon = function () {
1692 if (this.canInsertSemicolon()) {
1693 if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
1694 return true;
1695 }
1696 };
1697
1698 // Consume a semicolon, or, failing that, see if we are allowed to
1699 // pretend that there is a semicolon at this position.
1700
1701 pp.semicolon = function () {
1702 if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected();
1703 };
1704
1705 pp.afterTrailingComma = function (tokType) {
1706 if (this.type == tokType) {
1707 if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
1708 this.next();
1709 return true;
1710 }
1711 };
1712
1713 // Expect a token of a given type. If found, consume it, otherwise,
1714 // raise an unexpected token error.
1715
1716 pp.expect = function (type) {
1717 this.eat(type) || this.unexpected();
1718 };
1719
1720 // Raise an unexpected token error.
1721
1722 pp.unexpected = function (pos) {
1723 this.raise(pos != null ? pos : this.start, "Unexpected token");
1724 };
1725
1726 var pp$1 = Parser.prototype;
1727
1728 // ### Statement parsing
1729
1730 // Parse a program. Initializes the parser, reads any number of
1731 // statements, and wraps them in a Program node. Optionally takes a
1732 // `program` argument. If present, the statements will be appended
1733 // to its body instead of creating a new node.
1734
1735 pp$1.parseTopLevel = function (node) {
1736 var first = true;
1737 if (!node.body) node.body = [];
1738 while (this.type !== tt.eof) {
1739 var stmt = this.parseStatement(true, true);
1740 node.body.push(stmt);
1741 if (first) {
1742 if (this.isUseStrict(stmt)) this.setStrict(true);
1743 first = false;
1744 }
1745 }
1746 this.next();
1747 if (this.options.ecmaVersion >= 6) {
1748 node.sourceType = this.options.sourceType;
1749 }
1750 return this.finishNode(node, "Program");
1751 };
1752
1753 var loopLabel = { kind: "loop" };
1754 var switchLabel = { kind: "switch" };
1755 // Parse a single statement.
1756 //
1757 // If expecting a statement and finding a slash operator, parse a
1758 // regular expression literal. This is to handle cases like
1759 // `if (foo) /blah/.exec(foo)`, where looking at the previous token
1760 // does not help.
1761
1762 pp$1.parseStatement = function (declaration, topLevel) {
1763 var starttype = this.type,
1764 node = this.startNode();
1765
1766 // Most types of statements are recognized by the keyword they
1767 // start with. Many are trivial to parse, some require a bit of
1768 // complexity.
1769
1770 switch (starttype) {
1771 case tt._break:case tt._continue:
1772 return this.parseBreakContinueStatement(node, starttype.keyword);
1773 case tt._debugger:
1774 return this.parseDebuggerStatement(node);
1775 case tt._do:
1776 return this.parseDoStatement(node);
1777 case tt._for:
1778 return this.parseForStatement(node);
1779 case tt._function:
1780 if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
1781 return this.parseFunctionStatement(node);
1782 case tt._class:
1783 if (!declaration) this.unexpected();
1784 return this.parseClass(node, true);
1785 case tt._if:
1786 return this.parseIfStatement(node);
1787 case tt._return:
1788 return this.parseReturnStatement(node);
1789 case tt._switch:
1790 return this.parseSwitchStatement(node);
1791 case tt._throw:
1792 return this.parseThrowStatement(node);
1793 case tt._try:
1794 return this.parseTryStatement(node);
1795 case tt._let:case tt._const:
1796 if (!declaration) this.unexpected(); // NOTE: falls through to _var
1797 case tt._var:
1798 return this.parseVarStatement(node, starttype);
1799 case tt._while:
1800 return this.parseWhileStatement(node);
1801 case tt._with:
1802 return this.parseWithStatement(node);
1803 case tt.braceL:
1804 return this.parseBlock();
1805 case tt.semi:
1806 return this.parseEmptyStatement(node);
1807 case tt._export:
1808 case tt._import:
1809 if (!this.options.allowImportExportEverywhere) {
1810 if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
1811 if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
1812 }
1813 return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
1814
1815 // If the statement does not start with a statement keyword or a
1816 // brace, it's an ExpressionStatement or LabeledStatement. We
1817 // simply start parsing an expression, and afterwards, if the
1818 // next token is a colon and the expression was a simple
1819 // Identifier node, we switch to interpreting it as a label.
1820 default:
1821 var maybeName = this.value,
1822 expr = this.parseExpression();
1823 if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
1824 }
1825 };
1826
1827 pp$1.parseBreakContinueStatement = function (node, keyword) {
1828 var isBreak = keyword == "break";
1829 this.next();
1830 if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== tt.name) this.unexpected();else {
1831 node.label = this.parseIdent();
1832 this.semicolon();
1833 }
1834
1835 // Verify that there is an actual destination to break or
1836 // continue to.
1837 for (var i = 0; i < this.labels.length; ++i) {
1838 var lab = this.labels[i];
1839 if (node.label == null || lab.name === node.label.name) {
1840 if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
1841 if (node.label && isBreak) break;
1842 }
1843 }
1844 if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
1845 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
1846 };
1847
1848 pp$1.parseDebuggerStatement = function (node) {
1849 this.next();
1850 this.semicolon();
1851 return this.finishNode(node, "DebuggerStatement");
1852 };
1853
1854 pp$1.parseDoStatement = function (node) {
1855 this.next();
1856 this.labels.push(loopLabel);
1857 node.body = this.parseStatement(false);
1858 this.labels.pop();
1859 this.expect(tt._while);
1860 node.test = this.parseParenExpression();
1861 if (this.options.ecmaVersion >= 6) this.eat(tt.semi);else this.semicolon();
1862 return this.finishNode(node, "DoWhileStatement");
1863 };
1864
1865 // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
1866 // loop is non-trivial. Basically, we have to parse the init `var`
1867 // statement or expression, disallowing the `in` operator (see
1868 // the second parameter to `parseExpression`), and then check
1869 // whether the next token is `in` or `of`. When there is no init
1870 // part (semicolon immediately after the opening parenthesis), it
1871 // is a regular `for` loop.
1872
1873 pp$1.parseForStatement = function (node) {
1874 this.next();
1875 this.labels.push(loopLabel);
1876 this.expect(tt.parenL);
1877 if (this.type === tt.semi) return this.parseFor(node, null);
1878 if (this.type === tt._var || this.type === tt._let || this.type === tt._const) {
1879 var _init = this.startNode(),
1880 varKind = this.type;
1881 this.next();
1882 this.parseVar(_init, true, varKind);
1883 this.finishNode(_init, "VariableDeclaration");
1884 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);
1885 return this.parseFor(node, _init);
1886 }
1887 var refShorthandDefaultPos = { start: 0 };
1888 var init = this.parseExpression(true, refShorthandDefaultPos);
1889 if (this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
1890 this.toAssignable(init);
1891 this.checkLVal(init);
1892 return this.parseForIn(node, init);
1893 } else if (refShorthandDefaultPos.start) {
1894 this.unexpected(refShorthandDefaultPos.start);
1895 }
1896 return this.parseFor(node, init);
1897 };
1898
1899 pp$1.parseFunctionStatement = function (node) {
1900 this.next();
1901 return this.parseFunction(node, true);
1902 };
1903
1904 pp$1.parseIfStatement = function (node) {
1905 this.next();
1906 node.test = this.parseParenExpression();
1907 node.consequent = this.parseStatement(false);
1908 node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
1909 return this.finishNode(node, "IfStatement");
1910 };
1911
1912 pp$1.parseReturnStatement = function (node) {
1913 if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
1914 this.next();
1915
1916 // In `return` (and `break`/`continue`), the keywords with
1917 // optional arguments, we eagerly look for a semicolon or the
1918 // possibility to insert one.
1919
1920 if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null;else {
1921 node.argument = this.parseExpression();this.semicolon();
1922 }
1923 return this.finishNode(node, "ReturnStatement");
1924 };
1925
1926 pp$1.parseSwitchStatement = function (node) {
1927 this.next();
1928 node.discriminant = this.parseParenExpression();
1929 node.cases = [];
1930 this.expect(tt.braceL);
1931 this.labels.push(switchLabel);
1932
1933 // Statements under must be grouped (by label) in SwitchCase
1934 // nodes. `cur` is used to keep the node that we are currently
1935 // adding statements to.
1936
1937 for (var cur, sawDefault = false; this.type != tt.braceR;) {
1938 if (this.type === tt._case || this.type === tt._default) {
1939 var isCase = this.type === tt._case;
1940 if (cur) this.finishNode(cur, "SwitchCase");
1941 node.cases.push(cur = this.startNode());
1942 cur.consequent = [];
1943 this.next();
1944 if (isCase) {
1945 cur.test = this.parseExpression();
1946 } else {
1947 if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
1948 sawDefault = true;
1949 cur.test = null;
1950 }
1951 this.expect(tt.colon);
1952 } else {
1953 if (!cur) this.unexpected();
1954 cur.consequent.push(this.parseStatement(true));
1955 }
1956 }
1957 if (cur) this.finishNode(cur, "SwitchCase");
1958 this.next(); // Closing brace
1959 this.labels.pop();
1960 return this.finishNode(node, "SwitchStatement");
1961 };
1962
1963 pp$1.parseThrowStatement = function (node) {
1964 this.next();
1965 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
1966 node.argument = this.parseExpression();
1967 this.semicolon();
1968 return this.finishNode(node, "ThrowStatement");
1969 };
1970
1971 // Reused empty array added for node fields that are always empty.
1972
1973 var empty = [];
1974
1975 pp$1.parseTryStatement = function (node) {
1976 this.next();
1977 node.block = this.parseBlock();
1978 node.handler = null;
1979 if (this.type === tt._catch) {
1980 var clause = this.startNode();
1981 this.next();
1982 this.expect(tt.parenL);
1983 clause.param = this.parseBindingAtom();
1984 this.checkLVal(clause.param, true);
1985 this.expect(tt.parenR);
1986 clause.guard = null;
1987 clause.body = this.parseBlock();
1988 node.handler = this.finishNode(clause, "CatchClause");
1989 }
1990 node.guardedHandlers = empty;
1991 node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
1992 if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
1993 return this.finishNode(node, "TryStatement");
1994 };
1995
1996 pp$1.parseVarStatement = function (node, kind) {
1997 this.next();
1998 this.parseVar(node, false, kind);
1999 this.semicolon();
2000 return this.finishNode(node, "VariableDeclaration");
2001 };
2002
2003 pp$1.parseWhileStatement = function (node) {
2004 this.next();
2005 node.test = this.parseParenExpression();
2006 this.labels.push(loopLabel);
2007 node.body = this.parseStatement(false);
2008 this.labels.pop();
2009 return this.finishNode(node, "WhileStatement");
2010 };
2011
2012 pp$1.parseWithStatement = function (node) {
2013 if (this.strict) this.raise(this.start, "'with' in strict mode");
2014 this.next();
2015 node.object = this.parseParenExpression();
2016 node.body = this.parseStatement(false);
2017 return this.finishNode(node, "WithStatement");
2018 };
2019
2020 pp$1.parseEmptyStatement = function (node) {
2021 this.next();
2022 return this.finishNode(node, "EmptyStatement");
2023 };
2024
2025 pp$1.parseLabeledStatement = function (node, maybeName, expr) {
2026 for (var i = 0; i < this.labels.length; ++i) {
2027 if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
2028 }var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null;
2029 for (var i = this.labels.length - 1; i >= 0; i--) {
2030 var label = this.labels[i];
2031 if (label.statementStart == node.start) {
2032 label.statementStart = this.start;
2033 label.kind = kind;
2034 } else break;
2035 }
2036 this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
2037 node.body = this.parseStatement(true);
2038 this.labels.pop();
2039 node.label = expr;
2040 return this.finishNode(node, "LabeledStatement");
2041 };
2042
2043 pp$1.parseExpressionStatement = function (node, expr) {
2044 node.expression = expr;
2045 this.semicolon();
2046 return this.finishNode(node, "ExpressionStatement");
2047 };
2048
2049 // Parse a semicolon-enclosed block of statements, handling `"use
2050 // strict"` declarations when `allowStrict` is true (used for
2051 // function bodies).
2052
2053 pp$1.parseBlock = function (allowStrict) {
2054 var node = this.startNode(),
2055 first = true,
2056 oldStrict = undefined;
2057 node.body = [];
2058 this.expect(tt.braceL);
2059 while (!this.eat(tt.braceR)) {
2060 var stmt = this.parseStatement(true);
2061 node.body.push(stmt);
2062 if (first && allowStrict && this.isUseStrict(stmt)) {
2063 oldStrict = this.strict;
2064 this.setStrict(this.strict = true);
2065 }
2066 first = false;
2067 }
2068 if (oldStrict === false) this.setStrict(false);
2069 return this.finishNode(node, "BlockStatement");
2070 };
2071
2072 // Parse a regular `for` loop. The disambiguation code in
2073 // `parseStatement` will already have parsed the init statement or
2074 // expression.
2075
2076 pp$1.parseFor = function (node, init) {
2077 node.init = init;
2078 this.expect(tt.semi);
2079 node.test = this.type === tt.semi ? null : this.parseExpression();
2080 this.expect(tt.semi);
2081 node.update = this.type === tt.parenR ? null : this.parseExpression();
2082 this.expect(tt.parenR);
2083 node.body = this.parseStatement(false);
2084 this.labels.pop();
2085 return this.finishNode(node, "ForStatement");
2086 };
2087
2088 // Parse a `for`/`in` and `for`/`of` loop, which are almost
2089 // same from parser's perspective.
2090
2091 pp$1.parseForIn = function (node, init) {
2092 var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement";
2093 this.next();
2094 node.left = init;
2095 node.right = this.parseExpression();
2096 this.expect(tt.parenR);
2097 node.body = this.parseStatement(false);
2098 this.labels.pop();
2099 return this.finishNode(node, type);
2100 };
2101
2102 // Parse a list of variable declarations.
2103
2104 pp$1.parseVar = function (node, isFor, kind) {
2105 node.declarations = [];
2106 node.kind = kind.keyword;
2107 for (;;) {
2108 var decl = this.startNode();
2109 this.parseVarId(decl);
2110 if (this.eat(tt.eq)) {
2111 decl.init = this.parseMaybeAssign(isFor);
2112 } else if (kind === tt._const && !(this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
2113 this.unexpected();
2114 } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
2115 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
2116 } else {
2117 decl.init = null;
2118 }
2119 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
2120 if (!this.eat(tt.comma)) break;
2121 }
2122 return node;
2123 };
2124
2125 pp$1.parseVarId = function (decl) {
2126 decl.id = this.parseBindingAtom();
2127 this.checkLVal(decl.id, true);
2128 };
2129
2130 // Parse a function declaration or literal (depending on the
2131 // `isStatement` parameter).
2132
2133 pp$1.parseFunction = function (node, isStatement, allowExpressionBody) {
2134 this.initFunction(node);
2135 if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star);
2136 if (isStatement || this.type === tt.name) node.id = this.parseIdent();
2137 this.parseFunctionParams(node);
2138 this.parseFunctionBody(node, allowExpressionBody);
2139 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
2140 };
2141
2142 pp$1.parseFunctionParams = function (node) {
2143 this.expect(tt.parenL);
2144 node.params = this.parseBindingList(tt.parenR, false, false);
2145 };
2146
2147 // Parse a class declaration or literal (depending on the
2148 // `isStatement` parameter).
2149
2150 pp$1.parseClass = function (node, isStatement) {
2151 this.next();
2152 this.parseClassId(node, isStatement);
2153 this.parseClassSuper(node);
2154 var classBody = this.startNode();
2155 var hadConstructor = false;
2156 classBody.body = [];
2157 this.expect(tt.braceL);
2158 while (!this.eat(tt.braceR)) {
2159 if (this.eat(tt.semi)) continue;
2160 var method = this.startNode();
2161 var isGenerator = this.eat(tt.star);
2162 var isMaybeStatic = this.type === tt.name && this.value === "static";
2163 this.parsePropertyName(method);
2164 method.static = isMaybeStatic && this.type !== tt.parenL;
2165 if (method.static) {
2166 if (isGenerator) this.unexpected();
2167 isGenerator = this.eat(tt.star);
2168 this.parsePropertyName(method);
2169 }
2170 method.kind = "method";
2171 var isGetSet = false;
2172 if (!method.computed) {
2173 var key = method.key;
2174
2175 if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
2176 isGetSet = true;
2177 method.kind = key.name;
2178 key = this.parsePropertyName(method);
2179 }
2180 if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
2181 if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
2182 if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
2183 if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
2184 method.kind = "constructor";
2185 hadConstructor = true;
2186 }
2187 }
2188 this.parseClassMethod(classBody, method, isGenerator);
2189 if (isGetSet) {
2190 var paramCount = method.kind === "get" ? 0 : 1;
2191 if (method.value.params.length !== paramCount) {
2192 var start = method.value.start;
2193 if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
2194 }
2195 }
2196 }
2197 node.body = this.finishNode(classBody, "ClassBody");
2198 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
2199 };
2200
2201 pp$1.parseClassMethod = function (classBody, method, isGenerator) {
2202 method.value = this.parseMethod(isGenerator);
2203 classBody.body.push(this.finishNode(method, "MethodDefinition"));
2204 };
2205
2206 pp$1.parseClassId = function (node, isStatement) {
2207 node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
2208 };
2209
2210 pp$1.parseClassSuper = function (node) {
2211 node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
2212 };
2213
2214 // Parses module export declaration.
2215
2216 pp$1.parseExport = function (node) {
2217 this.next();
2218 // export * from '...'
2219 if (this.eat(tt.star)) {
2220 this.expectContextual("from");
2221 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2222 this.semicolon();
2223 return this.finishNode(node, "ExportAllDeclaration");
2224 }
2225 if (this.eat(tt._default)) {
2226 // export default ...
2227 var expr = this.parseMaybeAssign();
2228 var needsSemi = true;
2229 if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
2230 needsSemi = false;
2231 if (expr.id) {
2232 expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
2233 }
2234 }
2235 node.declaration = expr;
2236 if (needsSemi) this.semicolon();
2237 return this.finishNode(node, "ExportDefaultDeclaration");
2238 }
2239 // export var|const|let|function|class ...
2240 if (this.shouldParseExportStatement()) {
2241 node.declaration = this.parseStatement(true);
2242 node.specifiers = [];
2243 node.source = null;
2244 } else {
2245 // export { x, y as z } [from '...']
2246 node.declaration = null;
2247 node.specifiers = this.parseExportSpecifiers();
2248 if (this.eatContextual("from")) {
2249 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2250 } else {
2251 node.source = null;
2252 }
2253 this.semicolon();
2254 }
2255 return this.finishNode(node, "ExportNamedDeclaration");
2256 };
2257
2258 pp$1.shouldParseExportStatement = function () {
2259 return this.type.keyword;
2260 };
2261
2262 // Parses a comma-separated list of module exports.
2263
2264 pp$1.parseExportSpecifiers = function () {
2265 var nodes = [],
2266 first = true;
2267 // export { x, y as z } [from '...']
2268 this.expect(tt.braceL);
2269 while (!this.eat(tt.braceR)) {
2270 if (!first) {
2271 this.expect(tt.comma);
2272 if (this.afterTrailingComma(tt.braceR)) break;
2273 } else first = false;
2274
2275 var node = this.startNode();
2276 node.local = this.parseIdent(this.type === tt._default);
2277 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
2278 nodes.push(this.finishNode(node, "ExportSpecifier"));
2279 }
2280 return nodes;
2281 };
2282
2283 // Parses import declaration.
2284
2285 pp$1.parseImport = function (node) {
2286 this.next();
2287 // import '...'
2288 if (this.type === tt.string) {
2289 node.specifiers = empty;
2290 node.source = this.parseExprAtom();
2291 } else {
2292 node.specifiers = this.parseImportSpecifiers();
2293 this.expectContextual("from");
2294 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2295 }
2296 this.semicolon();
2297 return this.finishNode(node, "ImportDeclaration");
2298 };
2299
2300 // Parses a comma-separated list of module imports.
2301
2302 pp$1.parseImportSpecifiers = function () {
2303 var nodes = [],
2304 first = true;
2305 if (this.type === tt.name) {
2306 // import defaultObj, { x, y as z } from '...'
2307 var node = this.startNode();
2308 node.local = this.parseIdent();
2309 this.checkLVal(node.local, true);
2310 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
2311 if (!this.eat(tt.comma)) return nodes;
2312 }
2313 if (this.type === tt.star) {
2314 var node = this.startNode();
2315 this.next();
2316 this.expectContextual("as");
2317 node.local = this.parseIdent();
2318 this.checkLVal(node.local, true);
2319 nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"));
2320 return nodes;
2321 }
2322 this.expect(tt.braceL);
2323 while (!this.eat(tt.braceR)) {
2324 if (!first) {
2325 this.expect(tt.comma);
2326 if (this.afterTrailingComma(tt.braceR)) break;
2327 } else first = false;
2328
2329 var node = this.startNode();
2330 node.imported = this.parseIdent(true);
2331 node.local = this.eatContextual("as") ? this.parseIdent() : node.imported;
2332 this.checkLVal(node.local, true);
2333 nodes.push(this.finishNode(node, "ImportSpecifier"));
2334 }
2335 return nodes;
2336 };
2337
2338 var pp$2 = Parser.prototype;
2339
2340 // Convert existing expression atom to assignable pattern
2341 // if possible.
2342
2343 pp$2.toAssignable = function (node, isBinding) {
2344 if (this.options.ecmaVersion >= 6 && node) {
2345 switch (node.type) {
2346 case "Identifier":
2347 case "ObjectPattern":
2348 case "ArrayPattern":
2349 case "AssignmentPattern":
2350 break;
2351
2352 case "ObjectExpression":
2353 node.type = "ObjectPattern";
2354 for (var i = 0; i < node.properties.length; i++) {
2355 var prop = node.properties[i];
2356 if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
2357 this.toAssignable(prop.value, isBinding);
2358 }
2359 break;
2360
2361 case "ArrayExpression":
2362 node.type = "ArrayPattern";
2363 this.toAssignableList(node.elements, isBinding);
2364 break;
2365
2366 case "AssignmentExpression":
2367 if (node.operator === "=") {
2368 node.type = "AssignmentPattern";
2369 delete node.operator;
2370 } else {
2371 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
2372 }
2373 break;
2374
2375 case "ParenthesizedExpression":
2376 node.expression = this.toAssignable(node.expression, isBinding);
2377 break;
2378
2379 case "MemberExpression":
2380 if (!isBinding) break;
2381
2382 default:
2383 this.raise(node.start, "Assigning to rvalue");
2384 }
2385 }
2386 return node;
2387 };
2388
2389 // Convert list of expression atoms to binding list.
2390
2391 pp$2.toAssignableList = function (exprList, isBinding) {
2392 var end = exprList.length;
2393 if (end) {
2394 var last = exprList[end - 1];
2395 if (last && last.type == "RestElement") {
2396 --end;
2397 } else if (last && last.type == "SpreadElement") {
2398 last.type = "RestElement";
2399 var arg = last.argument;
2400 this.toAssignable(arg, isBinding);
2401 if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
2402 --end;
2403 }
2404 }
2405 for (var i = 0; i < end; i++) {
2406 var elt = exprList[i];
2407 if (elt) this.toAssignable(elt, isBinding);
2408 }
2409 return exprList;
2410 };
2411
2412 // Parses spread element.
2413
2414 pp$2.parseSpread = function (refShorthandDefaultPos) {
2415 var node = this.startNode();
2416 this.next();
2417 node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
2418 return this.finishNode(node, "SpreadElement");
2419 };
2420
2421 pp$2.parseRest = function () {
2422 var node = this.startNode();
2423 this.next();
2424 node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected();
2425 return this.finishNode(node, "RestElement");
2426 };
2427
2428 // Parses lvalue (assignable) atom.
2429
2430 pp$2.parseBindingAtom = function () {
2431 if (this.options.ecmaVersion < 6) return this.parseIdent();
2432 switch (this.type) {
2433 case tt.name:
2434 return this.parseIdent();
2435
2436 case tt.bracketL:
2437 var node = this.startNode();
2438 this.next();
2439 node.elements = this.parseBindingList(tt.bracketR, true, true);
2440 return this.finishNode(node, "ArrayPattern");
2441
2442 case tt.braceL:
2443 return this.parseObj(true);
2444
2445 default:
2446 this.unexpected();
2447 }
2448 };
2449
2450 pp$2.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
2451 var elts = [],
2452 first = true;
2453 while (!this.eat(close)) {
2454 if (first) first = false;else this.expect(tt.comma);
2455 if (allowEmpty && this.type === tt.comma) {
2456 elts.push(null);
2457 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
2458 break;
2459 } else if (this.type === tt.ellipsis) {
2460 var rest = this.parseRest();
2461 this.parseBindingListItem(rest);
2462 elts.push(rest);
2463 this.expect(close);
2464 break;
2465 } else {
2466 var elem = this.parseMaybeDefault(this.start, this.startLoc);
2467 this.parseBindingListItem(elem);
2468 elts.push(elem);
2469 }
2470 }
2471 return elts;
2472 };
2473
2474 pp$2.parseBindingListItem = function (param) {
2475 return param;
2476 };
2477
2478 // Parses assignment pattern around given atom if possible.
2479
2480 pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
2481 left = left || this.parseBindingAtom();
2482 if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left;
2483 var node = this.startNodeAt(startPos, startLoc);
2484 node.left = left;
2485 node.right = this.parseMaybeAssign();
2486 return this.finishNode(node, "AssignmentPattern");
2487 };
2488
2489 // Verify that a node is an lval — something that can be assigned
2490 // to.
2491
2492 pp$2.checkLVal = function (expr, isBinding, checkClashes) {
2493 switch (expr.type) {
2494 case "Identifier":
2495 if (this.strict && (reservedWords$1.strictBind(expr.name) || reservedWords$1.strict(expr.name))) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
2496 if (checkClashes) {
2497 if (has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash in strict mode");
2498 checkClashes[expr.name] = true;
2499 }
2500 break;
2501
2502 case "MemberExpression":
2503 if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
2504 break;
2505
2506 case "ObjectPattern":
2507 for (var i = 0; i < expr.properties.length; i++) {
2508 this.checkLVal(expr.properties[i].value, isBinding, checkClashes);
2509 }break;
2510
2511 case "ArrayPattern":
2512 for (var i = 0; i < expr.elements.length; i++) {
2513 var elem = expr.elements[i];
2514 if (elem) this.checkLVal(elem, isBinding, checkClashes);
2515 }
2516 break;
2517
2518 case "AssignmentPattern":
2519 this.checkLVal(expr.left, isBinding, checkClashes);
2520 break;
2521
2522 case "RestElement":
2523 this.checkLVal(expr.argument, isBinding, checkClashes);
2524 break;
2525
2526 case "ParenthesizedExpression":
2527 this.checkLVal(expr.expression, isBinding, checkClashes);
2528 break;
2529
2530 default:
2531 this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
2532 }
2533 };
2534
2535 var pp$3 = Parser.prototype;
2536
2537 // Check if property name clashes with already added.
2538 // Object/class getters and setters are not allowed to clash —
2539 // either with each other or with an init property — and in
2540 // strict mode, init properties are also not allowed to be repeated.
2541
2542 pp$3.checkPropClash = function (prop, propHash) {
2543 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
2544 var key = prop.key,
2545 name = undefined;
2546 switch (key.type) {
2547 case "Identifier":
2548 name = key.name;break;
2549 case "Literal":
2550 name = String(key.value);break;
2551 default:
2552 return;
2553 }
2554 var kind = prop.kind;
2555 if (this.options.ecmaVersion >= 6) {
2556 if (name === "__proto__" && kind === "init") {
2557 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
2558 propHash.proto = true;
2559 }
2560 return;
2561 }
2562 var other = undefined;
2563 if (has(propHash, name)) {
2564 other = propHash[name];
2565 var isGetSet = kind !== "init";
2566 if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
2567 } else {
2568 other = propHash[name] = {
2569 init: false,
2570 get: false,
2571 set: false
2572 };
2573 }
2574 other[kind] = true;
2575 };
2576
2577 // ### Expression parsing
2578
2579 // These nest, from the most general expression type at the top to
2580 // 'atomic', nondivisible expression types at the bottom. Most of
2581 // the functions will simply let the function(s) below them parse,
2582 // and, *if* the syntactic construct they handle is present, wrap
2583 // the AST node that the inner parser gave them in another node.
2584
2585 // Parse a full expression. The optional arguments are used to
2586 // forbid the `in` operator (in for loops initalization expressions)
2587 // and provide reference for storing '=' operator inside shorthand
2588 // property assignment in contexts where both object expression
2589 // and object pattern might appear (so it's possible to raise
2590 // delayed syntax error at correct position).
2591
2592 pp$3.parseExpression = function (noIn, refShorthandDefaultPos) {
2593 var startPos = this.start,
2594 startLoc = this.startLoc;
2595 var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
2596 if (this.type === tt.comma) {
2597 var node = this.startNodeAt(startPos, startLoc);
2598 node.expressions = [expr];
2599 while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
2600 return this.finishNode(node, "SequenceExpression");
2601 }
2602 return expr;
2603 };
2604
2605 // Parse an assignment expression. This includes applications of
2606 // operators like `+=`.
2607
2608 pp$3.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) {
2609 if (this.type == tt._yield && this.inGenerator) return this.parseYield();
2610
2611 var failOnShorthandAssign = undefined;
2612 if (!refShorthandDefaultPos) {
2613 refShorthandDefaultPos = { start: 0 };
2614 failOnShorthandAssign = true;
2615 } else {
2616 failOnShorthandAssign = false;
2617 }
2618 var startPos = this.start,
2619 startLoc = this.startLoc;
2620 if (this.type == tt.parenL || this.type == tt.name) this.potentialArrowAt = this.start;
2621 var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos);
2622 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
2623 if (this.type.isAssign) {
2624 var node = this.startNodeAt(startPos, startLoc);
2625 node.operator = this.value;
2626 node.left = this.type === tt.eq ? this.toAssignable(left) : left;
2627 refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
2628 this.checkLVal(left);
2629 this.next();
2630 node.right = this.parseMaybeAssign(noIn);
2631 return this.finishNode(node, "AssignmentExpression");
2632 } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
2633 this.unexpected(refShorthandDefaultPos.start);
2634 }
2635 return left;
2636 };
2637
2638 // Parse a ternary conditional (`?:`) operator.
2639
2640 pp$3.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
2641 var startPos = this.start,
2642 startLoc = this.startLoc;
2643 var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
2644 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2645 if (this.eat(tt.question)) {
2646 var node = this.startNodeAt(startPos, startLoc);
2647 node.test = expr;
2648 node.consequent = this.parseMaybeAssign();
2649 this.expect(tt.colon);
2650 node.alternate = this.parseMaybeAssign(noIn);
2651 return this.finishNode(node, "ConditionalExpression");
2652 }
2653 return expr;
2654 };
2655
2656 // Start the precedence parser.
2657
2658 pp$3.parseExprOps = function (noIn, refShorthandDefaultPos) {
2659 var startPos = this.start,
2660 startLoc = this.startLoc;
2661 var expr = this.parseMaybeUnary(refShorthandDefaultPos);
2662 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2663 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
2664 };
2665
2666 // Parse binary operators with the operator precedence parsing
2667 // algorithm. `left` is the left-hand side of the operator.
2668 // `minPrec` provides context that allows the function to stop and
2669 // defer further parser to one of its callers when it encounters an
2670 // operator that has a lower precedence than the set it is parsing.
2671
2672 pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
2673 var prec = this.type.binop;
2674 if (prec != null && (!noIn || this.type !== tt._in)) {
2675 if (prec > minPrec) {
2676 var node = this.startNodeAt(leftStartPos, leftStartLoc);
2677 node.left = left;
2678 node.operator = this.value;
2679 var op = this.type;
2680 this.next();
2681 var startPos = this.start,
2682 startLoc = this.startLoc;
2683 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
2684 this.finishNode(node, op === tt.logicalOR || op === tt.logicalAND ? "LogicalExpression" : "BinaryExpression");
2685 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
2686 }
2687 }
2688 return left;
2689 };
2690
2691 // Parse unary operators, both prefix and postfix.
2692
2693 pp$3.parseMaybeUnary = function (refShorthandDefaultPos) {
2694 if (this.type.prefix) {
2695 var node = this.startNode(),
2696 update = this.type === tt.incDec;
2697 node.operator = this.value;
2698 node.prefix = true;
2699 this.next();
2700 node.argument = this.parseMaybeUnary();
2701 if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
2702 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");
2703 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
2704 }
2705 var startPos = this.start,
2706 startLoc = this.startLoc;
2707 var expr = this.parseExprSubscripts(refShorthandDefaultPos);
2708 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2709 while (this.type.postfix && !this.canInsertSemicolon()) {
2710 var node = this.startNodeAt(startPos, startLoc);
2711 node.operator = this.value;
2712 node.prefix = false;
2713 node.argument = expr;
2714 this.checkLVal(expr);
2715 this.next();
2716 expr = this.finishNode(node, "UpdateExpression");
2717 }
2718 return expr;
2719 };
2720
2721 // Parse call, dot, and `[]`-subscript expressions.
2722
2723 pp$3.parseExprSubscripts = function (refShorthandDefaultPos) {
2724 var startPos = this.start,
2725 startLoc = this.startLoc;
2726 var expr = this.parseExprAtom(refShorthandDefaultPos);
2727 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
2728 return this.parseSubscripts(expr, startPos, startLoc);
2729 };
2730
2731 pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
2732 for (;;) {
2733 if (this.eat(tt.dot)) {
2734 var node = this.startNodeAt(startPos, startLoc);
2735 node.object = base;
2736 node.property = this.parseIdent(true);
2737 node.computed = false;
2738 base = this.finishNode(node, "MemberExpression");
2739 } else if (this.eat(tt.bracketL)) {
2740 var node = this.startNodeAt(startPos, startLoc);
2741 node.object = base;
2742 node.property = this.parseExpression();
2743 node.computed = true;
2744 this.expect(tt.bracketR);
2745 base = this.finishNode(node, "MemberExpression");
2746 } else if (!noCalls && this.eat(tt.parenL)) {
2747 var node = this.startNodeAt(startPos, startLoc);
2748 node.callee = base;
2749 node.arguments = this.parseExprList(tt.parenR, false);
2750 base = this.finishNode(node, "CallExpression");
2751 } else if (this.type === tt.backQuote) {
2752 var node = this.startNodeAt(startPos, startLoc);
2753 node.tag = base;
2754 node.quasi = this.parseTemplate();
2755 base = this.finishNode(node, "TaggedTemplateExpression");
2756 } else {
2757 return base;
2758 }
2759 }
2760 };
2761
2762 // Parse an atomic expression — either a single token that is an
2763 // expression, an expression started by a keyword like `function` or
2764 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
2765 // or `{}`.
2766
2767 pp$3.parseExprAtom = function (refShorthandDefaultPos) {
2768 var node = undefined,
2769 canBeArrow = this.potentialArrowAt == this.start;
2770 switch (this.type) {
2771 case tt._super:
2772 if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
2773 case tt._this:
2774 var type = this.type === tt._this ? "ThisExpression" : "Super";
2775 node = this.startNode();
2776 this.next();
2777 return this.finishNode(node, type);
2778
2779 case tt._yield:
2780 if (this.inGenerator) this.unexpected();
2781
2782 case tt.name:
2783 var startPos = this.start,
2784 startLoc = this.startLoc;
2785 var id = this.parseIdent(this.type !== tt.name);
2786 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]);
2787 return id;
2788
2789 case tt.regexp:
2790 var value = this.value;
2791 node = this.parseLiteral(value.value);
2792 node.regex = { pattern: value.pattern, flags: value.flags };
2793 return node;
2794
2795 case tt.num:case tt.string:
2796 return this.parseLiteral(this.value);
2797
2798 case tt._null:case tt._true:case tt._false:
2799 node = this.startNode();
2800 node.value = this.type === tt._null ? null : this.type === tt._true;
2801 node.raw = this.type.keyword;
2802 this.next();
2803 return this.finishNode(node, "Literal");
2804
2805 case tt.parenL:
2806 return this.parseParenAndDistinguishExpression(canBeArrow);
2807
2808 case tt.bracketL:
2809 node = this.startNode();
2810 this.next();
2811 // check whether this is array comprehension or regular array
2812 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2813 return this.parseComprehension(node, false);
2814 }
2815 node.elements = this.parseExprList(tt.bracketR, true, true, refShorthandDefaultPos);
2816 return this.finishNode(node, "ArrayExpression");
2817
2818 case tt.braceL:
2819 return this.parseObj(false, refShorthandDefaultPos);
2820
2821 case tt._function:
2822 node = this.startNode();
2823 this.next();
2824 return this.parseFunction(node, false);
2825
2826 case tt._class:
2827 return this.parseClass(this.startNode(), false);
2828
2829 case tt._new:
2830 return this.parseNew();
2831
2832 case tt.backQuote:
2833 return this.parseTemplate();
2834
2835 default:
2836 this.unexpected();
2837 }
2838 };
2839
2840 pp$3.parseLiteral = function (value) {
2841 var node = this.startNode();
2842 node.value = value;
2843 node.raw = this.input.slice(this.start, this.end);
2844 this.next();
2845 return this.finishNode(node, "Literal");
2846 };
2847
2848 pp$3.parseParenExpression = function () {
2849 this.expect(tt.parenL);
2850 var val = this.parseExpression();
2851 this.expect(tt.parenR);
2852 return val;
2853 };
2854
2855 pp$3.parseParenAndDistinguishExpression = function (canBeArrow) {
2856 var startPos = this.start,
2857 startLoc = this.startLoc,
2858 val = undefined;
2859 if (this.options.ecmaVersion >= 6) {
2860 this.next();
2861
2862 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2863 return this.parseComprehension(this.startNodeAt(startPos, startLoc), true);
2864 }
2865
2866 var innerStartPos = this.start,
2867 innerStartLoc = this.startLoc;
2868 var exprList = [],
2869 first = true;
2870 var refShorthandDefaultPos = { start: 0 },
2871 spreadStart = undefined,
2872 innerParenStart = undefined;
2873 while (this.type !== tt.parenR) {
2874 first ? first = false : this.expect(tt.comma);
2875 if (this.type === tt.ellipsis) {
2876 spreadStart = this.start;
2877 exprList.push(this.parseParenItem(this.parseRest()));
2878 break;
2879 } else {
2880 if (this.type === tt.parenL && !innerParenStart) {
2881 innerParenStart = this.start;
2882 }
2883 exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem));
2884 }
2885 }
2886 var innerEndPos = this.start,
2887 innerEndLoc = this.startLoc;
2888 this.expect(tt.parenR);
2889
2890 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
2891 if (innerParenStart) this.unexpected(innerParenStart);
2892 return this.parseParenArrowList(startPos, startLoc, exprList);
2893 }
2894
2895 if (!exprList.length) this.unexpected(this.lastTokStart);
2896 if (spreadStart) this.unexpected(spreadStart);
2897 if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
2898
2899 if (exprList.length > 1) {
2900 val = this.startNodeAt(innerStartPos, innerStartLoc);
2901 val.expressions = exprList;
2902 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
2903 } else {
2904 val = exprList[0];
2905 }
2906 } else {
2907 val = this.parseParenExpression();
2908 }
2909
2910 if (this.options.preserveParens) {
2911 var par = this.startNodeAt(startPos, startLoc);
2912 par.expression = val;
2913 return this.finishNode(par, "ParenthesizedExpression");
2914 } else {
2915 return val;
2916 }
2917 };
2918
2919 pp$3.parseParenItem = function (item) {
2920 return item;
2921 };
2922
2923 pp$3.parseParenArrowList = function (startPos, startLoc, exprList) {
2924 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
2925 };
2926
2927 // New's precedence is slightly tricky. It must allow its argument
2928 // to be a `[]` or dot subscript expression, but not a call — at
2929 // least, not without wrapping it in parentheses. Thus, it uses the
2930
2931 var empty$1 = [];
2932
2933 pp$3.parseNew = function () {
2934 var node = this.startNode();
2935 var meta = this.parseIdent(true);
2936 if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
2937 node.meta = meta;
2938 node.property = this.parseIdent(true);
2939 if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
2940 return this.finishNode(node, "MetaProperty");
2941 }
2942 var startPos = this.start,
2943 startLoc = this.startLoc;
2944 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
2945 if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false);else node.arguments = empty$1;
2946 return this.finishNode(node, "NewExpression");
2947 };
2948
2949 // Parse template expression.
2950
2951 pp$3.parseTemplateElement = function () {
2952 var elem = this.startNode();
2953 elem.value = {
2954 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
2955 cooked: this.value
2956 };
2957 this.next();
2958 elem.tail = this.type === tt.backQuote;
2959 return this.finishNode(elem, "TemplateElement");
2960 };
2961
2962 pp$3.parseTemplate = function () {
2963 var node = this.startNode();
2964 this.next();
2965 node.expressions = [];
2966 var curElt = this.parseTemplateElement();
2967 node.quasis = [curElt];
2968 while (!curElt.tail) {
2969 this.expect(tt.dollarBraceL);
2970 node.expressions.push(this.parseExpression());
2971 this.expect(tt.braceR);
2972 node.quasis.push(curElt = this.parseTemplateElement());
2973 }
2974 this.next();
2975 return this.finishNode(node, "TemplateLiteral");
2976 };
2977
2978 // Parse an object literal or binding pattern.
2979
2980 pp$3.parseObj = function (isPattern, refShorthandDefaultPos) {
2981 var node = this.startNode(),
2982 first = true,
2983 propHash = {};
2984 node.properties = [];
2985 this.next();
2986 while (!this.eat(tt.braceR)) {
2987 if (!first) {
2988 this.expect(tt.comma);
2989 if (this.afterTrailingComma(tt.braceR)) break;
2990 } else first = false;
2991
2992 var prop = this.startNode(),
2993 isGenerator = undefined,
2994 startPos = undefined,
2995 startLoc = undefined;
2996 if (this.options.ecmaVersion >= 6) {
2997 prop.method = false;
2998 prop.shorthand = false;
2999 if (isPattern || refShorthandDefaultPos) {
3000 startPos = this.start;
3001 startLoc = this.startLoc;
3002 }
3003 if (!isPattern) isGenerator = this.eat(tt.star);
3004 }
3005 this.parsePropertyName(prop);
3006 this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos);
3007 this.checkPropClash(prop, propHash);
3008 node.properties.push(this.finishNode(prop, "Property"));
3009 }
3010 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
3011 };
3012
3013 pp$3.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos) {
3014 if (this.eat(tt.colon)) {
3015 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
3016 prop.kind = "init";
3017 } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
3018 if (isPattern) this.unexpected();
3019 prop.kind = "init";
3020 prop.method = true;
3021 prop.value = this.parseMethod(isGenerator);
3022 } 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)) {
3023 if (isGenerator || isPattern) this.unexpected();
3024 prop.kind = prop.key.name;
3025 this.parsePropertyName(prop);
3026 prop.value = this.parseMethod(false);
3027 var paramCount = prop.kind === "get" ? 0 : 1;
3028 if (prop.value.params.length !== paramCount) {
3029 var start = prop.value.start;
3030 if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
3031 }
3032 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
3033 prop.kind = "init";
3034 if (isPattern) {
3035 if (this.isKeyword(prop.key.name) || this.strict && (reservedWords$1.strictBind(prop.key.name) || reservedWords$1.strict(prop.key.name)) || !this.options.allowReserved && this.isReservedWord(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
3036 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3037 } else if (this.type === tt.eq && refShorthandDefaultPos) {
3038 if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start;
3039 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3040 } else {
3041 prop.value = prop.key;
3042 }
3043 prop.shorthand = true;
3044 } else this.unexpected();
3045 };
3046
3047 pp$3.parsePropertyName = function (prop) {
3048 if (this.options.ecmaVersion >= 6) {
3049 if (this.eat(tt.bracketL)) {
3050 prop.computed = true;
3051 prop.key = this.parseMaybeAssign();
3052 this.expect(tt.bracketR);
3053 return prop.key;
3054 } else {
3055 prop.computed = false;
3056 }
3057 }
3058 return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true);
3059 };
3060
3061 // Initialize empty function node.
3062
3063 pp$3.initFunction = function (node) {
3064 node.id = null;
3065 if (this.options.ecmaVersion >= 6) {
3066 node.generator = false;
3067 node.expression = false;
3068 }
3069 };
3070
3071 // Parse object or class method.
3072
3073 pp$3.parseMethod = function (isGenerator) {
3074 var node = this.startNode();
3075 this.initFunction(node);
3076 this.expect(tt.parenL);
3077 node.params = this.parseBindingList(tt.parenR, false, false);
3078 var allowExpressionBody = undefined;
3079 if (this.options.ecmaVersion >= 6) {
3080 node.generator = isGenerator;
3081 }
3082 this.parseFunctionBody(node, false);
3083 return this.finishNode(node, "FunctionExpression");
3084 };
3085
3086 // Parse arrow function expression with given parameters.
3087
3088 pp$3.parseArrowExpression = function (node, params) {
3089 this.initFunction(node);
3090 node.params = this.toAssignableList(params, true);
3091 this.parseFunctionBody(node, true);
3092 return this.finishNode(node, "ArrowFunctionExpression");
3093 };
3094
3095 // Parse function body and check parameters.
3096
3097 pp$3.parseFunctionBody = function (node, allowExpression) {
3098 var isExpression = allowExpression && this.type !== tt.braceL;
3099
3100 if (isExpression) {
3101 node.body = this.parseMaybeAssign();
3102 node.expression = true;
3103 } else {
3104 // Start a new scope with regard to labels and the `inFunction`
3105 // flag (restore them to their old value afterwards).
3106 var oldInFunc = this.inFunction,
3107 oldInGen = this.inGenerator,
3108 oldLabels = this.labels;
3109 this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
3110 node.body = this.parseBlock(true);
3111 node.expression = false;
3112 this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
3113 }
3114
3115 // If this is a strict mode function, verify that argument names
3116 // are not repeated, and it does not try to bind the words `eval`
3117 // or `arguments`.
3118 if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
3119 var nameHash = {},
3120 oldStrict = this.strict;
3121 this.strict = true;
3122 if (node.id) this.checkLVal(node.id, true);
3123 for (var i = 0; i < node.params.length; i++) {
3124 this.checkLVal(node.params[i], true, nameHash);
3125 }this.strict = oldStrict;
3126 }
3127 };
3128
3129 // Parses a comma-separated list of expressions, and returns them as
3130 // an array. `close` is the token type that ends the list, and
3131 // `allowEmpty` can be turned on to allow subsequent commas with
3132 // nothing in between them to be parsed as `null` (which is needed
3133 // for array literals).
3134
3135 pp$3.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
3136 var elts = [],
3137 first = true;
3138 while (!this.eat(close)) {
3139 if (!first) {
3140 this.expect(tt.comma);
3141 if (allowTrailingComma && this.afterTrailingComma(close)) break;
3142 } else first = false;
3143
3144 var elt = undefined;
3145 if (allowEmpty && this.type === tt.comma) elt = null;else if (this.type === tt.ellipsis) elt = this.parseSpread(refShorthandDefaultPos);else elt = this.parseMaybeAssign(false, refShorthandDefaultPos);
3146 elts.push(elt);
3147 }
3148 return elts;
3149 };
3150
3151 // Parse the next token as an identifier. If `liberal` is true (used
3152 // when parsing properties), it will also convert keywords into
3153 // identifiers.
3154
3155 pp$3.parseIdent = function (liberal) {
3156 var node = this.startNode();
3157 if (liberal && this.options.allowReserved == "never") liberal = false;
3158 if (this.type === tt.name) {
3159 if (!liberal && (!this.options.allowReserved && this.isReservedWord(this.value) || this.strict && reservedWords$1.strict(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");
3160 node.name = this.value;
3161 } else if (liberal && this.type.keyword) {
3162 node.name = this.type.keyword;
3163 } else {
3164 this.unexpected();
3165 }
3166 this.next();
3167 return this.finishNode(node, "Identifier");
3168 };
3169
3170 // Parses yield expression inside generator.
3171
3172 pp$3.parseYield = function () {
3173 var node = this.startNode();
3174 this.next();
3175 if (this.type == tt.semi || this.canInsertSemicolon() || this.type != tt.star && !this.type.startsExpr) {
3176 node.delegate = false;
3177 node.argument = null;
3178 } else {
3179 node.delegate = this.eat(tt.star);
3180 node.argument = this.parseMaybeAssign();
3181 }
3182 return this.finishNode(node, "YieldExpression");
3183 };
3184
3185 // Parses array and generator comprehensions.
3186
3187 pp$3.parseComprehension = function (node, isGenerator) {
3188 node.blocks = [];
3189 while (this.type === tt._for) {
3190 var block = this.startNode();
3191 this.next();
3192 this.expect(tt.parenL);
3193 block.left = this.parseBindingAtom();
3194 this.checkLVal(block.left, true);
3195 this.expectContextual("of");
3196 block.right = this.parseExpression();
3197 this.expect(tt.parenR);
3198 node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
3199 }
3200 node.filter = this.eat(tt._if) ? this.parseParenExpression() : null;
3201 node.body = this.parseExpression();
3202 this.expect(isGenerator ? tt.parenR : tt.bracketR);
3203 node.generator = isGenerator;
3204 return this.finishNode(node, "ComprehensionExpression");
3205 };
3206
3207 var pp$4 = Parser.prototype;
3208
3209 // This function is used to raise exceptions on parse errors. It
3210 // takes an offset integer (into the current `input`) to indicate
3211 // the location of the error, attaches the position to the end
3212 // of the error message, and then raises a `SyntaxError` with that
3213 // message.
3214
3215 pp$4.raise = function (pos, message) {
3216 var loc = getLineInfo(this.input, pos);
3217 message += " (" + loc.line + ":" + loc.column + ")";
3218 var err = new SyntaxError(message);
3219 err.pos = pos;err.loc = loc;err.raisedAt = this.pos;
3220 throw err;
3221 };
3222
3223 pp$4.curPosition = function () {
3224 if (this.options.locations) {
3225 return new Position(this.curLine, this.pos - this.lineStart);
3226 }
3227 };
3228
3229 var Node = function Node(parser, pos, loc) {
3230 babelHelpers.classCallCheck(this, Node);
3231
3232 this.type = "";
3233 this.start = pos;
3234 this.end = 0;
3235 if (parser.options.locations) this.loc = new SourceLocation(parser, loc);
3236 if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
3237 if (parser.options.ranges) this.range = [pos, 0];
3238 }
3239
3240 // Start an AST node, attaching a start offset.
3241
3242 ;
3243
3244 var pp$5 = Parser.prototype;
3245
3246 pp$5.startNode = function () {
3247 return new Node(this, this.start, this.startLoc);
3248 };
3249
3250 pp$5.startNodeAt = function (pos, loc) {
3251 return new Node(this, pos, loc);
3252 };
3253
3254 // Finish an AST node, adding `type` and `end` properties.
3255
3256 function finishNodeAt(node, type, pos, loc) {
3257 node.type = type;
3258 node.end = pos;
3259 if (this.options.locations) node.loc.end = loc;
3260 if (this.options.ranges) node.range[1] = pos;
3261 return node;
3262 }
3263
3264 pp$5.finishNode = function (node, type) {
3265 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
3266 };
3267
3268 // Finish node at given position
3269
3270 pp$5.finishNodeAt = function (node, type, pos, loc) {
3271 return finishNodeAt.call(this, node, type, pos, loc);
3272 };
3273
3274 var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
3275 babelHelpers.classCallCheck(this, TokContext);
3276
3277 this.token = token;
3278 this.isExpr = !!isExpr;
3279 this.preserveSpace = !!preserveSpace;
3280 this.override = override;
3281 };
3282
3283 var types = {
3284 b_stat: new TokContext("{", false),
3285 b_expr: new TokContext("{", true),
3286 b_tmpl: new TokContext("${", true),
3287 p_stat: new TokContext("(", false),
3288 p_expr: new TokContext("(", true),
3289 q_tmpl: new TokContext("`", true, true, function (p) {
3290 return p.readTmplToken();
3291 }),
3292 f_expr: new TokContext("function", true)
3293 };
3294
3295 var pp$6 = Parser.prototype;
3296
3297 pp$6.initialContext = function () {
3298 return [types.b_stat];
3299 };
3300
3301 pp$6.braceIsBlock = function (prevType) {
3302 if (prevType === tt.colon) {
3303 var _parent = this.curContext();
3304 if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr;
3305 }
3306 if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
3307 if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true;
3308 if (prevType == tt.braceL) return this.curContext() === types.b_stat;
3309 return !this.exprAllowed;
3310 };
3311
3312 pp$6.updateContext = function (prevType) {
3313 var update = undefined,
3314 type = this.type;
3315 if (type.keyword && prevType == tt.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
3316 };
3317
3318 // Token-specific context update code
3319
3320 tt.parenR.updateContext = tt.braceR.updateContext = function () {
3321 if (this.context.length == 1) {
3322 this.exprAllowed = true;
3323 return;
3324 }
3325 var out = this.context.pop();
3326 if (out === types.b_stat && this.curContext() === types.f_expr) {
3327 this.context.pop();
3328 this.exprAllowed = false;
3329 } else if (out === types.b_tmpl) {
3330 this.exprAllowed = true;
3331 } else {
3332 this.exprAllowed = !out.isExpr;
3333 }
3334 };
3335
3336 tt.braceL.updateContext = function (prevType) {
3337 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
3338 this.exprAllowed = true;
3339 };
3340
3341 tt.dollarBraceL.updateContext = function () {
3342 this.context.push(types.b_tmpl);
3343 this.exprAllowed = true;
3344 };
3345
3346 tt.parenL.updateContext = function (prevType) {
3347 var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
3348 this.context.push(statementParens ? types.p_stat : types.p_expr);
3349 this.exprAllowed = true;
3350 };
3351
3352 tt.incDec.updateContext = function () {
3353 // tokExprAllowed stays unchanged
3354 };
3355
3356 tt._function.updateContext = function () {
3357 if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
3358 this.exprAllowed = false;
3359 };
3360
3361 tt.backQuote.updateContext = function () {
3362 if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
3363 this.exprAllowed = false;
3364 };
3365
3366 // Object type used to represent tokens. Note that normally, tokens
3367 // simply exist as properties on the parser object. This is only
3368 // used for the onToken callback and the external tokenizer.
3369
3370 var Token = function Token(p) {
3371 babelHelpers.classCallCheck(this, Token);
3372
3373 this.type = p.type;
3374 this.value = p.value;
3375 this.start = p.start;
3376 this.end = p.end;
3377 if (p.options.locations) this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
3378 if (p.options.ranges) this.range = [p.start, p.end];
3379 }
3380
3381 // ## Tokenizer
3382
3383 ;
3384
3385 var pp$7 = Parser.prototype;
3386
3387 // Are we running under Rhino?
3388 var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
3389
3390 // Move to the next token
3391
3392 pp$7.next = function () {
3393 if (this.options.onToken) this.options.onToken(new Token(this));
3394
3395 this.lastTokEnd = this.end;
3396 this.lastTokStart = this.start;
3397 this.lastTokEndLoc = this.endLoc;
3398 this.lastTokStartLoc = this.startLoc;
3399 this.nextToken();
3400 };
3401
3402 pp$7.getToken = function () {
3403 this.next();
3404 return new Token(this);
3405 };
3406
3407 // If we're in an ES6 environment, make parsers iterable
3408 if (typeof Symbol !== "undefined") pp$7[Symbol.iterator] = function () {
3409 var self = this;
3410 return { next: function () {
3411 var token = self.getToken();
3412 return {
3413 done: token.type === tt.eof,
3414 value: token
3415 };
3416 } };
3417 };
3418
3419 // Toggle strict mode. Re-reads the next number or string to please
3420 // pedantic tests (`"use strict"; 010;` should fail).
3421
3422 pp$7.setStrict = function (strict) {
3423 this.strict = strict;
3424 if (this.type !== tt.num && this.type !== tt.string) return;
3425 this.pos = this.start;
3426 if (this.options.locations) {
3427 while (this.pos < this.lineStart) {
3428 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
3429 --this.curLine;
3430 }
3431 }
3432 this.nextToken();
3433 };
3434
3435 pp$7.curContext = function () {
3436 return this.context[this.context.length - 1];
3437 };
3438
3439 // Read a single token, updating the parser object's token-related
3440 // properties.
3441
3442 pp$7.nextToken = function () {
3443 var curContext = this.curContext();
3444 if (!curContext || !curContext.preserveSpace) this.skipSpace();
3445
3446 this.start = this.pos;
3447 if (this.options.locations) this.startLoc = this.curPosition();
3448 if (this.pos >= this.input.length) return this.finishToken(tt.eof);
3449
3450 if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
3451 };
3452
3453 pp$7.readToken = function (code) {
3454 // Identifier or keyword. '\uXXXX' sequences are allowed in
3455 // identifiers, so '\' also dispatches to that.
3456 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
3457
3458 return this.getTokenFromCode(code);
3459 };
3460
3461 pp$7.fullCharCodeAtPos = function () {
3462 var code = this.input.charCodeAt(this.pos);
3463 if (code <= 0xd7ff || code >= 0xe000) return code;
3464 var next = this.input.charCodeAt(this.pos + 1);
3465 return (code << 10) + next - 0x35fdc00;
3466 };
3467
3468 pp$7.skipBlockComment = function () {
3469 var startLoc = this.options.onComment && this.curPosition();
3470 var start = this.pos,
3471 end = this.input.indexOf("*/", this.pos += 2);
3472 if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
3473 this.pos = end + 2;
3474 if (this.options.locations) {
3475 lineBreakG.lastIndex = start;
3476 var match = undefined;
3477 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
3478 ++this.curLine;
3479 this.lineStart = match.index + match[0].length;
3480 }
3481 }
3482 if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
3483 };
3484
3485 pp$7.skipLineComment = function (startSkip) {
3486 var start = this.pos;
3487 var startLoc = this.options.onComment && this.curPosition();
3488 var ch = this.input.charCodeAt(this.pos += startSkip);
3489 while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
3490 ++this.pos;
3491 ch = this.input.charCodeAt(this.pos);
3492 }
3493 if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
3494 };
3495
3496 // Called at the start of the parse and after every token. Skips
3497 // whitespace and comments, and.
3498
3499 pp$7.skipSpace = function () {
3500 loop: while (this.pos < this.input.length) {
3501 var ch = this.input.charCodeAt(this.pos);
3502 switch (ch) {
3503 case 32:case 160:
3504 // ' '
3505 ++this.pos;
3506 break;
3507 case 13:
3508 if (this.input.charCodeAt(this.pos + 1) === 10) {
3509 ++this.pos;
3510 }
3511 case 10:case 8232:case 8233:
3512 ++this.pos;
3513 if (this.options.locations) {
3514 ++this.curLine;
3515 this.lineStart = this.pos;
3516 }
3517 break;
3518 case 47:
3519 // '/'
3520 switch (this.input.charCodeAt(this.pos + 1)) {
3521 case 42:
3522 // '*'
3523 this.skipBlockComment();
3524 break;
3525 case 47:
3526 this.skipLineComment(2);
3527 break;
3528 default:
3529 break loop;
3530 }
3531 break;
3532 default:
3533 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
3534 ++this.pos;
3535 } else {
3536 break loop;
3537 }
3538 }
3539 }
3540 };
3541
3542 // Called at the end of every token. Sets `end`, `val`, and
3543 // maintains `context` and `exprAllowed`, and skips the space after
3544 // the token, so that the next one's `start` will point at the
3545 // right position.
3546
3547 pp$7.finishToken = function (type, val) {
3548 this.end = this.pos;
3549 if (this.options.locations) this.endLoc = this.curPosition();
3550 var prevType = this.type;
3551 this.type = type;
3552 this.value = val;
3553
3554 this.updateContext(prevType);
3555 };
3556
3557 // ### Token reading
3558
3559 // This is the function that is called to fetch the next token. It
3560 // is somewhat obscure, because it works in character codes rather
3561 // than characters, and because operator parsing has been inlined
3562 // into it.
3563 //
3564 // All in the name of speed.
3565 //
3566 pp$7.readToken_dot = function () {
3567 var next = this.input.charCodeAt(this.pos + 1);
3568 if (next >= 48 && next <= 57) return this.readNumber(true);
3569 var next2 = this.input.charCodeAt(this.pos + 2);
3570 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
3571 // 46 = dot '.'
3572 this.pos += 3;
3573 return this.finishToken(tt.ellipsis);
3574 } else {
3575 ++this.pos;
3576 return this.finishToken(tt.dot);
3577 }
3578 };
3579
3580 pp$7.readToken_slash = function () {
3581 // '/'
3582 var next = this.input.charCodeAt(this.pos + 1);
3583 if (this.exprAllowed) {
3584 ++this.pos;return this.readRegexp();
3585 }
3586 if (next === 61) return this.finishOp(tt.assign, 2);
3587 return this.finishOp(tt.slash, 1);
3588 };
3589
3590 pp$7.readToken_mult_modulo = function (code) {
3591 // '%*'
3592 var next = this.input.charCodeAt(this.pos + 1);
3593 if (next === 61) return this.finishOp(tt.assign, 2);
3594 return this.finishOp(code === 42 ? tt.star : tt.modulo, 1);
3595 };
3596
3597 pp$7.readToken_pipe_amp = function (code) {
3598 // '|&'
3599 var next = this.input.charCodeAt(this.pos + 1);
3600 if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2);
3601 if (next === 61) return this.finishOp(tt.assign, 2);
3602 return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1);
3603 };
3604
3605 pp$7.readToken_caret = function () {
3606 // '^'
3607 var next = this.input.charCodeAt(this.pos + 1);
3608 if (next === 61) return this.finishOp(tt.assign, 2);
3609 return this.finishOp(tt.bitwiseXOR, 1);
3610 };
3611
3612 pp$7.readToken_plus_min = function (code) {
3613 // '+-'
3614 var next = this.input.charCodeAt(this.pos + 1);
3615 if (next === code) {
3616 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
3617 // A `-->` line comment
3618 this.skipLineComment(3);
3619 this.skipSpace();
3620 return this.nextToken();
3621 }
3622 return this.finishOp(tt.incDec, 2);
3623 }
3624 if (next === 61) return this.finishOp(tt.assign, 2);
3625 return this.finishOp(tt.plusMin, 1);
3626 };
3627
3628 pp$7.readToken_lt_gt = function (code) {
3629 // '<>'
3630 var next = this.input.charCodeAt(this.pos + 1);
3631 var size = 1;
3632 if (next === code) {
3633 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
3634 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1);
3635 return this.finishOp(tt.bitShift, size);
3636 }
3637 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
3638 if (this.inModule) this.unexpected();
3639 // `<!--`, an XML-style comment that should be interpreted as a line comment
3640 this.skipLineComment(4);
3641 this.skipSpace();
3642 return this.nextToken();
3643 }
3644 if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
3645 return this.finishOp(tt.relational, size);
3646 };
3647
3648 pp$7.readToken_eq_excl = function (code) {
3649 // '=!'
3650 var next = this.input.charCodeAt(this.pos + 1);
3651 if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
3652 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
3653 // '=>'
3654 this.pos += 2;
3655 return this.finishToken(tt.arrow);
3656 }
3657 return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1);
3658 };
3659
3660 pp$7.getTokenFromCode = function (code) {
3661 switch (code) {
3662 // The interpretation of a dot depends on whether it is followed
3663 // by a digit or another two dots.
3664 case 46:
3665 // '.'
3666 return this.readToken_dot();
3667
3668 // Punctuation tokens.
3669 case 40:
3670 ++this.pos;return this.finishToken(tt.parenL);
3671 case 41:
3672 ++this.pos;return this.finishToken(tt.parenR);
3673 case 59:
3674 ++this.pos;return this.finishToken(tt.semi);
3675 case 44:
3676 ++this.pos;return this.finishToken(tt.comma);
3677 case 91:
3678 ++this.pos;return this.finishToken(tt.bracketL);
3679 case 93:
3680 ++this.pos;return this.finishToken(tt.bracketR);
3681 case 123:
3682 ++this.pos;return this.finishToken(tt.braceL);
3683 case 125:
3684 ++this.pos;return this.finishToken(tt.braceR);
3685 case 58:
3686 ++this.pos;return this.finishToken(tt.colon);
3687 case 63:
3688 ++this.pos;return this.finishToken(tt.question);
3689
3690 case 96:
3691 // '`'
3692 if (this.options.ecmaVersion < 6) break;
3693 ++this.pos;
3694 return this.finishToken(tt.backQuote);
3695
3696 case 48:
3697 // '0'
3698 var next = this.input.charCodeAt(this.pos + 1);
3699 if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
3700 if (this.options.ecmaVersion >= 6) {
3701 if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
3702 if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
3703 }
3704 // Anything else beginning with a digit is an integer, octal
3705 // number, or float.
3706 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
3707 // 1-9
3708 return this.readNumber(false);
3709
3710 // Quotes produce strings.
3711 case 34:case 39:
3712 // '"', "'"
3713 return this.readString(code);
3714
3715 // Operators are parsed inline in tiny state machines. '=' (61) is
3716 // often referred to. `finishOp` simply skips the amount of
3717 // characters it is given as second argument, and returns a token
3718 // of the type given by its first argument.
3719
3720 case 47:
3721 // '/'
3722 return this.readToken_slash();
3723
3724 case 37:case 42:
3725 // '%*'
3726 return this.readToken_mult_modulo(code);
3727
3728 case 124:case 38:
3729 // '|&'
3730 return this.readToken_pipe_amp(code);
3731
3732 case 94:
3733 // '^'
3734 return this.readToken_caret();
3735
3736 case 43:case 45:
3737 // '+-'
3738 return this.readToken_plus_min(code);
3739
3740 case 60:case 62:
3741 // '<>'
3742 return this.readToken_lt_gt(code);
3743
3744 case 61:case 33:
3745 // '=!'
3746 return this.readToken_eq_excl(code);
3747
3748 case 126:
3749 // '~'
3750 return this.finishOp(tt.prefix, 1);
3751 }
3752
3753 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
3754 };
3755
3756 pp$7.finishOp = function (type, size) {
3757 var str = this.input.slice(this.pos, this.pos + size);
3758 this.pos += size;
3759 return this.finishToken(type, str);
3760 };
3761
3762 // Parse a regular expression. Some context-awareness is necessary,
3763 // since a '/' inside a '[]' set does not end the expression.
3764
3765 function tryCreateRegexp(src, flags, throwErrorAt) {
3766 try {
3767 return new RegExp(src, flags);
3768 } catch (e) {
3769 if (throwErrorAt !== undefined) {
3770 if (e instanceof SyntaxError) this.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
3771 this.raise(e);
3772 }
3773 }
3774 }
3775
3776 var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
3777
3778 pp$7.readRegexp = function () {
3779 var _this = this;
3780
3781 var escaped = undefined,
3782 inClass = undefined,
3783 start = this.pos;
3784 for (;;) {
3785 if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
3786 var ch = this.input.charAt(this.pos);
3787 if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
3788 if (!escaped) {
3789 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;
3790 escaped = ch === "\\";
3791 } else escaped = false;
3792 ++this.pos;
3793 }
3794 var content = this.input.slice(start, this.pos);
3795 ++this.pos;
3796 // Need to use `readWord1` because '\uXXXX' sequences are allowed
3797 // here (don't ask).
3798 var mods = this.readWord1();
3799 var tmp = content;
3800 if (mods) {
3801 var validFlags = /^[gmsiy]*$/;
3802 if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
3803 if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
3804 if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
3805 // Replace each astral symbol and every Unicode escape sequence that
3806 // possibly represents an astral symbol or a paired surrogate with a
3807 // single ASCII symbol to avoid throwing on regular expressions that
3808 // are only valid in combination with the `/u` flag.
3809 // Note: replacing with the ASCII symbol `x` might cause false
3810 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
3811 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
3812 // be replaced by `[x-b]` which throws an error.
3813 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (match, code, offset) {
3814 code = Number("0x" + code);
3815 if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
3816 return "x";
3817 });
3818 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
3819 }
3820 }
3821 // Detect invalid regular expressions.
3822 var value = null;
3823 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
3824 // so don't do detection if we are running under Rhino
3825 if (!isRhino) {
3826 tryCreateRegexp(tmp, undefined, start);
3827 // Get a regular expression object for this pattern-flag pair, or `null` in
3828 // case the current environment doesn't support the flags it uses.
3829 value = tryCreateRegexp(content, mods);
3830 }
3831 return this.finishToken(tt.regexp, { pattern: content, flags: mods, value: value });
3832 };
3833
3834 // Read an integer in the given radix. Return null if zero digits
3835 // were read, the integer value otherwise. When `len` is given, this
3836 // will return `null` unless the integer has exactly `len` digits.
3837
3838 pp$7.readInt = function (radix, len) {
3839 var start = this.pos,
3840 total = 0;
3841 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
3842 var code = this.input.charCodeAt(this.pos),
3843 val = undefined;
3844 if (code >= 97) val = code - 97 + 10; // a
3845 else if (code >= 65) val = code - 65 + 10; // A
3846 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
3847 else val = Infinity;
3848 if (val >= radix) break;
3849 ++this.pos;
3850 total = total * radix + val;
3851 }
3852 if (this.pos === start || len != null && this.pos - start !== len) return null;
3853
3854 return total;
3855 };
3856
3857 pp$7.readRadixNumber = function (radix) {
3858 this.pos += 2; // 0x
3859 var val = this.readInt(radix);
3860 if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
3861 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3862 return this.finishToken(tt.num, val);
3863 };
3864
3865 // Read an integer, octal integer, or floating-point number.
3866
3867 pp$7.readNumber = function (startsWithDot) {
3868 var start = this.pos,
3869 isFloat = false,
3870 octal = this.input.charCodeAt(this.pos) === 48;
3871 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
3872 var next = this.input.charCodeAt(this.pos);
3873 if (next === 46) {
3874 // '.'
3875 ++this.pos;
3876 this.readInt(10);
3877 isFloat = true;
3878 next = this.input.charCodeAt(this.pos);
3879 }
3880 if (next === 69 || next === 101) {
3881 // 'eE'
3882 next = this.input.charCodeAt(++this.pos);
3883 if (next === 43 || next === 45) ++this.pos; // '+-'
3884 if (this.readInt(10) === null) this.raise(start, "Invalid number");
3885 isFloat = true;
3886 }
3887 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3888
3889 var str = this.input.slice(start, this.pos),
3890 val = undefined;
3891 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);
3892 return this.finishToken(tt.num, val);
3893 };
3894
3895 // Read a string value, interpreting backslash-escapes.
3896
3897 pp$7.readCodePoint = function () {
3898 var ch = this.input.charCodeAt(this.pos),
3899 code = undefined;
3900
3901 if (ch === 123) {
3902 if (this.options.ecmaVersion < 6) this.unexpected();
3903 var codePos = ++this.pos;
3904 code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
3905 ++this.pos;
3906 if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
3907 } else {
3908 code = this.readHexChar(4);
3909 }
3910 return code;
3911 };
3912
3913 function codePointToString(code) {
3914 // UTF-16 Decoding
3915 if (code <= 0xFFFF) return String.fromCharCode(code);
3916 code -= 0x10000;
3917 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
3918 }
3919
3920 pp$7.readString = function (quote) {
3921 var out = "",
3922 chunkStart = ++this.pos;
3923 for (;;) {
3924 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
3925 var ch = this.input.charCodeAt(this.pos);
3926 if (ch === quote) break;
3927 if (ch === 92) {
3928 // '\'
3929 out += this.input.slice(chunkStart, this.pos);
3930 out += this.readEscapedChar(false);
3931 chunkStart = this.pos;
3932 } else {
3933 if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
3934 ++this.pos;
3935 }
3936 }
3937 out += this.input.slice(chunkStart, this.pos++);
3938 return this.finishToken(tt.string, out);
3939 };
3940
3941 // Reads template string tokens.
3942
3943 pp$7.readTmplToken = function () {
3944 var out = "",
3945 chunkStart = this.pos;
3946 for (;;) {
3947 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
3948 var ch = this.input.charCodeAt(this.pos);
3949 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
3950 // '`', '${'
3951 if (this.pos === this.start && this.type === tt.template) {
3952 if (ch === 36) {
3953 this.pos += 2;
3954 return this.finishToken(tt.dollarBraceL);
3955 } else {
3956 ++this.pos;
3957 return this.finishToken(tt.backQuote);
3958 }
3959 }
3960 out += this.input.slice(chunkStart, this.pos);
3961 return this.finishToken(tt.template, out);
3962 }
3963 if (ch === 92) {
3964 // '\'
3965 out += this.input.slice(chunkStart, this.pos);
3966 out += this.readEscapedChar(true);
3967 chunkStart = this.pos;
3968 } else if (isNewLine(ch)) {
3969 out += this.input.slice(chunkStart, this.pos);
3970 ++this.pos;
3971 switch (ch) {
3972 case 13:
3973 if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
3974 case 10:
3975 out += "\n";
3976 break;
3977 default:
3978 out += String.fromCharCode(ch);
3979 break;
3980 }
3981 if (this.options.locations) {
3982 ++this.curLine;
3983 this.lineStart = this.pos;
3984 }
3985 chunkStart = this.pos;
3986 } else {
3987 ++this.pos;
3988 }
3989 }
3990 };
3991
3992 // Used to read escaped characters
3993
3994 pp$7.readEscapedChar = function (inTemplate) {
3995 var ch = this.input.charCodeAt(++this.pos);
3996 ++this.pos;
3997 switch (ch) {
3998 case 110:
3999 return "\n"; // 'n' -> '\n'
4000 case 114:
4001 return "\r"; // 'r' -> '\r'
4002 case 120:
4003 return String.fromCharCode(this.readHexChar(2)); // 'x'
4004 case 117:
4005 return codePointToString(this.readCodePoint()); // 'u'
4006 case 116:
4007 return "\t"; // 't' -> '\t'
4008 case 98:
4009 return "\b"; // 'b' -> '\b'
4010 case 118:
4011 return "\u000b"; // 'v' -> '\u000b'
4012 case 102:
4013 return "\f"; // 'f' -> '\f'
4014 case 13:
4015 if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
4016 case 10:
4017 // ' \n'
4018 if (this.options.locations) {
4019 this.lineStart = this.pos;++this.curLine;
4020 }
4021 return "";
4022 default:
4023 if (ch >= 48 && ch <= 55) {
4024 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
4025 var octal = parseInt(octalStr, 8);
4026 if (octal > 255) {
4027 octalStr = octalStr.slice(0, -1);
4028 octal = parseInt(octalStr, 8);
4029 }
4030 if (octal > 0 && (this.strict || inTemplate)) {
4031 this.raise(this.pos - 2, "Octal literal in strict mode");
4032 }
4033 this.pos += octalStr.length - 1;
4034 return String.fromCharCode(octal);
4035 }
4036 return String.fromCharCode(ch);
4037 }
4038 };
4039
4040 // Used to read character escape sequences ('\x', '\u', '\U').
4041
4042 pp$7.readHexChar = function (len) {
4043 var codePos = this.pos;
4044 var n = this.readInt(16, len);
4045 if (n === null) this.raise(codePos, "Bad character escape sequence");
4046 return n;
4047 };
4048
4049 // Read an identifier, and return it as a string. Sets `this.containsEsc`
4050 // to whether the word contained a '\u' escape.
4051 //
4052 // Incrementally adds only escaped chars, adding other chunks as-is
4053 // as a micro-optimization.
4054
4055 pp$7.readWord1 = function () {
4056 this.containsEsc = false;
4057 var word = "",
4058 first = true,
4059 chunkStart = this.pos;
4060 var astral = this.options.ecmaVersion >= 6;
4061 while (this.pos < this.input.length) {
4062 var ch = this.fullCharCodeAtPos();
4063 if (isIdentifierChar(ch, astral)) {
4064 this.pos += ch <= 0xffff ? 1 : 2;
4065 } else if (ch === 92) {
4066 // "\"
4067 this.containsEsc = true;
4068 word += this.input.slice(chunkStart, this.pos);
4069 var escStart = this.pos;
4070 if (this.input.charCodeAt(++this.pos) != 117) // "u"
4071 this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
4072 ++this.pos;
4073 var esc = this.readCodePoint();
4074 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
4075 word += codePointToString(esc);
4076 chunkStart = this.pos;
4077 } else {
4078 break;
4079 }
4080 first = false;
4081 }
4082 return word + this.input.slice(chunkStart, this.pos);
4083 };
4084
4085 // Read an identifier or keyword token. Will check for reserved
4086 // words when necessary.
4087
4088 pp$7.readWord = function () {
4089 var word = this.readWord1();
4090 var type = tt.name;
4091 if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.isKeyword(word)) type = keywordTypes[word];
4092 return this.finishToken(type, word);
4093 };
4094
4095 // The main exported interface (under `self.acorn` when in the
4096 // browser) is a `parse` function that takes a code string and
4097 // returns an abstract syntax tree as specified by [Mozilla parser
4098 // API][api].
4099 //
4100 // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
4101
4102 function parse(input, options) {
4103 return new Parser(options, input).parse();
4104 }
4105
4106 function walk(ast, _ref) {
4107 var enter = _ref.enter;
4108 var leave = _ref.leave;
4109
4110 visit(ast, null, enter, leave);
4111 }
4112
4113 var context = {
4114 skip: function skip() {
4115 return context.shouldSkip = true;
4116 }
4117 };
4118
4119 var childKeys = {};
4120
4121 var toString = Object.prototype.toString;
4122
4123 function isArray(thing) {
4124 return toString.call(thing) === '[object Array]';
4125 }
4126
4127 function visit(node, parent, enter, leave, prop, index) {
4128 if (!node) return;
4129
4130 if (enter) {
4131 context.shouldSkip = false;
4132 enter.call(context, node, parent, prop, index);
4133 if (context.shouldSkip) return;
4134 }
4135
4136 var keys = childKeys[node.type] || (childKeys[node.type] = Object.keys(node).filter(function (prop) {
4137 return typeof node[prop] === 'object';
4138 }));
4139
4140 var key = undefined,
4141 value = undefined,
4142 i = undefined,
4143 j = undefined;
4144
4145 i = keys.length;
4146 while (i--) {
4147 key = keys[i];
4148 value = node[key];
4149
4150 if (isArray(value)) {
4151 j = value.length;
4152 while (j--) {
4153 visit(value[j], node, enter, leave, key, j);
4154 }
4155 } else if (value && value.type) {
4156 visit(value, node, enter, leave, key, null);
4157 }
4158 }
4159
4160 if (leave) {
4161 leave(node, parent, prop, index);
4162 }
4163 }
4164
4165 var extractors = {
4166 Identifier: function (names, param) {
4167 names.push(param.name);
4168 },
4169
4170 ObjectPattern: function (names, param) {
4171 param.properties.forEach(function (prop) {
4172 extractors[prop.key.type](names, prop.key);
4173 });
4174 },
4175
4176 ArrayPattern: function (names, param) {
4177 param.elements.forEach(function (element) {
4178 if (element) extractors[element.type](names, element);
4179 });
4180 },
4181
4182 RestElement: function (names, param) {
4183 extractors[param.argument.type](names, param.argument);
4184 },
4185
4186 AssignmentPattern: function (names, param) {
4187 return extractors[param.left.type](names, param.left);
4188 }
4189 };
4190
4191 function extractNames(param) {
4192 var names = [];
4193
4194 extractors[param.type](names, param);
4195 return names;
4196 }
4197
4198 var Declaration = (function () {
4199 function Declaration() {
4200 babelHelpers.classCallCheck(this, Declaration);
4201
4202 this.statement = null;
4203 this.name = null;
4204
4205 this.isReassigned = false;
4206 this.aliases = [];
4207 }
4208
4209 Declaration.prototype.addAlias = function addAlias(declaration) {
4210 this.aliases.push(declaration);
4211 };
4212
4213 Declaration.prototype.addReference = function addReference(reference) {
4214 reference.declaration = this;
4215 this.name = reference.name; // TODO handle differences of opinion
4216
4217 if (reference.isReassignment) this.isReassigned = true;
4218 };
4219
4220 Declaration.prototype.render = function render(es6) {
4221 if (es6) return this.name;
4222 if (!this.isReassigned || !this.isExported) return this.name;
4223
4224 return 'exports.' + this.name;
4225 };
4226
4227 Declaration.prototype.use = function use() {
4228 this.isUsed = true;
4229 if (this.statement) this.statement.mark();
4230
4231 this.aliases.forEach(function (alias) {
4232 return alias.use();
4233 });
4234 };
4235
4236 return Declaration;
4237 })();
4238
4239 var Scope = (function () {
4240 function Scope(options) {
4241 var _this = this;
4242
4243 babelHelpers.classCallCheck(this, Scope);
4244
4245 options = options || {};
4246
4247 this.parent = options.parent;
4248 this.isBlockScope = !!options.block;
4249
4250 this.declarations = blank();
4251
4252 if (options.params) {
4253 options.params.forEach(function (param) {
4254 extractNames(param).forEach(function (name) {
4255 _this.declarations[name] = new Declaration(name);
4256 });
4257 });
4258 }
4259 }
4260
4261 Scope.prototype.addDeclaration = function addDeclaration(node, isBlockDeclaration, isVar) {
4262 var _this2 = this;
4263
4264 if (!isBlockDeclaration && this.isBlockScope) {
4265 // it's a `var` or function node, and this
4266 // is a block scope, so we need to go up
4267 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
4268 } else {
4269 extractNames(node.id).forEach(function (name) {
4270 _this2.declarations[name] = new Declaration(name);
4271 });
4272 }
4273 };
4274
4275 Scope.prototype.contains = function contains(name) {
4276 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
4277 };
4278
4279 Scope.prototype.eachDeclaration = function eachDeclaration(fn) {
4280 var _this3 = this;
4281
4282 keys(this.declarations).forEach(function (key) {
4283 fn(key, _this3.declarations[key]);
4284 });
4285 };
4286
4287 Scope.prototype.findDeclaration = function findDeclaration(name) {
4288 return this.declarations[name] || this.parent && this.parent.findDeclaration(name);
4289 };
4290
4291 return Scope;
4292 })();
4293
4294 var blockDeclarations = {
4295 'const': true,
4296 'let': true
4297 };
4298 function attachScopes(statement) {
4299 var node = statement.node;
4300 var scope = statement.scope;
4301
4302 walk(node, {
4303 enter: function (node, parent) {
4304 // function foo () {...}
4305 // class Foo {...}
4306 if (/(Function|Class)Declaration/.test(node.type)) {
4307 scope.addDeclaration(node, false, false);
4308 }
4309
4310 // var foo = 1, bar = 2
4311 if (node.type === 'VariableDeclaration') {
4312 (function () {
4313 var isBlockDeclaration = blockDeclarations[node.kind];
4314 node.declarations.forEach(function (declaration) {
4315 return scope.addDeclaration(declaration, isBlockDeclaration, true);
4316 });
4317 })();
4318 }
4319
4320 var newScope = undefined;
4321
4322 // create new function scope
4323 if (/Function/.test(node.type)) {
4324 newScope = new Scope({
4325 parent: scope,
4326 block: false,
4327 params: node.params
4328 });
4329
4330 // named function expressions - the name is considered
4331 // part of the function's scope
4332 if (node.type === 'FunctionExpression' && node.id) {
4333 newScope.addDeclaration(node, false, false);
4334 }
4335 }
4336
4337 // create new block scope
4338 if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
4339 newScope = new Scope({
4340 parent: scope,
4341 block: true
4342 });
4343 }
4344
4345 // catch clause has its own block scope
4346 if (node.type === 'CatchClause') {
4347 newScope = new Scope({
4348 parent: scope,
4349 params: [node.param],
4350 block: true
4351 });
4352 }
4353
4354 if (newScope) {
4355 Object.defineProperty(node, '_scope', {
4356 value: newScope,
4357 configurable: true
4358 });
4359
4360 scope = newScope;
4361 }
4362 },
4363 leave: function (node) {
4364 if (node._scope) {
4365 scope = scope.parent;
4366 }
4367 }
4368 });
4369 }
4370
4371 function getLocation$1(source, charIndex) {
4372 var lines = source.split('\n');
4373 var len = lines.length;
4374
4375 var lineStart = 0;
4376 var i = undefined;
4377
4378 for (i = 0; i < len; i += 1) {
4379 var line = lines[i];
4380 var lineEnd = lineStart + line.length + 1; // +1 for newline
4381
4382 if (lineEnd > charIndex) {
4383 return { line: i + 1, column: charIndex - lineStart };
4384 }
4385
4386 lineStart = lineEnd;
4387 }
4388
4389 throw new Error('Could not determine location of character');
4390 }
4391
4392 var modifierNodes = {
4393 AssignmentExpression: 'left',
4394 UpdateExpression: 'argument'
4395 };
4396
4397 function isIife(node, parent) {
4398 return parent && parent.type === 'CallExpression' && node === parent.callee;
4399 }
4400
4401 function isReference(node, parent) {
4402 if (node.type === 'MemberExpression') {
4403 return !node.computed && isReference(node.object, node);
4404 }
4405
4406 if (node.type === 'Identifier') {
4407 // TODO is this right?
4408 if (parent.type === 'MemberExpression') return parent.computed || node === parent.object;
4409
4410 // disregard the `bar` in { bar: foo }
4411 if (parent.type === 'Property' && node !== parent.value) return false;
4412
4413 // disregard the `bar` in `class Foo { bar () {...} }`
4414 if (parent.type === 'MethodDefinition') return false;
4415
4416 // disregard the `bar` in `export { foo as bar }`
4417 if (parent.type === 'ExportSpecifier' && node !== parent.local) return;
4418
4419 return true;
4420 }
4421 }
4422
4423 var Reference = function Reference(node, scope) {
4424 babelHelpers.classCallCheck(this, Reference);
4425
4426 this.node = node;
4427 this.scope = scope;
4428
4429 this.declaration = null; // bound later
4430
4431 this.parts = [];
4432
4433 var root = node;
4434 while (root.type === 'MemberExpression') {
4435 this.parts.unshift(root.property.name);
4436 root = root.object;
4437 }
4438
4439 this.name = root.name;
4440
4441 this.start = node.start;
4442 this.end = node.start + this.name.length; // can be overridden in the case of namespace members
4443 this.rewritten = false;
4444 };
4445
4446 var Statement = (function () {
4447 function Statement(node, module, start, end) {
4448 babelHelpers.classCallCheck(this, Statement);
4449
4450 this.node = node;
4451 this.module = module;
4452 this.start = start;
4453 this.end = end;
4454 this.next = null; // filled in later
4455
4456 this.scope = new Scope();
4457
4458 this.references = [];
4459 this.stringLiteralRanges = [];
4460
4461 this.isIncluded = false;
4462
4463 this.isImportDeclaration = node.type === 'ImportDeclaration';
4464 this.isExportDeclaration = /^Export/.test(node.type);
4465 this.isReexportDeclaration = this.isExportDeclaration && !!node.source;
4466 }
4467
4468 Statement.prototype.analyse = function analyse() {
4469 var _this = this;
4470
4471 if (this.isImportDeclaration) return; // nothing to analyse
4472
4473 // attach scopes
4474 attachScopes(this);
4475
4476 // attach statement to each top-level declaration,
4477 // so we can mark statements easily
4478 this.scope.eachDeclaration(function (name, declaration) {
4479 declaration.statement = _this;
4480 });
4481
4482 // find references
4483 var module = this.module;
4484 var references = this.references;
4485 var scope = this.scope;
4486 var stringLiteralRanges = this.stringLiteralRanges;
4487
4488 var readDepth = 0;
4489
4490 walk(this.node, {
4491 enter: function (node, parent) {
4492 // warn about eval
4493 if (node.type === 'CallExpression' && node.callee.name === 'eval' && !scope.contains('eval')) {
4494 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');
4495 }
4496
4497 if (node.type === 'TemplateElement') stringLiteralRanges.push([node.start, node.end]);
4498 if (node.type === 'Literal' && typeof node.value === 'string' && /\n/.test(node.raw)) {
4499 stringLiteralRanges.push([node.start + 1, node.end - 1]);
4500 }
4501
4502 if (node._scope) scope = node._scope;
4503 if (/Function/.test(node.type) && !isIife(node, parent)) readDepth += 1;
4504
4505 // special case – shorthand properties. because node.key === node.value,
4506 // we can't differentiate once we've descended into the node
4507 if (node.type === 'Property' && node.shorthand) {
4508 var reference = new Reference(node.key, scope);
4509 reference.isShorthandProperty = true; // TODO feels a bit kludgy
4510 references.push(reference);
4511 return this.skip();
4512 }
4513
4514 var isReassignment = undefined;
4515
4516 if (parent && parent.type in modifierNodes) {
4517 var subject = parent[modifierNodes[parent.type]];
4518 var depth = 0;
4519
4520 while (subject.type === 'MemberExpression') {
4521 subject = subject.object;
4522 depth += 1;
4523 }
4524
4525 var importDeclaration = module.imports[subject.name];
4526
4527 if (!scope.contains(subject.name) && importDeclaration) {
4528 var minDepth = importDeclaration.name === '*' ? 2 : // cannot do e.g. `namespace.foo = bar`
4529 1; // cannot do e.g. `foo = bar`, but `foo.bar = bar` is fine
4530
4531 if (depth < minDepth) {
4532 var err = new Error('Illegal reassignment to import \'' + subject.name + '\'');
4533 err.file = module.id;
4534 err.loc = getLocation$1(module.magicString.toString(), subject.start);
4535 throw err;
4536 }
4537 }
4538
4539 isReassignment = !depth;
4540 }
4541
4542 if (isReference(node, parent)) {
4543 // function declaration IDs are a special case – they're associated
4544 // with the parent scope
4545 var referenceScope = parent.type === 'FunctionDeclaration' && node === parent.id ? scope.parent : scope;
4546
4547 var reference = new Reference(node, referenceScope);
4548 references.push(reference);
4549
4550 reference.isImmediatelyUsed = !readDepth;
4551 reference.isReassignment = isReassignment;
4552
4553 this.skip(); // don't descend from `foo.bar.baz` into `foo.bar`
4554 }
4555 },
4556 leave: function (node, parent) {
4557 if (node._scope) scope = scope.parent;
4558 if (/Function/.test(node.type) && !isIife(node, parent)) readDepth -= 1;
4559 }
4560 });
4561 };
4562
4563 Statement.prototype.mark = function mark() {
4564 if (this.isIncluded) return; // prevent infinite loops
4565 this.isIncluded = true;
4566
4567 this.references.forEach(function (reference) {
4568 if (reference.declaration) reference.declaration.use();
4569 });
4570 };
4571
4572 Statement.prototype.markSideEffect = function markSideEffect() {
4573 if (this.isIncluded) return;
4574
4575 var statement = this;
4576 var hasSideEffect = false;
4577
4578 walk(this.node, {
4579 enter: function (node, parent) {
4580 if (/Function/.test(node.type) && !isIife(node, parent)) return this.skip();
4581
4582 // If this is a top-level call expression, or an assignment to a global,
4583 // this statement will need to be marked
4584 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
4585 hasSideEffect = true;
4586 } else if (node.type in modifierNodes) {
4587 var subject = node[modifierNodes[node.type]];
4588 while (subject.type === 'MemberExpression') subject = subject.object;
4589
4590 var declaration = statement.module.trace(subject.name);
4591
4592 if (!declaration || declaration.isExternal || declaration.statement.isIncluded) {
4593 hasSideEffect = true;
4594 }
4595 }
4596
4597 if (hasSideEffect) this.skip();
4598 }
4599 });
4600
4601 if (hasSideEffect) statement.mark();
4602 return hasSideEffect;
4603 };
4604
4605 Statement.prototype.source = function source() {
4606 return this.module.source.slice(this.start, this.end);
4607 };
4608
4609 Statement.prototype.toString = function toString() {
4610 return this.module.magicString.slice(this.start, this.end);
4611 };
4612
4613 return Statement;
4614 })();
4615
4616 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(' ');
4617 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(' ');
4618
4619 var blacklisted = blank();
4620 reservedWords.concat(builtins).forEach(function (word) {
4621 return blacklisted[word] = true;
4622 });
4623 function makeLegalIdentifier(str) {
4624 str = str.replace(/-(\w)/g, function (_, letter) {
4625 return letter.toUpperCase();
4626 }).replace(/[^$_a-zA-Z0-9]/g, '_');
4627
4628 if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str;
4629
4630 return str;
4631 }
4632
4633 var SyntheticDefaultDeclaration = (function () {
4634 function SyntheticDefaultDeclaration(node, statement, name) {
4635 babelHelpers.classCallCheck(this, SyntheticDefaultDeclaration);
4636
4637 this.node = node;
4638 this.statement = statement;
4639 this.name = name;
4640
4641 this.original = null;
4642 this.isExported = false;
4643 this.aliases = [];
4644 }
4645
4646 SyntheticDefaultDeclaration.prototype.addAlias = function addAlias(declaration) {
4647 this.aliases.push(declaration);
4648 };
4649
4650 SyntheticDefaultDeclaration.prototype.addReference = function addReference(reference) {
4651 // Don't change the name to `default`; it's not a valid identifier name.
4652 if (reference.name === 'default') return;
4653
4654 reference.declaration = this;
4655 this.name = reference.name;
4656 };
4657
4658 SyntheticDefaultDeclaration.prototype.bind = function bind(declaration) {
4659 this.original = declaration;
4660 };
4661
4662 SyntheticDefaultDeclaration.prototype.render = function render() {
4663 return !this.original || this.original.isReassigned ? this.name : this.original.render();
4664 };
4665
4666 SyntheticDefaultDeclaration.prototype.use = function use() {
4667 this.isUsed = true;
4668 this.statement.mark();
4669
4670 if (this.original) this.original.use();
4671
4672 this.aliases.forEach(function (alias) {
4673 return alias.use();
4674 });
4675 };
4676
4677 return SyntheticDefaultDeclaration;
4678 })();
4679
4680 var SyntheticNamespaceDeclaration = (function () {
4681 function SyntheticNamespaceDeclaration(module) {
4682 var _this = this;
4683
4684 babelHelpers.classCallCheck(this, SyntheticNamespaceDeclaration);
4685
4686 this.module = module;
4687 this.name = null;
4688
4689 this.needsNamespaceBlock = false;
4690 this.aliases = [];
4691
4692 this.originals = blank();
4693 module.getExports().forEach(function (name) {
4694 _this.originals[name] = module.traceExport(name);
4695 });
4696 }
4697
4698 SyntheticNamespaceDeclaration.prototype.addAlias = function addAlias(declaration) {
4699 this.aliases.push(declaration);
4700 };
4701
4702 SyntheticNamespaceDeclaration.prototype.addReference = function addReference(reference) {
4703 // if we have e.g. `foo.bar`, we can optimise
4704 // the reference by pointing directly to `bar`
4705 if (reference.parts.length) {
4706 reference.name = reference.parts.shift();
4707
4708 reference.end += reference.name.length + 1; // TODO this is brittle
4709
4710 var original = this.originals[reference.name];
4711
4712 // throw with an informative error message if the reference doesn't exist.
4713 if (!original) {
4714 this.module.bundle.onwarn('Export \'' + reference.name + '\' is not defined by \'' + this.module.id + '\'');
4715 reference.isUndefined = true;
4716 return;
4717 }
4718
4719 original.addReference(reference);
4720 return;
4721 }
4722
4723 // otherwise we're accessing the namespace directly,
4724 // which means we need to mark all of this module's
4725 // exports and render a namespace block in the bundle
4726 if (!this.needsNamespaceBlock) {
4727 this.needsNamespaceBlock = true;
4728 this.module.bundle.internalNamespaces.push(this);
4729 }
4730
4731 reference.declaration = this;
4732 this.name = reference.name;
4733 };
4734
4735 SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock(indentString) {
4736 var _this2 = this;
4737
4738 var members = keys(this.originals).map(function (name) {
4739 var original = _this2.originals[name];
4740
4741 if (original.isReassigned) {
4742 return indentString + 'get ' + name + ' () { return ' + original.render() + '; }';
4743 }
4744
4745 return '' + indentString + name + ': ' + original.render();
4746 });
4747
4748 return 'var ' + this.render() + ' = Object.freeze({\n' + members.join(',\n') + '\n});\n\n';
4749 };
4750
4751 SyntheticNamespaceDeclaration.prototype.render = function render() {
4752 return this.name;
4753 };
4754
4755 SyntheticNamespaceDeclaration.prototype.use = function use() {
4756 var _this3 = this;
4757
4758 keys(this.originals).forEach(function (name) {
4759 _this3.originals[name].use();
4760 });
4761
4762 this.aliases.forEach(function (alias) {
4763 return alias.use();
4764 });
4765 };
4766
4767 return SyntheticNamespaceDeclaration;
4768 })();
4769
4770 var Module = (function () {
4771 function Module(_ref) {
4772 var id = _ref.id;
4773 var code = _ref.code;
4774 var originalCode = _ref.originalCode;
4775 var ast = _ref.ast;
4776 var sourceMapChain = _ref.sourceMapChain;
4777 var bundle = _ref.bundle;
4778 babelHelpers.classCallCheck(this, Module);
4779
4780 this.code = code;
4781 this.originalCode = originalCode;
4782 this.sourceMapChain = sourceMapChain;
4783
4784 this.bundle = bundle;
4785 this.id = id;
4786
4787 // all dependencies
4788 this.dependencies = [];
4789 this.resolvedIds = blank();
4790
4791 // imports and exports, indexed by local name
4792 this.imports = blank();
4793 this.exports = blank();
4794 this.reexports = blank();
4795
4796 this.exportAllSources = [];
4797 this.exportAllModules = null;
4798
4799 // By default, `id` is the filename. Custom resolvers and loaders
4800 // can change that, but it makes sense to use it for the source filename
4801 this.magicString = new MagicString(code, {
4802 filename: id,
4803 indentExclusionRanges: []
4804 });
4805
4806 // remove existing sourceMappingURL comments
4807 var pattern = new RegExp('\\/\\/#\\s+' + SOURCEMAPPING_URL$1 + '=.+\\n?', 'g');
4808 var match = undefined;
4809 while (match = pattern.exec(code)) {
4810 this.magicString.remove(match.index, match.index + match[0].length);
4811 }
4812
4813 this.comments = [];
4814 this.statements = this.parse(ast);
4815
4816 this.declarations = blank();
4817 this.analyse();
4818 }
4819
4820 Module.prototype.addExport = function addExport(statement) {
4821 var _this4 = this;
4822
4823 var node = statement.node;
4824 var source = node.source && node.source.value;
4825
4826 // export { name } from './other.js'
4827 if (source) {
4828 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
4829
4830 if (node.type === 'ExportAllDeclaration') {
4831 // Store `export * from '...'` statements in an array of delegates.
4832 // When an unknown import is encountered, we see if one of them can satisfy it.
4833 this.exportAllSources.push(source);
4834 } else {
4835 node.specifiers.forEach(function (specifier) {
4836 _this4.reexports[specifier.exported.name] = {
4837 source: source,
4838 localName: specifier.local.name,
4839 module: null // filled in later
4840 };
4841 });
4842 }
4843 }
4844
4845 // export default function foo () {}
4846 // export default foo;
4847 // export default 42;
4848 else if (node.type === 'ExportDefaultDeclaration') {
4849 var identifier = node.declaration.id && node.declaration.id.name || node.declaration.name;
4850
4851 this.exports.default = {
4852 localName: 'default',
4853 identifier: identifier
4854 };
4855
4856 // create a synthetic declaration
4857 this.declarations.default = new SyntheticDefaultDeclaration(node, statement, identifier || this.basename());
4858 }
4859
4860 // export { foo, bar, baz }
4861 // export var foo = 42;
4862 // export var a = 1, b = 2, c = 3;
4863 // export function foo () {}
4864 else if (node.type === 'ExportNamedDeclaration') {
4865 if (node.specifiers.length) {
4866 // export { foo, bar, baz }
4867 node.specifiers.forEach(function (specifier) {
4868 var localName = specifier.local.name;
4869 var exportedName = specifier.exported.name;
4870
4871 _this4.exports[exportedName] = { localName: localName };
4872 });
4873 } else {
4874 var declaration = node.declaration;
4875
4876 var _name = undefined;
4877
4878 if (declaration.type === 'VariableDeclaration') {
4879 // export var foo = 42
4880 _name = declaration.declarations[0].id.name;
4881 } else {
4882 // export function foo () {}
4883 _name = declaration.id.name;
4884 }
4885
4886 this.exports[_name] = { localName: _name };
4887 }
4888 }
4889 };
4890
4891 Module.prototype.addImport = function addImport(statement) {
4892 var _this5 = this;
4893
4894 var node = statement.node;
4895 var source = node.source.value;
4896
4897 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
4898
4899 node.specifiers.forEach(function (specifier) {
4900 var localName = specifier.local.name;
4901
4902 if (_this5.imports[localName]) {
4903 var err = new Error('Duplicated import \'' + localName + '\'');
4904 err.file = _this5.id;
4905 err.loc = getLocation$1(_this5.code, specifier.start);
4906 throw err;
4907 }
4908
4909 var isDefault = specifier.type === 'ImportDefaultSpecifier';
4910 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
4911
4912 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
4913 _this5.imports[localName] = { source: source, name: name, module: null };
4914 });
4915 };
4916
4917 Module.prototype.analyse = function analyse() {
4918 var _this6 = this;
4919
4920 // discover this module's imports and exports
4921 this.statements.forEach(function (statement) {
4922 if (statement.isImportDeclaration) _this6.addImport(statement);else if (statement.isExportDeclaration) _this6.addExport(statement);
4923
4924 statement.analyse();
4925
4926 statement.scope.eachDeclaration(function (name, declaration) {
4927 _this6.declarations[name] = declaration;
4928 });
4929 });
4930 };
4931
4932 Module.prototype.basename = function basename() {
4933 var base = _basename(this.id);
4934 var ext = extname(this.id);
4935
4936 return makeLegalIdentifier(ext ? base.slice(0, -ext.length) : base);
4937 };
4938
4939 Module.prototype.bindAliases = function bindAliases() {
4940 var _this7 = this;
4941
4942 keys(this.declarations).forEach(function (name) {
4943 if (name === '*') return;
4944
4945 var declaration = _this7.declarations[name];
4946 var statement = declaration.statement;
4947
4948 if (statement.node.type !== 'VariableDeclaration') return;
4949
4950 statement.references.forEach(function (reference) {
4951 if (reference.name === name || !reference.isImmediatelyUsed) return;
4952
4953 var otherDeclaration = _this7.trace(reference.name);
4954 if (otherDeclaration) otherDeclaration.addAlias(declaration);
4955 });
4956 });
4957 };
4958
4959 Module.prototype.bindImportSpecifiers = function bindImportSpecifiers() {
4960 var _this8 = this;
4961
4962 [this.imports, this.reexports].forEach(function (specifiers) {
4963 keys(specifiers).forEach(function (name) {
4964 var specifier = specifiers[name];
4965
4966 var id = _this8.resolvedIds[specifier.source];
4967 specifier.module = _this8.bundle.moduleById[id];
4968 });
4969 });
4970
4971 this.exportAllModules = this.exportAllSources.map(function (source) {
4972 var id = _this8.resolvedIds[source];
4973 return _this8.bundle.moduleById[id];
4974 });
4975 };
4976
4977 Module.prototype.bindReferences = function bindReferences() {
4978 var _this9 = this;
4979
4980 if (this.declarations.default) {
4981 if (this.exports.default.identifier) {
4982 var declaration = this.trace(this.exports.default.identifier);
4983 if (declaration) this.declarations.default.bind(declaration);
4984 }
4985 }
4986
4987 this.statements.forEach(function (statement) {
4988 // skip `export { foo, bar, baz }`...
4989 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length) {
4990 // ...unless this is the entry module
4991 if (_this9 !== _this9.bundle.entryModule) return;
4992 }
4993
4994 statement.references.forEach(function (reference) {
4995 var declaration = reference.scope.findDeclaration(reference.name) || _this9.trace(reference.name);
4996
4997 if (declaration) {
4998 declaration.addReference(reference);
4999 } else if (statement.node.type !== 'ExportNamedDeclaration' || !_this9.reexports[reference.name]) {
5000 // TODO handle globals
5001 _this9.bundle.assumedGlobals[reference.name] = true;
5002 }
5003 });
5004 });
5005 };
5006
5007 Module.prototype.consolidateDependencies = function consolidateDependencies() {
5008 var _this10 = this;
5009
5010 var strongDependencies = blank();
5011 var weakDependencies = blank();
5012
5013 // treat all imports as weak dependencies
5014 this.dependencies.forEach(function (source) {
5015 var id = _this10.resolvedIds[source];
5016 var dependency = _this10.bundle.moduleById[id];
5017
5018 if (!dependency.isExternal) {
5019 weakDependencies[dependency.id] = dependency;
5020 }
5021 });
5022
5023 // identify strong dependencies to break ties in case of cycles
5024 this.statements.forEach(function (statement) {
5025 statement.references.forEach(function (reference) {
5026 var declaration = reference.declaration;
5027
5028 if (declaration && declaration.statement) {
5029 var _module = declaration.statement.module;
5030 if (_module === _this10) return;
5031
5032 // TODO disregard function declarations
5033 if (reference.isImmediatelyUsed) {
5034 strongDependencies[_module.id] = _module;
5035 }
5036 }
5037 });
5038 });
5039
5040 return { strongDependencies: strongDependencies, weakDependencies: weakDependencies };
5041 };
5042
5043 Module.prototype.getExports = function getExports() {
5044 var exports = blank();
5045
5046 keys(this.exports).forEach(function (name) {
5047 exports[name] = true;
5048 });
5049
5050 keys(this.reexports).forEach(function (name) {
5051 exports[name] = true;
5052 });
5053
5054 this.exportAllModules.forEach(function (module) {
5055 module.getExports().forEach(function (name) {
5056 if (name !== 'default') exports[name] = true;
5057 });
5058 });
5059
5060 return keys(exports);
5061 };
5062
5063 Module.prototype.markAllSideEffects = function markAllSideEffects() {
5064 var hasSideEffect = false;
5065
5066 this.statements.forEach(function (statement) {
5067 if (statement.markSideEffect()) hasSideEffect = true;
5068 });
5069
5070 return hasSideEffect;
5071 };
5072
5073 Module.prototype.namespace = function namespace() {
5074 if (!this.declarations['*']) {
5075 this.declarations['*'] = new SyntheticNamespaceDeclaration(this);
5076 }
5077
5078 return this.declarations['*'];
5079 };
5080
5081 Module.prototype.parse = function parse$$(ast) {
5082 var _this11 = this;
5083
5084 // The ast can be supplied programmatically (but usually won't be)
5085 if (!ast) {
5086 // Try to extract a list of top-level statements/declarations. If
5087 // the parse fails, attach file info and abort
5088 try {
5089 ast = parse(this.code, {
5090 ecmaVersion: 6,
5091 sourceType: 'module',
5092 onComment: function (block, text, start, end) {
5093 return _this11.comments.push({ block: block, text: text, start: start, end: end });
5094 },
5095 preserveParens: true
5096 });
5097 } catch (err) {
5098 err.code = 'PARSE_ERROR';
5099 err.file = this.id; // see above - not necessarily true, but true enough
5100 err.message += ' in ' + this.id;
5101 throw err;
5102 }
5103 }
5104
5105 walk(ast, {
5106 enter: function (node) {
5107 _this11.magicString.addSourcemapLocation(node.start);
5108 _this11.magicString.addSourcemapLocation(node.end);
5109 }
5110 });
5111
5112 var statements = [];
5113 var lastChar = 0;
5114 var commentIndex = 0;
5115
5116 ast.body.forEach(function (node) {
5117 if (node.type === 'EmptyStatement') return;
5118
5119 if (node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'VariableDeclaration' && node.declaration.declarations && node.declaration.declarations.length > 1) {
5120 // push a synthetic export declaration
5121 var syntheticNode = {
5122 type: 'ExportNamedDeclaration',
5123 specifiers: node.declaration.declarations.map(function (declarator) {
5124 var id = { name: declarator.id.name };
5125 return {
5126 local: id,
5127 exported: id
5128 };
5129 }),
5130 isSynthetic: true
5131 };
5132
5133 var statement = new Statement(syntheticNode, _this11, node.start, node.start);
5134 statements.push(statement);
5135
5136 _this11.magicString.remove(node.start, node.declaration.start);
5137 node = node.declaration;
5138 }
5139
5140 // special case - top-level var declarations with multiple declarators
5141 // should be split up. Otherwise, we may end up including code we
5142 // don't need, just because an unwanted declarator is included
5143 if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
5144 // remove the leading var/let/const... UNLESS the previous node
5145 // was also a synthetic node, in which case it'll get removed anyway
5146 var lastStatement = statements[statements.length - 1];
5147 if (!lastStatement || !lastStatement.node.isSynthetic) {
5148 _this11.magicString.remove(node.start, node.declarations[0].start);
5149 }
5150
5151 node.declarations.forEach(function (declarator) {
5152 var start = declarator.start;
5153 var end = declarator.end;
5154
5155 var syntheticNode = {
5156 type: 'VariableDeclaration',
5157 kind: node.kind,
5158 start: start,
5159 end: end,
5160 declarations: [declarator],
5161 isSynthetic: true
5162 };
5163
5164 var statement = new Statement(syntheticNode, _this11, start, end);
5165 statements.push(statement);
5166 });
5167
5168 lastChar = node.end; // TODO account for trailing line comment
5169 } else {
5170 var comment = undefined;
5171 do {
5172 comment = _this11.comments[commentIndex];
5173 if (!comment) break;
5174 if (comment.start > node.start) break;
5175 commentIndex += 1;
5176 } while (comment.end < lastChar);
5177
5178 var start = comment ? Math.min(comment.start, node.start) : node.start;
5179 var end = node.end; // TODO account for trailing line comment
5180
5181 var statement = new Statement(node, _this11, start, end);
5182 statements.push(statement);
5183
5184 lastChar = end;
5185 }
5186 });
5187
5188 var i = statements.length;
5189 var next = this.code.length;
5190 while (i--) {
5191 statements[i].next = next;
5192 if (!statements[i].isSynthetic) next = statements[i].start;
5193 }
5194
5195 return statements;
5196 };
5197
5198 Module.prototype.render = function render(es6) {
5199 var _this12 = this;
5200
5201 var magicString = this.magicString.clone();
5202
5203 this.statements.forEach(function (statement) {
5204 if (!statement.isIncluded) {
5205 magicString.remove(statement.start, statement.next);
5206 return;
5207 }
5208
5209 statement.stringLiteralRanges.forEach(function (range) {
5210 return magicString.indentExclusionRanges.push(range);
5211 });
5212
5213 // skip `export { foo, bar, baz }`
5214 if (statement.node.type === 'ExportNamedDeclaration') {
5215 if (statement.node.isSynthetic) return;
5216
5217 // skip `export { foo, bar, baz }`
5218 if (statement.node.specifiers.length) {
5219 magicString.remove(statement.start, statement.next);
5220 return;
5221 }
5222 }
5223
5224 // split up/remove var declarations as necessary
5225 if (statement.node.isSynthetic) {
5226 // insert `var/let/const` if necessary
5227 var declaration = _this12.declarations[statement.node.declarations[0].id.name];
5228 if (!(declaration.isExported && declaration.isReassigned)) {
5229 // TODO encapsulate this
5230 magicString.insert(statement.start, statement.node.kind + ' ');
5231 }
5232
5233 magicString.overwrite(statement.end, statement.next, ';\n'); // TODO account for trailing newlines
5234 }
5235
5236 var toDeshadow = blank();
5237
5238 statement.references.forEach(function (reference) {
5239 var start = reference.start;
5240 var end = reference.end;
5241
5242 if (reference.isUndefined) {
5243 magicString.overwrite(start, end, 'undefined', true);
5244 }
5245
5246 var declaration = reference.declaration;
5247
5248 if (declaration) {
5249 var _name2 = declaration.render(es6);
5250
5251 // the second part of this check is necessary because of
5252 // namespace optimisation – name of `foo.bar` could be `bar`
5253 if (reference.name === _name2 && _name2.length === end - start) return;
5254
5255 reference.rewritten = true;
5256
5257 // prevent local variables from shadowing renamed references
5258 var identifier = _name2.match(/[^\.]+/)[0];
5259 if (reference.scope.contains(identifier)) {
5260 toDeshadow[identifier] = identifier + '$$'; // TODO more robust mechanism
5261 }
5262
5263 if (reference.isShorthandProperty) {
5264 magicString.insert(end, ': ' + _name2);
5265 } else {
5266 magicString.overwrite(start, end, _name2, true);
5267 }
5268 }
5269 });
5270
5271 if (keys(toDeshadow).length) {
5272 statement.references.forEach(function (reference) {
5273 if (!reference.rewritten && reference.name in toDeshadow) {
5274 magicString.overwrite(reference.start, reference.end, toDeshadow[reference.name], true);
5275 }
5276 });
5277 }
5278
5279 // modify exports as necessary
5280 if (statement.isExportDeclaration) {
5281 // remove `export` from `export var foo = 42`
5282 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration') {
5283 var _name3 = statement.node.declaration.declarations[0].id.name;
5284 var declaration = _this12.declarations[_name3];
5285
5286 var end = declaration.isExported && declaration.isReassigned ? statement.node.declaration.declarations[0].start : statement.node.declaration.start;
5287
5288 magicString.remove(statement.node.start, end);
5289 } else if (statement.node.type === 'ExportAllDeclaration') {
5290 // TODO: remove once `export * from 'external'` is supported.
5291 magicString.remove(statement.start, statement.next);
5292 }
5293
5294 // remove `export` from `export class Foo {...}` or `export default Foo`
5295 // TODO default exports need different treatment
5296 else if (statement.node.declaration.id) {
5297 magicString.remove(statement.node.start, statement.node.declaration.start);
5298 } else if (statement.node.type === 'ExportDefaultDeclaration') {
5299 var defaultDeclaration = _this12.declarations.default;
5300
5301 // prevent `var foo = foo`
5302 if (defaultDeclaration.original && !defaultDeclaration.original.isReassigned) {
5303 magicString.remove(statement.start, statement.next);
5304 return;
5305 }
5306
5307 var defaultName = defaultDeclaration.render();
5308
5309 // prevent `var undefined = sideEffectyDefault(foo)`
5310 if (!defaultDeclaration.isExported && !defaultDeclaration.isUsed) {
5311 magicString.remove(statement.start, statement.node.declaration.start);
5312 return;
5313 }
5314
5315 // anonymous functions should be converted into declarations
5316 if (statement.node.declaration.type === 'FunctionExpression') {
5317 magicString.overwrite(statement.node.start, statement.node.declaration.start + 8, 'function ' + defaultName);
5318 } else {
5319 magicString.overwrite(statement.node.start, statement.node.declaration.start, 'var ' + defaultName + ' = ');
5320 }
5321 } else {
5322 throw new Error('Unhandled export');
5323 }
5324 }
5325 });
5326
5327 // add namespace block if necessary
5328 var namespace = this.declarations['*'];
5329 if (namespace && namespace.needsNamespaceBlock) {
5330 magicString.append('\n\n' + namespace.renderBlock(magicString.getIndentString()));
5331 }
5332
5333 return magicString.trim();
5334 };
5335
5336 Module.prototype.trace = function trace(name) {
5337 if (name in this.declarations) return this.declarations[name];
5338 if (name in this.imports) {
5339 var importDeclaration = this.imports[name];
5340 var otherModule = importDeclaration.module;
5341
5342 if (importDeclaration.name === '*' && !otherModule.isExternal) {
5343 return otherModule.namespace();
5344 }
5345
5346 var declaration = otherModule.traceExport(importDeclaration.name);
5347
5348 if (!declaration) throw new Error('Module ' + otherModule.id + ' does not export ' + importDeclaration.name + ' (imported by ' + this.id + ')');
5349 return declaration;
5350 }
5351
5352 return null;
5353 };
5354
5355 Module.prototype.traceExport = function traceExport(name) {
5356 // export { foo } from './other.js'
5357 var reexportDeclaration = this.reexports[name];
5358 if (reexportDeclaration) {
5359 return reexportDeclaration.module.traceExport(reexportDeclaration.localName);
5360 }
5361
5362 var exportDeclaration = this.exports[name];
5363 if (exportDeclaration) {
5364 return this.trace(exportDeclaration.localName);
5365 }
5366
5367 for (var i = 0; i < this.exportAllModules.length; i += 1) {
5368 var _module2 = this.exportAllModules[i];
5369 var declaration = _module2.traceExport(name);
5370
5371 if (declaration) return declaration;
5372 }
5373 };
5374
5375 return Module;
5376 })();
5377
5378 var ExternalDeclaration = (function () {
5379 function ExternalDeclaration(module, name) {
5380 babelHelpers.classCallCheck(this, ExternalDeclaration);
5381
5382 this.module = module;
5383 this.name = name;
5384 this.isExternal = true;
5385 }
5386
5387 ExternalDeclaration.prototype.addAlias = function addAlias() {
5388 // noop
5389 };
5390
5391 ExternalDeclaration.prototype.addReference = function addReference(reference) {
5392 reference.declaration = this;
5393
5394 if (this.name === 'default' || this.name === '*') {
5395 this.module.suggestName(reference.name);
5396 }
5397 };
5398
5399 ExternalDeclaration.prototype.render = function render(es6) {
5400 if (this.name === '*') {
5401 return this.module.name;
5402 }
5403
5404 if (this.name === 'default') {
5405 return !es6 && this.module.exportsNames ? this.module.name + '__default' : this.module.name;
5406 }
5407
5408 return es6 ? this.name : this.module.name + '.' + this.name;
5409 };
5410
5411 ExternalDeclaration.prototype.use = function use() {
5412 // noop?
5413 };
5414
5415 return ExternalDeclaration;
5416 })();
5417
5418 var ExternalModule = (function () {
5419 function ExternalModule(id) {
5420 babelHelpers.classCallCheck(this, ExternalModule);
5421
5422 this.id = id;
5423 this.name = makeLegalIdentifier(id);
5424
5425 this.nameSuggestions = blank();
5426 this.mostCommonSuggestion = 0;
5427
5428 this.isExternal = true;
5429 this.declarations = blank();
5430
5431 this.exportsNames = false;
5432 }
5433
5434 ExternalModule.prototype.suggestName = function suggestName(name) {
5435 if (!this.nameSuggestions[name]) this.nameSuggestions[name] = 0;
5436 this.nameSuggestions[name] += 1;
5437
5438 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
5439 this.mostCommonSuggestion = this.nameSuggestions[name];
5440 this.name = name;
5441 }
5442 };
5443
5444 ExternalModule.prototype.traceExport = function traceExport(name) {
5445 if (name !== 'default' && name !== '*') {
5446 this.exportsNames = true;
5447 }
5448
5449 return this.declarations[name] || (this.declarations[name] = new ExternalDeclaration(this, name));
5450 };
5451
5452 return ExternalModule;
5453 })();
5454
5455 function getName(x) {
5456 return x.name;
5457 }
5458
5459 function quoteId(x) {
5460 return "'" + x.id + "'";
5461 }
5462
5463 function req(x) {
5464 return "require('" + x.id + "')";
5465 }
5466
5467 function getInteropBlock(bundle) {
5468 return bundle.externalModules.map(function (module) {
5469 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;
5470 }).filter(Boolean).join('\n');
5471 }
5472
5473 function getExportBlock(entryModule, exportMode) {
5474 var mechanism = arguments.length <= 2 || arguments[2] === undefined ? 'return' : arguments[2];
5475
5476 if (exportMode === 'default') {
5477 return mechanism + ' ' + entryModule.declarations.default.render(false) + ';';
5478 }
5479
5480 return entryModule.getExports().map(function (name) {
5481 var prop = name === 'default' ? '[\'default\']' : '.' + name;
5482 var declaration = entryModule.traceExport(name);
5483
5484 var lhs = 'exports' + prop;
5485 var rhs = declaration.render(false);
5486
5487 // prevent `exports.count = exports.count`
5488 if (lhs === rhs) return null;
5489
5490 return lhs + ' = ' + rhs + ';';
5491 }).filter(Boolean).join('\n');
5492 }
5493
5494 function umd(bundle, magicString, _ref, options) {
5495 var exportMode = _ref.exportMode;
5496 var indentString = _ref.indentString;
5497
5498 if (exportMode !== 'none' && !options.moduleName) {
5499 throw new Error('You must supply options.moduleName for UMD bundles');
5500 }
5501
5502 var globalNames = options.globals || blank();
5503
5504 var amdDeps = bundle.externalModules.map(quoteId);
5505 var cjsDeps = bundle.externalModules.map(req);
5506 var globalDeps = bundle.externalModules.map(function (module) {
5507 return 'global.' + (globalNames[module.id] || module.name);
5508 });
5509
5510 var args = bundle.externalModules.map(getName);
5511
5512 if (exportMode === 'named') {
5513 amdDeps.unshift('\'exports\'');
5514 cjsDeps.unshift('exports');
5515 globalDeps.unshift('(global.' + options.moduleName + ' = {})');
5516
5517 args.unshift('exports');
5518 }
5519
5520 var amdParams = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (amdDeps.length ? '[' + amdDeps.join(', ') + '], ' : '');
5521
5522 var cjsExport = exportMode === 'default' ? 'module.exports = ' : '';
5523 var defaultExport = exportMode === 'default' ? 'global.' + options.moduleName + ' = ' : '';
5524
5525 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5526
5527 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());
5528
5529 // var foo__default = 'default' in foo ? foo['default'] : foo;
5530 var interopBlock = getInteropBlock(bundle);
5531 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5532
5533 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5534 if (exportBlock) magicString.append('\n\n' + exportBlock);
5535
5536 return magicString.trim().indent(indentString).append('\n\n}));').prepend(intro);
5537 }
5538
5539 function iife(bundle, magicString, _ref, options) {
5540 var exportMode = _ref.exportMode;
5541 var indentString = _ref.indentString;
5542
5543 var globalNames = options.globals || blank();
5544
5545 var dependencies = bundle.externalModules.map(function (module) {
5546 return globalNames[module.id] || module.name;
5547 });
5548
5549 var args = bundle.externalModules.map(getName);
5550
5551 if (exportMode !== 'none' && !options.moduleName) {
5552 throw new Error('You must supply options.moduleName for IIFE bundles');
5553 }
5554
5555 if (exportMode === 'named') {
5556 dependencies.unshift('(this.' + options.moduleName + ' = {})');
5557 args.unshift('exports');
5558 }
5559
5560 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5561 var intro = '(function (' + args + ') {' + useStrict + '\n\n';
5562 var outro = '\n\n})(' + dependencies + ');';
5563
5564 if (exportMode === 'default') {
5565 intro = 'var ' + options.moduleName + ' = ' + intro;
5566 }
5567
5568 // var foo__default = 'default' in foo ? foo['default'] : foo;
5569 var interopBlock = getInteropBlock(bundle);
5570 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5571
5572 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5573 if (exportBlock) magicString.append('\n\n' + exportBlock);
5574
5575 return magicString.indent(indentString).prepend(intro).append(outro);
5576 }
5577
5578 function notDefault(name) {
5579 return name !== 'default';
5580 }
5581 function es6(bundle, magicString) {
5582 var importBlock = bundle.externalModules.map(function (module) {
5583 var specifiers = [];
5584 var importedNames = keys(module.declarations).filter(function (name) {
5585 return name !== '*' && name !== 'default';
5586 });
5587
5588 if (module.declarations.default) {
5589 specifiers.push(module.name);
5590 }
5591
5592 if (module.declarations['*']) {
5593 specifiers.push('* as ' + module.name);
5594 }
5595
5596 if (importedNames.length) {
5597 specifiers.push('{ ' + importedNames.join(', ') + ' }');
5598 }
5599
5600 return specifiers.length ? 'import ' + specifiers.join(', ') + ' from \'' + module.id + '\';' : 'import \'' + module.id + '\';';
5601 }).join('\n');
5602
5603 if (importBlock) {
5604 magicString.prepend(importBlock + '\n\n');
5605 }
5606
5607 var module = bundle.entryModule;
5608
5609 var specifiers = module.getExports().filter(notDefault).map(function (name) {
5610 var declaration = module.traceExport(name);
5611
5612 return declaration.name === name ? name : declaration.name + ' as ' + name;
5613 });
5614
5615 var exportBlock = specifiers.length ? 'export { ' + specifiers.join(', ') + ' };' : '';
5616
5617 var defaultExport = module.exports.default || module.reexports.default;
5618 if (defaultExport) {
5619 exportBlock += 'export default ' + module.traceExport('default').name + ';';
5620 }
5621
5622 if (exportBlock) {
5623 magicString.append('\n\n' + exportBlock.trim());
5624 }
5625
5626 return magicString.trim();
5627 }
5628
5629 function cjs(bundle, magicString, _ref, options) {
5630 var exportMode = _ref.exportMode;
5631
5632 var intro = options.useStrict === false ? '' : '\'use strict\';\n\n';
5633
5634 // TODO handle empty imports, once they're supported
5635 var importBlock = bundle.externalModules.map(function (module) {
5636 var requireStatement = 'var ' + module.name + ' = require(\'' + module.id + '\');';
5637
5638 if (module.declarations.default) {
5639 requireStatement += '\n' + (module.exportsNames ? 'var ' + module.name + '__default = ' : module.name + ' = ') + ('\'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';');
5640 }
5641
5642 return requireStatement;
5643 }).join('\n');
5644
5645 if (importBlock) {
5646 intro += importBlock + '\n\n';
5647 }
5648
5649 magicString.prepend(intro);
5650
5651 var exportBlock = getExportBlock(bundle.entryModule, exportMode, 'module.exports =');
5652 if (exportBlock) magicString.append('\n\n' + exportBlock);
5653
5654 return magicString;
5655 }
5656
5657 function amd(bundle, magicString, _ref, options) {
5658 var exportMode = _ref.exportMode;
5659 var indentString = _ref.indentString;
5660
5661 var deps = bundle.externalModules.map(quoteId);
5662 var args = bundle.externalModules.map(getName);
5663
5664 if (exportMode === 'named') {
5665 args.unshift('exports');
5666 deps.unshift('\'exports\'');
5667 }
5668
5669 var params = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (deps.length ? '[' + deps.join(', ') + '], ' : '');
5670
5671 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5672 var intro = 'define(' + params + 'function (' + args.join(', ') + ') {' + useStrict + '\n\n';
5673
5674 // var foo__default = 'default' in foo ? foo['default'] : foo;
5675 var interopBlock = getInteropBlock(bundle);
5676 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5677
5678 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5679 if (exportBlock) magicString.append('\n\n' + exportBlock);
5680
5681 return magicString.indent(indentString).append('\n\n});').prepend(intro);
5682 }
5683
5684 var finalisers = { amd: amd, cjs: cjs, es6: es6, iife: iife, umd: umd };
5685
5686 function ensureArray(thing) {
5687 if (Array.isArray(thing)) return thing;
5688 if (thing == undefined) return [];
5689 return [thing];
5690 }
5691
5692 function load(id) {
5693 return readFileSync(id, 'utf-8');
5694 }
5695
5696 function addJsExtensionIfNecessary(file) {
5697 if (isFile(file)) return file;
5698
5699 file += '.js';
5700 if (isFile(file)) return file;
5701
5702 return null;
5703 }
5704
5705 function resolveId(importee, importer) {
5706 // absolute paths are left untouched
5707 if (isAbsolute(importee)) return addJsExtensionIfNecessary(importee);
5708
5709 // if this is the entry point, resolve against cwd
5710 if (importer === undefined) return addJsExtensionIfNecessary(resolve(process.cwd(), importee));
5711
5712 // external modules are skipped at this stage
5713 if (importee[0] !== '.') return null;
5714
5715 return addJsExtensionIfNecessary(resolve(dirname(importer), importee));
5716 }
5717
5718 function onwarn(msg) {
5719 console.error(msg);
5720 }
5721
5722 function badExports(option, keys) {
5723 throw new Error('\'' + option + '\' was specified for options.exports, but entry module has following exports: ' + keys.join(', '));
5724 }
5725 function getExportMode(bundle, exportMode) {
5726 var exportKeys = keys(bundle.entryModule.exports).concat(keys(bundle.entryModule.reexports)).concat(bundle.entryModule.exportAllSources); // not keys, but makes our job easier this way
5727
5728 if (exportMode === 'default') {
5729 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
5730 badExports('default', exportKeys);
5731 }
5732 } else if (exportMode === 'none' && exportKeys.length) {
5733 badExports('none', exportKeys);
5734 }
5735
5736 if (!exportMode || exportMode === 'auto') {
5737 if (exportKeys.length === 0) {
5738 exportMode = 'none';
5739 } else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
5740 exportMode = 'default';
5741 } else {
5742 exportMode = 'named';
5743 }
5744 }
5745
5746 if (!/(?:default|named|none)/.test(exportMode)) {
5747 throw new Error('options.exports must be \'default\', \'named\', \'none\', \'auto\', or left unspecified (defaults to \'auto\')');
5748 }
5749
5750 return exportMode;
5751 }
5752
5753 function getIndentString(magicString, options) {
5754 if (!('indent' in options) || options.indent === true) {
5755 return magicString.getIndentString();
5756 }
5757
5758 return options.indent || '';
5759 }
5760
5761 function unixizePath(path) {
5762 return path.split(/[\/\\]/).join('/');
5763 }
5764
5765 function transform(source, id, transformers) {
5766 var sourceMapChain = [];
5767
5768 if (typeof source === 'string') {
5769 source = {
5770 code: source,
5771 ast: null
5772 };
5773 }
5774
5775 var originalCode = source.code;
5776 var ast = source.ast;
5777
5778 return transformers.reduce(function (promise, transformer) {
5779 return promise.then(function (previous) {
5780 return Promise.resolve(transformer(previous, id)).then(function (result) {
5781 if (result == null) return previous;
5782
5783 if (typeof result === 'string') {
5784 result = {
5785 code: result,
5786 ast: null,
5787 map: null
5788 };
5789 }
5790
5791 sourceMapChain.push(result.map);
5792 ast = result.ast;
5793
5794 return result.code;
5795 });
5796 });
5797 }, Promise.resolve(source.code)).then(function (code) {
5798 return { code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain };
5799 });
5800 }
5801
5802 var charToInteger$1 = {};
5803 var integerToChar$1 = {};
5804
5805 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach(function (char, i) {
5806 charToInteger$1[char] = i;
5807 integerToChar$1[i] = char;
5808 });
5809
5810 function decode$1(string) {
5811 var result = [],
5812 len = string.length,
5813 i,
5814 hasContinuationBit,
5815 shift = 0,
5816 value = 0,
5817 integer,
5818 shouldNegate;
5819
5820 for (i = 0; i < len; i += 1) {
5821 integer = charToInteger$1[string[i]];
5822
5823 if (integer === undefined) {
5824 throw new Error('Invalid character (' + string[i] + ')');
5825 }
5826
5827 hasContinuationBit = integer & 32;
5828
5829 integer &= 31;
5830 value += integer << shift;
5831
5832 if (hasContinuationBit) {
5833 shift += 5;
5834 } else {
5835 shouldNegate = value & 1;
5836 value >>= 1;
5837
5838 result.push(shouldNegate ? -value : value);
5839
5840 // reset
5841 value = shift = 0;
5842 }
5843 }
5844
5845 return result;
5846 }
5847
5848 function encode$1(value) {
5849 var result, i;
5850
5851 if (typeof value === 'number') {
5852 result = encodeInteger$1(value);
5853 } else {
5854 result = '';
5855 for (i = 0; i < value.length; i += 1) {
5856 result += encodeInteger$1(value[i]);
5857 }
5858 }
5859
5860 return result;
5861 }
5862
5863 function encodeInteger$1(num) {
5864 var result = '',
5865 clamped;
5866
5867 if (num < 0) {
5868 num = -num << 1 | 1;
5869 } else {
5870 num <<= 1;
5871 }
5872
5873 do {
5874 clamped = num & 31;
5875 num >>= 5;
5876
5877 if (num > 0) {
5878 clamped |= 32;
5879 }
5880
5881 result += integerToChar$1[clamped];
5882 } while (num > 0);
5883
5884 return result;
5885 }
5886
5887 function decodeSegments(encodedSegments) {
5888 var i = encodedSegments.length;
5889 var segments = new Array(i);
5890
5891 while (i--) segments[i] = decode$1(encodedSegments[i]);
5892 return segments;
5893 }
5894
5895 //let _uid = 0;
5896
5897 function decode$1$1(mappings) {
5898 var sourceFileIndex = 0; // second field
5899 var sourceCodeLine = 0; // third field
5900 var sourceCodeColumn = 0; // fourth field
5901 var nameIndex = 0; // fifth field
5902
5903 var lines = mappings.split(';');
5904 var numLines = lines.length;
5905 var decoded = new Array(numLines);
5906
5907 var i = undefined;
5908 var j = undefined;
5909 var line = undefined;
5910 var generatedCodeColumn = undefined;
5911 var decodedLine = undefined;
5912 var segments = undefined;
5913 var segment = undefined;
5914 var result = undefined;
5915
5916 for (i = 0; i < numLines; i += 1) {
5917 line = lines[i];
5918
5919 generatedCodeColumn = 0; // first field - reset each time
5920 decodedLine = [];
5921
5922 //if ( _uid++ > 50 ) throw new Error( 'hm' );
5923
5924 segments = decodeSegments(line.split(','));
5925
5926 for (j = 0; j < segments.length; j += 1) {
5927 segment = segments[j];
5928
5929 if (!segment.length) {
5930 break;
5931 }
5932
5933 generatedCodeColumn += segment[0];
5934
5935 result = [generatedCodeColumn];
5936 decodedLine.push(result);
5937
5938 if (segment.length === 1) {
5939 // only one field!
5940 continue;
5941 }
5942
5943 sourceFileIndex += segment[1];
5944 sourceCodeLine += segment[2];
5945 sourceCodeColumn += segment[3];
5946
5947 result.push(sourceFileIndex, sourceCodeLine, sourceCodeColumn);
5948
5949 if (segment.length === 5) {
5950 nameIndex += segment[4];
5951 result.push(nameIndex);
5952 }
5953 }
5954
5955 decoded[i] = decodedLine;
5956 }
5957
5958 return decoded;
5959 }
5960
5961 function encode$1$1(decoded) {
5962 var offsets = {
5963 generatedCodeColumn: 0,
5964 sourceFileIndex: 0, // second field
5965 sourceCodeLine: 0, // third field
5966 sourceCodeColumn: 0, // fourth field
5967 nameIndex: 0 // fifth field
5968 };
5969
5970 return decoded.map(function (line) {
5971 offsets.generatedCodeColumn = 0; // first field - reset each time
5972 return line.map(encodeSegment).join(',');
5973 }).join(';');
5974
5975 function encodeSegment(segment) {
5976 if (!segment.length) {
5977 return segment;
5978 }
5979
5980 var result = new Array(segment.length);
5981
5982 result[0] = segment[0] - offsets.generatedCodeColumn;
5983 offsets.generatedCodeColumn = segment[0];
5984
5985 if (segment.length === 1) {
5986 // only one field!
5987 return encode$1(result);
5988 }
5989
5990 result[1] = segment[1] - offsets.sourceFileIndex;
5991 result[2] = segment[2] - offsets.sourceCodeLine;
5992 result[3] = segment[3] - offsets.sourceCodeColumn;
5993
5994 offsets.sourceFileIndex = segment[1];
5995 offsets.sourceCodeLine = segment[2];
5996 offsets.sourceCodeColumn = segment[3];
5997
5998 if (segment.length === 5) {
5999 result[4] = segment[4] - offsets.nameIndex;
6000 offsets.nameIndex = segment[4];
6001 }
6002
6003 return encode$1(result);
6004 }
6005 }
6006
6007 function traceSegment(loc, mappings) {
6008 var line = loc[0];
6009 var column = loc[1];
6010
6011 var segments = mappings[line];
6012
6013 if (!segments) return null;
6014
6015 for (var i = 0; i < segments.length; i += 1) {
6016 var segment = segments[i];
6017
6018 if (segment[0] > column) return null;
6019
6020 if (segment[0] === column) {
6021 if (segment[1] !== 0) {
6022 throw new Error('Bad sourcemap');
6023 }
6024
6025 return [segment[2], segment[3]];
6026 }
6027 }
6028
6029 return null;
6030 }
6031 function collapseSourcemaps(map, modules) {
6032 var chains = modules.map(function (module) {
6033 return module.sourceMapChain.map(function (map) {
6034 if (!map) throw new Error('Cannot generate a sourcemap if non-sourcemap-generating transformers are used');
6035 return decode$1$1(map.mappings);
6036 });
6037 });
6038
6039 var decodedMappings = decode$1$1(map.mappings);
6040
6041 var tracedMappings = decodedMappings.map(function (line) {
6042 var tracedLine = [];
6043
6044 line.forEach(function (segment) {
6045 var sourceIndex = segment[1];
6046 var sourceCodeLine = segment[2];
6047 var sourceCodeColumn = segment[3];
6048
6049 var chain = chains[sourceIndex];
6050
6051 var i = chain.length;
6052 var traced = [sourceCodeLine, sourceCodeColumn];
6053
6054 while (i-- && traced) {
6055 traced = traceSegment(traced, chain[i]);
6056 }
6057
6058 if (traced) {
6059 tracedLine.push([segment[0], segment[1], traced[0], traced[1]
6060 // TODO name?
6061 ]);
6062 }
6063 });
6064
6065 return tracedLine;
6066 });
6067
6068 map.sourcesContent = modules.map(function (module) {
6069 return module.originalCode;
6070 });
6071 map.mappings = encode$1$1(tracedMappings);
6072 return map;
6073 }
6074
6075 function callIfFunction(thing) {
6076 return typeof thing === 'function' ? thing() : thing;
6077 }
6078
6079 var Bundle = (function () {
6080 function Bundle(options) {
6081 var _this = this;
6082
6083 babelHelpers.classCallCheck(this, Bundle);
6084
6085 this.entry = options.entry;
6086 this.entryModule = null;
6087
6088 this.plugins = ensureArray(options.plugins);
6089
6090 this.resolveId = first$1(this.plugins.map(function (plugin) {
6091 return plugin.resolveId;
6092 }).filter(Boolean).concat(resolveId));
6093
6094 this.load = first$1(this.plugins.map(function (plugin) {
6095 return plugin.load;
6096 }).filter(Boolean).concat(load));
6097
6098 this.transformers = this.plugins.map(function (plugin) {
6099 return plugin.transform;
6100 }).filter(Boolean);
6101
6102 this.pending = blank();
6103 this.moduleById = blank();
6104 this.modules = [];
6105
6106 this.externalModules = [];
6107 this.internalNamespaces = [];
6108
6109 this.assumedGlobals = blank();
6110
6111 this.external = options.external || [];
6112 this.onwarn = options.onwarn || onwarn;
6113
6114 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
6115 ['module', 'exports'].forEach(function (global) {
6116 return _this.assumedGlobals[global] = true;
6117 });
6118 }
6119
6120 Bundle.prototype.build = function build() {
6121 var _this2 = this;
6122
6123 return Promise.resolve(this.resolveId(this.entry, undefined)).then(function (id) {
6124 return _this2.fetchModule(id, undefined);
6125 }).then(function (entryModule) {
6126 _this2.entryModule = entryModule;
6127
6128 _this2.modules.forEach(function (module) {
6129 return module.bindImportSpecifiers();
6130 });
6131 _this2.modules.forEach(function (module) {
6132 return module.bindAliases();
6133 });
6134 _this2.modules.forEach(function (module) {
6135 return module.bindReferences();
6136 });
6137
6138 // mark all export statements
6139 entryModule.getExports().forEach(function (name) {
6140 var declaration = entryModule.traceExport(name);
6141 declaration.isExported = true;
6142
6143 declaration.use();
6144 });
6145
6146 var settled = false;
6147 while (!settled) {
6148 settled = true;
6149
6150 _this2.modules.forEach(function (module) {
6151 if (module.markAllSideEffects()) settled = false;
6152 });
6153 }
6154
6155 _this2.orderedModules = _this2.sort();
6156 _this2.deconflict();
6157 });
6158 };
6159
6160 Bundle.prototype.deconflict = function deconflict() {
6161 var used = blank();
6162
6163 // ensure no conflicts with globals
6164 keys(this.assumedGlobals).forEach(function (name) {
6165 return used[name] = 1;
6166 });
6167
6168 function getSafeName(name) {
6169 while (used[name]) {
6170 name += '$' + used[name]++;
6171 }
6172
6173 used[name] = 1;
6174 return name;
6175 }
6176
6177 this.externalModules.forEach(function (module) {
6178 module.name = getSafeName(module.name);
6179 });
6180
6181 this.modules.forEach(function (module) {
6182 keys(module.declarations).forEach(function (originalName) {
6183 var declaration = module.declarations[originalName];
6184
6185 if (originalName === 'default') {
6186 if (declaration.original && !declaration.original.isReassigned) return;
6187 }
6188
6189 declaration.name = getSafeName(declaration.name);
6190 });
6191 });
6192 };
6193
6194 Bundle.prototype.fetchModule = function fetchModule(id, importer) {
6195 var _this3 = this;
6196
6197 // short-circuit cycles
6198 if (this.pending[id]) return null;
6199 this.pending[id] = true;
6200
6201 return Promise.resolve(this.load(id)).catch(function (err) {
6202 var msg = 'Could not load ' + id;
6203 if (importer) msg += ' (imported by ' + importer + ')';
6204
6205 msg += ': ' + err.message;
6206 throw new Error(msg);
6207 }).then(function (source) {
6208 return transform(source, id, _this3.transformers);
6209 }).then(function (source) {
6210 var code = source.code;
6211 var originalCode = source.originalCode;
6212 var ast = source.ast;
6213 var sourceMapChain = source.sourceMapChain;
6214
6215 var module = new Module({ id: id, code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain, bundle: _this3 });
6216
6217 _this3.modules.push(module);
6218 _this3.moduleById[id] = module;
6219
6220 return _this3.fetchAllDependencies(module).then(function () {
6221 return module;
6222 });
6223 });
6224 };
6225
6226 Bundle.prototype.fetchAllDependencies = function fetchAllDependencies(module) {
6227 var _this4 = this;
6228
6229 var promises = module.dependencies.map(function (source) {
6230 return Promise.resolve(_this4.resolveId(source, module.id)).then(function (resolvedId) {
6231 if (!resolvedId) {
6232 if (! ~_this4.external.indexOf(source)) _this4.onwarn('Treating \'' + source + '\' as external dependency');
6233 module.resolvedIds[source] = source;
6234
6235 if (!_this4.moduleById[source]) {
6236 var _module = new ExternalModule(source);
6237 _this4.externalModules.push(_module);
6238 _this4.moduleById[source] = _module;
6239 }
6240 } else {
6241 if (resolvedId === module.id) {
6242 throw new Error('A module cannot import itself (' + resolvedId + ')');
6243 }
6244
6245 module.resolvedIds[source] = resolvedId;
6246 return _this4.fetchModule(resolvedId, module.id);
6247 }
6248 });
6249 });
6250
6251 return Promise.all(promises);
6252 };
6253
6254 Bundle.prototype.render = function render() {
6255 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
6256
6257 var format = options.format || 'es6';
6258
6259 // Determine export mode - 'default', 'named', 'none'
6260 var exportMode = getExportMode(this, options.exports);
6261
6262 var magicString = new MagicString.Bundle({ separator: '\n\n' });
6263 var usedModules = [];
6264
6265 this.orderedModules.forEach(function (module) {
6266 var source = module.render(format === 'es6');
6267 if (source.toString().length) {
6268 magicString.addSource(source);
6269 usedModules.push(module);
6270 }
6271 });
6272
6273 var intro = [options.intro].concat(this.plugins.map(function (plugin) {
6274 return plugin.intro && plugin.intro();
6275 })).filter(Boolean).join('\n\n');
6276
6277 if (intro) magicString.prepend(intro + '\n');
6278 if (options.outro) magicString.append('\n' + options.outro);
6279
6280 var indentString = getIndentString(magicString, options);
6281
6282 var finalise = finalisers[format];
6283 if (!finalise) throw new Error('You must specify an output type - valid options are ' + keys(finalisers).join(', '));
6284
6285 magicString = finalise(this, magicString.trim(), { exportMode: exportMode, indentString: indentString }, options);
6286
6287 var banner = [options.banner].concat(this.plugins.map(function (plugin) {
6288 return plugin.banner;
6289 })).map(callIfFunction).filter(Boolean).join('\n');
6290
6291 var footer = [options.footer].concat(this.plugins.map(function (plugin) {
6292 return plugin.footer;
6293 })).map(callIfFunction).filter(Boolean).join('\n');
6294
6295 if (banner) magicString.prepend(banner + '\n');
6296 if (footer) magicString.append('\n' + footer);
6297
6298 var code = magicString.toString();
6299 var map = null;
6300
6301 if (options.sourceMap) {
6302 var file = options.sourceMapFile || options.dest;
6303 map = magicString.generateMap({
6304 includeContent: true,
6305 file: file
6306 // TODO
6307 });
6308
6309 if (this.transformers.length) map = collapseSourcemaps(map, usedModules);
6310 map.sources = map.sources.map(unixizePath);
6311 }
6312
6313 return { code: code, map: map };
6314 };
6315
6316 Bundle.prototype.sort = function sort() {
6317 var seen = {};
6318 var ordered = [];
6319 var hasCycles = undefined;
6320
6321 var strongDeps = {};
6322 var stronglyDependsOn = {};
6323
6324 function visit(module) {
6325 if (seen[module.id]) return;
6326 seen[module.id] = true;
6327
6328 var _module$consolidateDependencies = module.consolidateDependencies();
6329
6330 var strongDependencies = _module$consolidateDependencies.strongDependencies;
6331 var weakDependencies = _module$consolidateDependencies.weakDependencies;
6332
6333 strongDeps[module.id] = [];
6334 stronglyDependsOn[module.id] = {};
6335
6336 keys(strongDependencies).forEach(function (id) {
6337 var imported = strongDependencies[id];
6338
6339 strongDeps[module.id].push(imported);
6340
6341 if (seen[id]) {
6342 // we need to prevent an infinite loop, and note that
6343 // we need to check for strong/weak dependency relationships
6344 hasCycles = true;
6345 return;
6346 }
6347
6348 visit(imported);
6349 });
6350
6351 keys(weakDependencies).forEach(function (id) {
6352 var imported = weakDependencies[id];
6353
6354 if (seen[id]) {
6355 // we need to prevent an infinite loop, and note that
6356 // we need to check for strong/weak dependency relationships
6357 hasCycles = true;
6358 return;
6359 }
6360
6361 visit(imported);
6362 });
6363
6364 // add second (and third...) order dependencies
6365 function addStrongDependencies(dependency) {
6366 if (stronglyDependsOn[module.id][dependency.id]) return;
6367
6368 stronglyDependsOn[module.id][dependency.id] = true;
6369 strongDeps[dependency.id].forEach(addStrongDependencies);
6370 }
6371
6372 strongDeps[module.id].forEach(addStrongDependencies);
6373
6374 ordered.push(module);
6375 }
6376
6377 this.modules.forEach(visit);
6378
6379 if (hasCycles) {
6380 var unordered = ordered;
6381 ordered = [];
6382
6383 // unordered is actually semi-ordered, as [ fewer dependencies ... more dependencies ]
6384 unordered.forEach(function (module) {
6385 // ensure strong dependencies of `module` that don't strongly depend on `module` go first
6386 strongDeps[module.id].forEach(place);
6387
6388 function place(dep) {
6389 if (!stronglyDependsOn[dep.id][module.id] && ! ~ordered.indexOf(dep)) {
6390 strongDeps[dep.id].forEach(place);
6391 ordered.push(dep);
6392 }
6393 }
6394
6395 if (! ~ordered.indexOf(module)) {
6396 ordered.push(module);
6397 }
6398 });
6399 }
6400
6401 return ordered;
6402 };
6403
6404 return Bundle;
6405 })();
6406
6407 var VERSION = '0.20.4';
6408
6409 function rollup(options) {
6410 if (!options || !options.entry) {
6411 throw new Error('You must supply options.entry to rollup');
6412 }
6413
6414 if (options.transform || options.load || options.resolveId || options.resolveExternal) {
6415 throw 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');
6416 }
6417
6418 var bundle = new Bundle(options);
6419
6420 return bundle.build().then(function () {
6421 return {
6422 imports: bundle.externalModules.map(function (module) {
6423 return module.id;
6424 }),
6425 exports: keys(bundle.entryModule.exports),
6426 modules: bundle.orderedModules.map(function (module) {
6427 return { id: module.id };
6428 }),
6429
6430 generate: function (options) {
6431 return bundle.render(options);
6432 },
6433 write: function (options) {
6434 if (!options || !options.dest) {
6435 throw new Error('You must supply options.dest to bundle.write');
6436 }
6437
6438 var dest = options.dest;
6439
6440 var _bundle$render = bundle.render(options);
6441
6442 var code = _bundle$render.code;
6443 var map = _bundle$render.map;
6444
6445 var promises = [];
6446
6447 if (options.sourceMap) {
6448 var url = undefined;
6449
6450 if (options.sourceMap === 'inline') {
6451 url = map.toUrl();
6452 } else {
6453 url = _basename(dest) + '.map';
6454 promises.push(writeFile(dest + '.map', map.toString()));
6455 }
6456
6457 code += '\n//# ' + SOURCEMAPPING_URL$1 + '=' + url;
6458 }
6459
6460 promises.push(writeFile(dest, code));
6461 return Promise.all(promises);
6462 }
6463 };
6464 });
6465 }
6466
6467 exports.rollup = rollup;
6468 exports.VERSION = VERSION;
6469
6470}));
6471//# sourceMappingURL=rollup.browser.js.map
\No newline at end of file