UNPKG

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