UNPKG

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