UNPKG

415 kBJavaScriptView Raw
1/*
2 Rollup.js v0.47.4
3 Sun Aug 13 2017 15:16:05 GMT-0400 (EDT) - commit aaca8b581becf5ee5a7fab30bc9c5f4de5d2b935
4
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10
11'use strict';
12
13Object.defineProperty(exports, '__esModule', { value: true });
14
15function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
16
17var path = require('path');
18var path__default = _interopDefault(path);
19var fs = require('fs');
20var EventEmitter = _interopDefault(require('events'));
21var module$1 = _interopDefault(require('module'));
22
23var DEBUG = false;
24var map = new Map;
25
26var timeStartHelper;
27var timeEndHelper;
28
29if ( typeof process === 'undefined' || typeof process.hrtime === 'undefined' ) {
30 timeStartHelper = function timeStartHelper () {
31 return window.performance.now();
32 };
33
34 timeEndHelper = function timeEndHelper ( previous ) {
35 return window.performance.now() - previous;
36 };
37} else {
38 timeStartHelper = function timeStartHelper () {
39 return process.hrtime();
40 };
41
42 timeEndHelper = function timeEndHelper ( previous ) {
43 var hrtime = process.hrtime( previous );
44 return hrtime[0] * 1e3 + Math.floor( hrtime[1] / 1e6 );
45 };
46}
47
48function timeStart ( label ) {
49 if ( !map.has( label ) ) {
50 map.set( label, {
51 time: 0
52 });
53 }
54 map.get( label ).start = timeStartHelper();
55}
56
57function timeEnd ( label ) {
58 if ( map.has( label ) ) {
59 var item = map.get( label );
60 item.time += timeEndHelper( item.start );
61 }
62}
63
64function flushTime ( log ) {
65 if ( log === void 0 ) log = defaultLog;
66
67 for ( var item of map.entries() ) {
68 log( item[0], item[1].time );
69 }
70 map.clear();
71}
72
73function defaultLog ( label, time ) {
74 if ( DEBUG ) {
75 /* eslint-disable no-console */
76 console.info( '%dms: %s', time, label );
77 /* eslint-enable no-console */
78 }
79}
80
81var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
82var relativePath = /^\.?\.\//;
83
84function isAbsolute ( path$$1 ) {
85 return absolutePath.test( path$$1 );
86}
87
88function isRelative ( path$$1 ) {
89 return relativePath.test( path$$1 );
90}
91
92function normalize ( path$$1 ) {
93 return path$$1.replace( /\\/g, '/' );
94}
95
96function mkdirpath ( path$$1 ) {
97 var dir = path.dirname( path$$1 );
98 try {
99 fs.readdirSync( dir );
100 } catch ( err ) {
101 mkdirpath( dir );
102 fs.mkdirSync( dir );
103 }
104}
105
106function writeFile$1 ( dest, data ) {
107 return new Promise( function ( fulfil, reject ) {
108 mkdirpath( dest );
109
110 fs.writeFile( dest, data, function (err) {
111 if ( err ) {
112 reject( err );
113 } else {
114 fulfil();
115 }
116 });
117 });
118}
119
120var keys = Object.keys;
121
122function blank () {
123 return Object.create( null );
124}
125
126function forOwn ( object, func ) {
127 Object.keys( object ).forEach( function (key) { return func( object[ key ], key ); } );
128}
129
130function assign ( target ) {
131 var sources = [], len = arguments.length - 1;
132 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
133
134 sources.forEach( function (source) {
135 for ( var key in source ) {
136 if ( source.hasOwnProperty( key ) ) { target[ key ] = source[ key ]; }
137 }
138 });
139
140 return target;
141}
142
143function mapSequence ( array, fn ) {
144 var results = [];
145 var promise = Promise.resolve();
146
147 function next ( member, i ) {
148 return fn( member ).then( function (value) { return results[i] = value; } );
149 }
150
151 var loop = function ( i ) {
152 promise = promise.then( function () { return next( array[i], i ); } );
153 };
154
155 for ( var i = 0; i < array.length; i += 1 ) loop( i );
156
157 return promise.then( function () { return results; } );
158}
159
160function validateKeys ( actualKeys, allowedKeys ) {
161 var i = actualKeys.length;
162
163 while ( i-- ) {
164 var key = actualKeys[i];
165
166 if ( allowedKeys.indexOf( key ) === -1 ) {
167 return new Error(
168 ("Unexpected key '" + key + "' found, expected one of: " + (allowedKeys.join( ', ' )))
169 );
170 }
171 }
172}
173
174function error ( props ) {
175 // use the same constructor as props (if it's an error object)
176 // so that err.name is preserved etc
177 // (Object.keys below does not update these values because they
178 // are properties on the prototype chain)
179 // basically if props is a SyntaxError it will not be overriden as a generic Error
180 var constructor = (props instanceof Error) ? props.constructor : Error;
181 var err = new constructor( props.message );
182
183 Object.keys( props ).forEach( function (key) {
184 err[ key ] = props[ key ];
185 });
186
187 throw err;
188}
189
190// this looks ridiculous, but it prevents sourcemap tooling from mistaking
191// this for an actual sourceMappingURL
192var SOURCEMAPPING_URL = 'sourceMa';
193SOURCEMAPPING_URL += 'ppingURL';
194
195var SOURCEMAPPING_URL_RE = new RegExp( ("^#\\s+" + SOURCEMAPPING_URL + "=.+\\n?") );
196
197var charToInteger = {};
198var integerToChar = {};
199
200'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
201 charToInteger[ char ] = i;
202 integerToChar[ i ] = char;
203});
204
205function decode$1 ( string ) {
206 var result = [],
207 len = string.length,
208 i,
209 hasContinuationBit,
210 shift = 0,
211 value = 0,
212 integer,
213 shouldNegate;
214
215 for ( i = 0; i < len; i += 1 ) {
216 integer = charToInteger[ string[i] ];
217
218 if ( integer === undefined ) {
219 throw new Error( 'Invalid character (' + string[i] + ')' );
220 }
221
222 hasContinuationBit = integer & 32;
223
224 integer &= 31;
225 value += integer << shift;
226
227 if ( hasContinuationBit ) {
228 shift += 5;
229 } else {
230 shouldNegate = value & 1;
231 value >>= 1;
232
233 result.push( shouldNegate ? -value : value );
234
235 // reset
236 value = shift = 0;
237 }
238 }
239
240 return result;
241}
242
243function encode$1 ( value ) {
244 var result, i;
245
246 if ( typeof value === 'number' ) {
247 result = encodeInteger( value );
248 } else {
249 result = '';
250 for ( i = 0; i < value.length; i += 1 ) {
251 result += encodeInteger( value[i] );
252 }
253 }
254
255 return result;
256}
257
258function encodeInteger ( num ) {
259 var result = '', clamped;
260
261 if ( num < 0 ) {
262 num = ( -num << 1 ) | 1;
263 } else {
264 num <<= 1;
265 }
266
267 do {
268 clamped = num & 31;
269 num >>= 5;
270
271 if ( num > 0 ) {
272 clamped |= 32;
273 }
274
275 result += integerToChar[ clamped ];
276 } while ( num > 0 );
277
278 return result;
279}
280
281function decodeSegments ( encodedSegments ) {
282 var i = encodedSegments.length;
283 var segments = new Array( i );
284
285 while ( i-- ) { segments[i] = decode$1( encodedSegments[i] ); }
286 return segments;
287}
288
289function decode$$1 ( mappings ) {
290 var sourceFileIndex = 0; // second field
291 var sourceCodeLine = 0; // third field
292 var sourceCodeColumn = 0; // fourth field
293 var nameIndex = 0; // fifth field
294
295 var lines = mappings.split( ';' );
296 var numLines = lines.length;
297 var decoded = new Array( numLines );
298
299 var i;
300 var j;
301 var line;
302 var generatedCodeColumn;
303 var decodedLine;
304 var segments;
305 var segment;
306 var result;
307
308 for ( i = 0; i < numLines; i += 1 ) {
309 line = lines[i];
310
311 generatedCodeColumn = 0; // first field - reset each time
312 decodedLine = [];
313
314 segments = decodeSegments( line.split( ',' ) );
315
316 for ( j = 0; j < segments.length; j += 1 ) {
317 segment = segments[j];
318
319 if ( !segment.length ) {
320 break;
321 }
322
323 generatedCodeColumn += segment[0];
324
325 result = [ generatedCodeColumn ];
326 decodedLine.push( result );
327
328 if ( segment.length === 1 ) {
329 // only one field!
330 continue;
331 }
332
333 sourceFileIndex += segment[1];
334 sourceCodeLine += segment[2];
335 sourceCodeColumn += segment[3];
336
337 result.push( sourceFileIndex, sourceCodeLine, sourceCodeColumn );
338
339 if ( segment.length === 5 ) {
340 nameIndex += segment[4];
341 result.push( nameIndex );
342 }
343 }
344
345 decoded[i] = decodedLine;
346 }
347
348 return decoded;
349}
350
351function encode$$1 ( decoded ) {
352 var offsets = {
353 generatedCodeColumn: 0,
354 sourceFileIndex: 0, // second field
355 sourceCodeLine: 0, // third field
356 sourceCodeColumn: 0, // fourth field
357 nameIndex: 0 // fifth field
358 };
359
360 return decoded.map( function (line) {
361 offsets.generatedCodeColumn = 0; // first field - reset each time
362 return line.map( encodeSegment ).join( ',' );
363 }).join( ';' );
364
365 function encodeSegment ( segment ) {
366 if ( !segment.length ) {
367 return segment;
368 }
369
370 var result = new Array( segment.length );
371
372 result[0] = segment[0] - offsets.generatedCodeColumn;
373 offsets.generatedCodeColumn = segment[0];
374
375 if ( segment.length === 1 ) {
376 // only one field!
377 return encode$1( result );
378 }
379
380 result[1] = segment[1] - offsets.sourceFileIndex;
381 result[2] = segment[2] - offsets.sourceCodeLine;
382 result[3] = segment[3] - offsets.sourceCodeColumn;
383
384 offsets.sourceFileIndex = segment[1];
385 offsets.sourceCodeLine = segment[2];
386 offsets.sourceCodeColumn = segment[3];
387
388 if ( segment.length === 5 ) {
389 result[4] = segment[4] - offsets.nameIndex;
390 offsets.nameIndex = segment[4];
391 }
392
393 return encode$1( result );
394 }
395}
396
397var charToInteger$1 = {};
398var integerToChar$1 = {};
399
400'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
401 charToInteger$1[ char ] = i;
402 integerToChar$1[ i ] = char;
403});
404
405
406
407function encode ( value ) {
408 var result;
409
410 if ( typeof value === 'number' ) {
411 result = encodeInteger$1( value );
412 } else {
413 result = '';
414 for ( var i = 0; i < value.length; i += 1 ) {
415 result += encodeInteger$1( value[i] );
416 }
417 }
418
419 return result;
420}
421
422function encodeInteger$1 ( num ) {
423 var result = '';
424
425 if ( num < 0 ) {
426 num = ( -num << 1 ) | 1;
427 } else {
428 num <<= 1;
429 }
430
431 do {
432 var clamped = num & 31;
433 num >>= 5;
434
435 if ( num > 0 ) {
436 clamped |= 32;
437 }
438
439 result += integerToChar$1[ clamped ];
440 } while ( num > 0 );
441
442 return result;
443}
444
445function Chunk ( start, end, content ) {
446 this.start = start;
447 this.end = end;
448 this.original = content;
449
450 this.intro = '';
451 this.outro = '';
452
453 this.content = content;
454 this.storeName = false;
455 this.edited = false;
456
457 // we make these non-enumerable, for sanity while debugging
458 Object.defineProperties( this, {
459 previous: { writable: true, value: null },
460 next: { writable: true, value: null }
461 });
462}
463
464Chunk.prototype = {
465 appendLeft: function appendLeft ( content ) {
466 this.outro += content;
467 },
468
469 appendRight: function appendRight ( content ) {
470 this.intro = this.intro + content;
471 },
472
473 clone: function clone () {
474 var chunk = new Chunk( this.start, this.end, this.original );
475
476 chunk.intro = this.intro;
477 chunk.outro = this.outro;
478 chunk.content = this.content;
479 chunk.storeName = this.storeName;
480 chunk.edited = this.edited;
481
482 return chunk;
483 },
484
485 contains: function contains ( index ) {
486 return this.start < index && index < this.end;
487 },
488
489 eachNext: function eachNext ( fn ) {
490 var chunk = this;
491 while ( chunk ) {
492 fn( chunk );
493 chunk = chunk.next;
494 }
495 },
496
497 eachPrevious: function eachPrevious ( fn ) {
498 var chunk = this;
499 while ( chunk ) {
500 fn( chunk );
501 chunk = chunk.previous;
502 }
503 },
504
505 edit: function edit ( content, storeName, contentOnly ) {
506 this.content = content;
507 if ( !contentOnly ) {
508 this.intro = '';
509 this.outro = '';
510 }
511 this.storeName = storeName;
512
513 this.edited = true;
514
515 return this;
516 },
517
518 prependLeft: function prependLeft ( content ) {
519 this.outro = content + this.outro;
520 },
521
522 prependRight: function prependRight ( content ) {
523 this.intro = content + this.intro;
524 },
525
526 split: function split ( index ) {
527 var sliceIndex = index - this.start;
528
529 var originalBefore = this.original.slice( 0, sliceIndex );
530 var originalAfter = this.original.slice( sliceIndex );
531
532 this.original = originalBefore;
533
534 var newChunk = new Chunk( index, this.end, originalAfter );
535 newChunk.outro = this.outro;
536 this.outro = '';
537
538 this.end = index;
539
540 if ( this.edited ) {
541 // TODO is this block necessary?...
542 newChunk.edit( '', false );
543 this.content = '';
544 } else {
545 this.content = originalBefore;
546 }
547
548 newChunk.next = this.next;
549 if ( newChunk.next ) { newChunk.next.previous = newChunk; }
550 newChunk.previous = this;
551 this.next = newChunk;
552
553 return newChunk;
554 },
555
556 toString: function toString () {
557 return this.intro + this.content + this.outro;
558 },
559
560 trimEnd: function trimEnd ( rx ) {
561 this.outro = this.outro.replace( rx, '' );
562 if ( this.outro.length ) { return true; }
563
564 var trimmed = this.content.replace( rx, '' );
565
566 if ( trimmed.length ) {
567 if ( trimmed !== this.content ) {
568 this.split( this.start + trimmed.length ).edit( '', false );
569 }
570
571 return true;
572 } else {
573 this.edit( '', false );
574
575 this.intro = this.intro.replace( rx, '' );
576 if ( this.intro.length ) { return true; }
577 }
578 },
579
580 trimStart: function trimStart ( rx ) {
581 this.intro = this.intro.replace( rx, '' );
582 if ( this.intro.length ) { return true; }
583
584 var trimmed = this.content.replace( rx, '' );
585
586 if ( trimmed.length ) {
587 if ( trimmed !== this.content ) {
588 this.split( this.end - trimmed.length );
589 this.edit( '', false );
590 }
591
592 return true;
593 } else {
594 this.edit( '', false );
595
596 this.outro = this.outro.replace( rx, '' );
597 if ( this.outro.length ) { return true; }
598 }
599 }
600};
601
602var _btoa;
603
604if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) {
605 _btoa = window.btoa;
606} else if ( typeof Buffer === 'function' ) {
607 _btoa = function (str) { return new Buffer( str ).toString( 'base64' ); };
608} else {
609 _btoa = function () {
610 throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' );
611 };
612}
613
614var btoa = _btoa;
615
616function SourceMap ( properties ) {
617 this.version = 3;
618
619 this.file = properties.file;
620 this.sources = properties.sources;
621 this.sourcesContent = properties.sourcesContent;
622 this.names = properties.names;
623 this.mappings = properties.mappings;
624}
625
626SourceMap.prototype = {
627 toString: function toString () {
628 return JSON.stringify( this );
629 },
630
631 toUrl: function toUrl () {
632 return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() );
633 }
634};
635
636function guessIndent ( code ) {
637 var lines = code.split( '\n' );
638
639 var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } );
640 var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } );
641
642 if ( tabbed.length === 0 && spaced.length === 0 ) {
643 return null;
644 }
645
646 // More lines tabbed than spaced? Assume tabs, and
647 // default to tabs in the case of a tie (or nothing
648 // to go on)
649 if ( tabbed.length >= spaced.length ) {
650 return '\t';
651 }
652
653 // Otherwise, we need to guess the multiple
654 var min = spaced.reduce( function ( previous, current ) {
655 var numSpaces = /^ +/.exec( current )[0].length;
656 return Math.min( numSpaces, previous );
657 }, Infinity );
658
659 return new Array( min + 1 ).join( ' ' );
660}
661
662function getRelativePath ( from, to ) {
663 var fromParts = from.split( /[\/\\]/ );
664 var toParts = to.split( /[\/\\]/ );
665
666 fromParts.pop(); // get dirname
667
668 while ( fromParts[0] === toParts[0] ) {
669 fromParts.shift();
670 toParts.shift();
671 }
672
673 if ( fromParts.length ) {
674 var i = fromParts.length;
675 while ( i-- ) { fromParts[i] = '..'; }
676 }
677
678 return fromParts.concat( toParts ).join( '/' );
679}
680
681var toString$1 = Object.prototype.toString;
682
683function isObject ( thing ) {
684 return toString$1.call( thing ) === '[object Object]';
685}
686
687function getLocator ( source ) {
688 var originalLines = source.split( '\n' );
689
690 var start = 0;
691 var lineRanges = originalLines.map( function ( line, i ) {
692 var end = start + line.length + 1;
693 var range = { start: start, end: end, line: i };
694
695 start = end;
696 return range;
697 });
698
699 var i = 0;
700
701 function rangeContains ( range, index ) {
702 return range.start <= index && index < range.end;
703 }
704
705 function getLocation ( range, index ) {
706 return { line: range.line, column: index - range.start };
707 }
708
709 return function locate ( index ) {
710 var range = lineRanges[i];
711
712 var d = index >= range.end ? 1 : -1;
713
714 while ( range ) {
715 if ( rangeContains( range, index ) ) { return getLocation( range, index ); }
716
717 i += d;
718 range = lineRanges[i];
719 }
720 };
721}
722
723function Mappings ( hires ) {
724 var this$1 = this;
725
726 var offsets = {
727 generatedCodeColumn: 0,
728 sourceIndex: 0,
729 sourceCodeLine: 0,
730 sourceCodeColumn: 0,
731 sourceCodeName: 0
732 };
733
734 var generatedCodeLine = 0;
735 var generatedCodeColumn = 0;
736
737 this.raw = [];
738 var rawSegments = this.raw[ generatedCodeLine ] = [];
739
740 var pending = null;
741
742 this.addEdit = function ( sourceIndex, content, original, loc, nameIndex ) {
743 if ( content.length ) {
744 rawSegments.push([
745 generatedCodeColumn,
746 sourceIndex,
747 loc.line,
748 loc.column,
749 nameIndex ]);
750 } else if ( pending ) {
751 rawSegments.push( pending );
752 }
753
754 this$1.advance( content );
755 pending = null;
756 };
757
758 this.addUneditedChunk = function ( sourceIndex, chunk, original, loc, sourcemapLocations ) {
759 var originalCharIndex = chunk.start;
760 var first = true;
761
762 while ( originalCharIndex < chunk.end ) {
763 if ( hires || first || sourcemapLocations[ originalCharIndex ] ) {
764 rawSegments.push([
765 generatedCodeColumn,
766 sourceIndex,
767 loc.line,
768 loc.column,
769 -1
770 ]);
771 }
772
773 if ( original[ originalCharIndex ] === '\n' ) {
774 loc.line += 1;
775 loc.column = 0;
776 generatedCodeLine += 1;
777 this$1.raw[ generatedCodeLine ] = rawSegments = [];
778 generatedCodeColumn = 0;
779 } else {
780 loc.column += 1;
781 generatedCodeColumn += 1;
782 }
783
784 originalCharIndex += 1;
785 first = false;
786 }
787
788 pending = [
789 generatedCodeColumn,
790 sourceIndex,
791 loc.line,
792 loc.column,
793 -1 ];
794 };
795
796 this.advance = function (str) {
797 if ( !str ) { return; }
798
799 var lines = str.split( '\n' );
800 var lastLine = lines.pop();
801
802 if ( lines.length ) {
803 generatedCodeLine += lines.length;
804 this$1.raw[ generatedCodeLine ] = rawSegments = [];
805 generatedCodeColumn = lastLine.length;
806 } else {
807 generatedCodeColumn += lastLine.length;
808 }
809 };
810
811 this.encode = function () {
812 return this$1.raw.map( function (segments) {
813 var generatedCodeColumn = 0;
814
815 return segments.map( function (segment) {
816 var arr = [
817 segment[0] - generatedCodeColumn,
818 segment[1] - offsets.sourceIndex,
819 segment[2] - offsets.sourceCodeLine,
820 segment[3] - offsets.sourceCodeColumn
821 ];
822
823 generatedCodeColumn = segment[0];
824 offsets.sourceIndex = segment[1];
825 offsets.sourceCodeLine = segment[2];
826 offsets.sourceCodeColumn = segment[3];
827
828 if ( ~segment[4] ) {
829 arr.push( segment[4] - offsets.sourceCodeName );
830 offsets.sourceCodeName = segment[4];
831 }
832
833 return encode( arr );
834 }).join( ',' );
835 }).join( ';' );
836 };
837}
838
839var Stats = function Stats () {
840 Object.defineProperties( this, {
841 startTimes: { value: {} }
842 });
843};
844
845Stats.prototype.time = function time ( label ) {
846 this.startTimes[ label ] = process.hrtime();
847};
848
849Stats.prototype.timeEnd = function timeEnd ( label ) {
850 var elapsed = process.hrtime( this.startTimes[ label ] );
851
852 if ( !this[ label ] ) { this[ label ] = 0; }
853 this[ label ] += elapsed[0] * 1e3 + elapsed[1] * 1e-6;
854};
855
856var warned = {
857 insertLeft: false,
858 insertRight: false,
859 storeName: false
860};
861
862function MagicString$1 ( string, options ) {
863 if ( options === void 0 ) options = {};
864
865 var chunk = new Chunk( 0, string.length, string );
866
867 Object.defineProperties( this, {
868 original: { writable: true, value: string },
869 outro: { writable: true, value: '' },
870 intro: { writable: true, value: '' },
871 firstChunk: { writable: true, value: chunk },
872 lastChunk: { writable: true, value: chunk },
873 lastSearchedChunk: { writable: true, value: chunk },
874 byStart: { writable: true, value: {} },
875 byEnd: { writable: true, value: {} },
876 filename: { writable: true, value: options.filename },
877 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
878 sourcemapLocations: { writable: true, value: {} },
879 storedNames: { writable: true, value: {} },
880 indentStr: { writable: true, value: guessIndent( string ) }
881 });
882
883 this.byStart[ 0 ] = chunk;
884 this.byEnd[ string.length ] = chunk;
885}
886
887MagicString$1.prototype = {
888 addSourcemapLocation: function addSourcemapLocation ( char ) {
889 this.sourcemapLocations[ char ] = true;
890 },
891
892 append: function append ( content ) {
893 if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
894
895 this.outro += content;
896 return this;
897 },
898
899 appendLeft: function appendLeft ( index, content ) {
900 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
901
902 this._split( index );
903
904 var chunk = this.byEnd[ index ];
905
906 if ( chunk ) {
907 chunk.appendLeft( content );
908 } else {
909 this.intro += content;
910 }
911
912 return this;
913 },
914
915 appendRight: function appendRight ( index, content ) {
916 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
917
918 this._split( index );
919
920 var chunk = this.byStart[ index ];
921
922 if ( chunk ) {
923 chunk.appendRight( content );
924 } else {
925 this.outro += content;
926 }
927
928 return this;
929 },
930
931 clone: function clone () {
932 var cloned = new MagicString$1( this.original, { filename: this.filename });
933
934 var originalChunk = this.firstChunk;
935 var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
936
937 while ( originalChunk ) {
938 cloned.byStart[ clonedChunk.start ] = clonedChunk;
939 cloned.byEnd[ clonedChunk.end ] = clonedChunk;
940
941 var nextOriginalChunk = originalChunk.next;
942 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
943
944 if ( nextClonedChunk ) {
945 clonedChunk.next = nextClonedChunk;
946 nextClonedChunk.previous = clonedChunk;
947
948 clonedChunk = nextClonedChunk;
949 }
950
951 originalChunk = nextOriginalChunk;
952 }
953
954 cloned.lastChunk = clonedChunk;
955
956 if ( this.indentExclusionRanges ) {
957 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
958 }
959
960 Object.keys( this.sourcemapLocations ).forEach( function (loc) {
961 cloned.sourcemapLocations[ loc ] = true;
962 });
963
964 return cloned;
965 },
966
967 generateMap: function generateMap ( options ) {
968 var this$1 = this;
969
970 options = options || {};
971
972 var sourceIndex = 0;
973 var names = Object.keys( this.storedNames );
974 var mappings = new Mappings( options.hires );
975
976 var locate = getLocator( this.original );
977
978 if ( this.intro ) {
979 mappings.advance( this.intro );
980 }
981
982 this.firstChunk.eachNext( function (chunk) {
983 var loc = locate( chunk.start );
984
985 if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
986
987 if ( chunk.edited ) {
988 mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
989 } else {
990 mappings.addUneditedChunk( sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations );
991 }
992
993 if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
994 });
995
996 var map = new SourceMap({
997 file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
998 sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ],
999 sourcesContent: options.includeContent ? [ this.original ] : [ null ],
1000 names: names,
1001 mappings: mappings.encode()
1002 });
1003 return map;
1004 },
1005
1006 getIndentString: function getIndentString () {
1007 return this.indentStr === null ? '\t' : this.indentStr;
1008 },
1009
1010 indent: function indent ( indentStr, options ) {
1011 var this$1 = this;
1012
1013 var pattern = /^[^\r\n]/gm;
1014
1015 if ( isObject( indentStr ) ) {
1016 options = indentStr;
1017 indentStr = undefined;
1018 }
1019
1020 indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' );
1021
1022 if ( indentStr === '' ) { return this; } // noop
1023
1024 options = options || {};
1025
1026 // Process exclusion ranges
1027 var isExcluded = {};
1028
1029 if ( options.exclude ) {
1030 var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude;
1031 exclusions.forEach( function (exclusion) {
1032 for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) {
1033 isExcluded[i] = true;
1034 }
1035 });
1036 }
1037
1038 var shouldIndentNextCharacter = options.indentStart !== false;
1039 var replacer = function (match) {
1040 if ( shouldIndentNextCharacter ) { return ("" + indentStr + match); }
1041 shouldIndentNextCharacter = true;
1042 return match;
1043 };
1044
1045 this.intro = this.intro.replace( pattern, replacer );
1046
1047 var charIndex = 0;
1048
1049 var chunk = this.firstChunk;
1050
1051 while ( chunk ) {
1052 var end = chunk.end;
1053
1054 if ( chunk.edited ) {
1055 if ( !isExcluded[ charIndex ] ) {
1056 chunk.content = chunk.content.replace( pattern, replacer );
1057
1058 if ( chunk.content.length ) {
1059 shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n';
1060 }
1061 }
1062 } else {
1063 charIndex = chunk.start;
1064
1065 while ( charIndex < end ) {
1066 if ( !isExcluded[ charIndex ] ) {
1067 var char = this$1.original[ charIndex ];
1068
1069 if ( char === '\n' ) {
1070 shouldIndentNextCharacter = true;
1071 } else if ( char !== '\r' && shouldIndentNextCharacter ) {
1072 shouldIndentNextCharacter = false;
1073
1074 if ( charIndex === chunk.start ) {
1075 chunk.prependRight( indentStr );
1076 } else {
1077 this$1._splitChunk( chunk, charIndex );
1078 chunk = chunk.next;
1079 chunk.prependRight( indentStr );
1080 }
1081 }
1082 }
1083
1084 charIndex += 1;
1085 }
1086 }
1087
1088 charIndex = chunk.end;
1089 chunk = chunk.next;
1090 }
1091
1092 this.outro = this.outro.replace( pattern, replacer );
1093
1094 return this;
1095 },
1096
1097 insert: function insert () {
1098 throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' );
1099 },
1100
1101 insertLeft: function insertLeft ( index, content ) {
1102 if ( !warned.insertLeft ) {
1103 console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console
1104 warned.insertLeft = true;
1105 }
1106
1107 return this.appendLeft( index, content );
1108 },
1109
1110 insertRight: function insertRight ( index, content ) {
1111 if ( !warned.insertRight ) {
1112 console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console
1113 warned.insertRight = true;
1114 }
1115
1116 return this.prependRight( index, content );
1117 },
1118
1119 move: function move ( start, end, index ) {
1120 if ( index >= start && index <= end ) { throw new Error( 'Cannot move a selection inside itself' ); }
1121
1122 this._split( start );
1123 this._split( end );
1124 this._split( index );
1125
1126 var first = this.byStart[ start ];
1127 var last = this.byEnd[ end ];
1128
1129 var oldLeft = first.previous;
1130 var oldRight = last.next;
1131
1132 var newRight = this.byStart[ index ];
1133 if ( !newRight && last === this.lastChunk ) { return this; }
1134 var newLeft = newRight ? newRight.previous : this.lastChunk;
1135
1136 if ( oldLeft ) { oldLeft.next = oldRight; }
1137 if ( oldRight ) { oldRight.previous = oldLeft; }
1138
1139 if ( newLeft ) { newLeft.next = first; }
1140 if ( newRight ) { newRight.previous = last; }
1141
1142 if ( !first.previous ) { this.firstChunk = last.next; }
1143 if ( !last.next ) {
1144 this.lastChunk = first.previous;
1145 this.lastChunk.next = null;
1146 }
1147
1148 first.previous = newLeft;
1149 last.next = newRight || null;
1150
1151 if ( !newLeft ) { this.firstChunk = first; }
1152 if ( !newRight ) { this.lastChunk = last; }
1153
1154 return this;
1155 },
1156
1157 overwrite: function overwrite ( start, end, content, options ) {
1158 var this$1 = this;
1159
1160 if ( typeof content !== 'string' ) { throw new TypeError( 'replacement content must be a string' ); }
1161
1162 while ( start < 0 ) { start += this$1.original.length; }
1163 while ( end < 0 ) { end += this$1.original.length; }
1164
1165 if ( end > this.original.length ) { throw new Error( 'end is out of bounds' ); }
1166 if ( start === end ) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); }
1167
1168 this._split( start );
1169 this._split( end );
1170
1171 if ( options === true ) {
1172 if ( !warned.storeName ) {
1173 console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console
1174 warned.storeName = true;
1175 }
1176
1177 options = { storeName: true };
1178 }
1179 var storeName = options !== undefined ? options.storeName : false;
1180 var contentOnly = options !== undefined ? options.contentOnly : false;
1181
1182 if ( storeName ) {
1183 var original = this.original.slice( start, end );
1184 this.storedNames[ original ] = true;
1185 }
1186
1187 var first = this.byStart[ start ];
1188 var last = this.byEnd[ end ];
1189
1190 if ( first ) {
1191 if ( end > first.end && first.next !== this.byStart[ first.end ] ) {
1192 throw new Error( 'Cannot overwrite across a split point' );
1193 }
1194
1195 first.edit( content, storeName, contentOnly );
1196
1197 if ( first !== last ) {
1198 var chunk = first.next;
1199 while ( chunk !== last ) {
1200 chunk.edit( '', false );
1201 chunk = chunk.next;
1202 }
1203
1204 chunk.edit( '', false );
1205 }
1206 }
1207
1208 else {
1209 // must be inserting at the end
1210 var newChunk = new Chunk( start, end, '' ).edit( content, storeName );
1211
1212 // TODO last chunk in the array may not be the last chunk, if it's moved...
1213 last.next = newChunk;
1214 newChunk.previous = last;
1215 }
1216
1217 return this;
1218 },
1219
1220 prepend: function prepend ( content ) {
1221 if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
1222
1223 this.intro = content + this.intro;
1224 return this;
1225 },
1226
1227 prependLeft: function prependLeft ( index, content ) {
1228 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
1229
1230 this._split( index );
1231
1232 var chunk = this.byEnd[ index ];
1233
1234 if ( chunk ) {
1235 chunk.prependLeft( content );
1236 } else {
1237 this.intro = content + this.intro;
1238 }
1239
1240 return this;
1241 },
1242
1243 prependRight: function prependRight ( index, content ) {
1244 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
1245
1246 this._split( index );
1247
1248 var chunk = this.byStart[ index ];
1249
1250 if ( chunk ) {
1251 chunk.prependRight( content );
1252 } else {
1253 this.outro = content + this.outro;
1254 }
1255
1256 return this;
1257 },
1258
1259 remove: function remove ( start, end ) {
1260 var this$1 = this;
1261
1262 while ( start < 0 ) { start += this$1.original.length; }
1263 while ( end < 0 ) { end += this$1.original.length; }
1264
1265 if ( start === end ) { return this; }
1266
1267 if ( start < 0 || end > this.original.length ) { throw new Error( 'Character is out of bounds' ); }
1268 if ( start > end ) { throw new Error( 'end must be greater than start' ); }
1269
1270 this._split( start );
1271 this._split( end );
1272
1273 var chunk = this.byStart[ start ];
1274
1275 while ( chunk ) {
1276 chunk.intro = '';
1277 chunk.outro = '';
1278 chunk.edit( '' );
1279
1280 chunk = end > chunk.end ? this$1.byStart[ chunk.end ] : null;
1281 }
1282
1283 return this;
1284 },
1285
1286 slice: function slice ( start, end ) {
1287 var this$1 = this;
1288 if ( start === void 0 ) start = 0;
1289 if ( end === void 0 ) end = this.original.length;
1290
1291 while ( start < 0 ) { start += this$1.original.length; }
1292 while ( end < 0 ) { end += this$1.original.length; }
1293
1294 var result = '';
1295
1296 // find start chunk
1297 var chunk = this.firstChunk;
1298 while ( chunk && ( chunk.start > start || chunk.end <= start ) ) {
1299
1300 // found end chunk before start
1301 if ( chunk.start < end && chunk.end >= end ) {
1302 return result;
1303 }
1304
1305 chunk = chunk.next;
1306 }
1307
1308 if ( chunk && chunk.edited && chunk.start !== start ) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1309
1310 var startChunk = chunk;
1311 while ( chunk ) {
1312 if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) {
1313 result += chunk.intro;
1314 }
1315
1316 var containsEnd = chunk.start < end && chunk.end >= end;
1317 if ( containsEnd && chunk.edited && chunk.end !== end ) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1318
1319 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1320 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1321
1322 result += chunk.content.slice( sliceStart, sliceEnd );
1323
1324 if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) {
1325 result += chunk.outro;
1326 }
1327
1328 if ( containsEnd ) {
1329 break;
1330 }
1331
1332 chunk = chunk.next;
1333 }
1334
1335 return result;
1336 },
1337
1338 // TODO deprecate this? not really very useful
1339 snip: function snip ( start, end ) {
1340 var clone = this.clone();
1341 clone.remove( 0, start );
1342 clone.remove( end, clone.original.length );
1343
1344 return clone;
1345 },
1346
1347 _split: function _split ( index ) {
1348 var this$1 = this;
1349
1350 if ( this.byStart[ index ] || this.byEnd[ index ] ) { return; }
1351
1352 var chunk = this.lastSearchedChunk;
1353 var searchForward = index > chunk.end;
1354
1355 while ( true ) {
1356 if ( chunk.contains( index ) ) { return this$1._splitChunk( chunk, index ); }
1357
1358 chunk = searchForward ?
1359 this$1.byStart[ chunk.end ] :
1360 this$1.byEnd[ chunk.start ];
1361 }
1362 },
1363
1364 _splitChunk: function _splitChunk ( chunk, index ) {
1365 if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements)
1366 var loc = getLocator( this.original )( index );
1367 throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") );
1368 }
1369
1370 var newChunk = chunk.split( index );
1371
1372 this.byEnd[ index ] = chunk;
1373 this.byStart[ index ] = newChunk;
1374 this.byEnd[ newChunk.end ] = newChunk;
1375
1376 if ( chunk === this.lastChunk ) { this.lastChunk = newChunk; }
1377
1378 this.lastSearchedChunk = chunk;
1379 return true;
1380 },
1381
1382 toString: function toString () {
1383 var str = this.intro;
1384
1385 var chunk = this.firstChunk;
1386 while ( chunk ) {
1387 str += chunk.toString();
1388 chunk = chunk.next;
1389 }
1390
1391 return str + this.outro;
1392 },
1393
1394 trimLines: function trimLines () {
1395 return this.trim('[\\r\\n]');
1396 },
1397
1398 trim: function trim ( charType ) {
1399 return this.trimStart( charType ).trimEnd( charType );
1400 },
1401
1402 trimEnd: function trimEnd ( charType ) {
1403 var this$1 = this;
1404
1405 var rx = new RegExp( ( charType || '\\s' ) + '+$' );
1406
1407 this.outro = this.outro.replace( rx, '' );
1408 if ( this.outro.length ) { return this; }
1409
1410 var chunk = this.lastChunk;
1411
1412 do {
1413 var end = chunk.end;
1414 var aborted = chunk.trimEnd( rx );
1415
1416 // if chunk was trimmed, we have a new lastChunk
1417 if ( chunk.end !== end ) {
1418 if ( this$1.lastChunk === chunk ) {
1419 this$1.lastChunk = chunk.next;
1420 }
1421
1422 this$1.byEnd[ chunk.end ] = chunk;
1423 this$1.byStart[ chunk.next.start ] = chunk.next;
1424 this$1.byEnd[ chunk.next.end ] = chunk.next;
1425 }
1426
1427 if ( aborted ) { return this$1; }
1428 chunk = chunk.previous;
1429 } while ( chunk );
1430
1431 return this;
1432 },
1433
1434 trimStart: function trimStart ( charType ) {
1435 var this$1 = this;
1436
1437 var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
1438
1439 this.intro = this.intro.replace( rx, '' );
1440 if ( this.intro.length ) { return this; }
1441
1442 var chunk = this.firstChunk;
1443
1444 do {
1445 var end = chunk.end;
1446 var aborted = chunk.trimStart( rx );
1447
1448 if ( chunk.end !== end ) {
1449 // special case...
1450 if ( chunk === this$1.lastChunk ) { this$1.lastChunk = chunk.next; }
1451
1452 this$1.byEnd[ chunk.end ] = chunk;
1453 this$1.byStart[ chunk.next.start ] = chunk.next;
1454 this$1.byEnd[ chunk.next.end ] = chunk.next;
1455 }
1456
1457 if ( aborted ) { return this$1; }
1458 chunk = chunk.next;
1459 } while ( chunk );
1460
1461 return this;
1462 }
1463};
1464
1465var hasOwnProp = Object.prototype.hasOwnProperty;
1466
1467function Bundle$2 ( options ) {
1468 if ( options === void 0 ) options = {};
1469
1470 this.intro = options.intro || '';
1471 this.separator = options.separator !== undefined ? options.separator : '\n';
1472
1473 this.sources = [];
1474
1475 this.uniqueSources = [];
1476 this.uniqueSourceIndexByFilename = {};
1477}
1478
1479Bundle$2.prototype = {
1480 addSource: function addSource ( source ) {
1481 if ( source instanceof MagicString$1 ) {
1482 return this.addSource({
1483 content: source,
1484 filename: source.filename,
1485 separator: this.separator
1486 });
1487 }
1488
1489 if ( !isObject( source ) || !source.content ) {
1490 throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' );
1491 }
1492
1493 [ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) {
1494 if ( !hasOwnProp.call( source, option ) ) { source[ option ] = source.content[ option ]; }
1495 });
1496
1497 if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up
1498 source.separator = this.separator;
1499 }
1500
1501 if ( source.filename ) {
1502 if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) {
1503 this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length;
1504 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1505 } else {
1506 var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ];
1507 if ( source.content.original !== uniqueSource.content ) {
1508 throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") );
1509 }
1510 }
1511 }
1512
1513 this.sources.push( source );
1514 return this;
1515 },
1516
1517 append: function append ( str, options ) {
1518 this.addSource({
1519 content: new MagicString$1( str ),
1520 separator: ( options && options.separator ) || ''
1521 });
1522
1523 return this;
1524 },
1525
1526 clone: function clone () {
1527 var bundle = new Bundle$2({
1528 intro: this.intro,
1529 separator: this.separator
1530 });
1531
1532 this.sources.forEach( function (source) {
1533 bundle.addSource({
1534 filename: source.filename,
1535 content: source.content.clone(),
1536 separator: source.separator
1537 });
1538 });
1539
1540 return bundle;
1541 },
1542
1543 generateMap: function generateMap ( options ) {
1544 var this$1 = this;
1545 if ( options === void 0 ) options = {};
1546
1547 var names = [];
1548 this.sources.forEach( function (source) {
1549 Object.keys( source.content.storedNames ).forEach( function (name) {
1550 if ( !~names.indexOf( name ) ) { names.push( name ); }
1551 });
1552 });
1553
1554 var mappings = new Mappings( options.hires );
1555
1556 if ( this.intro ) {
1557 mappings.advance( this.intro );
1558 }
1559
1560 this.sources.forEach( function ( source, i ) {
1561 if ( i > 0 ) {
1562 mappings.advance( this$1.separator );
1563 }
1564
1565 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[ source.filename ] : -1;
1566 var magicString = source.content;
1567 var locate = getLocator( magicString.original );
1568
1569 if ( magicString.intro ) {
1570 mappings.advance( magicString.intro );
1571 }
1572
1573 magicString.firstChunk.eachNext( function (chunk) {
1574 var loc = locate( chunk.start );
1575
1576 if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
1577
1578 if ( source.filename ) {
1579 if ( chunk.edited ) {
1580 mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
1581 } else {
1582 mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations );
1583 }
1584 }
1585
1586 else {
1587 mappings.advance( chunk.content );
1588 }
1589
1590 if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
1591 });
1592
1593 if ( magicString.outro ) {
1594 mappings.advance( magicString.outro );
1595 }
1596 });
1597
1598 return new SourceMap({
1599 file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
1600 sources: this.uniqueSources.map( function (source) {
1601 return options.file ? getRelativePath( options.file, source.filename ) : source.filename;
1602 }),
1603 sourcesContent: this.uniqueSources.map( function (source) {
1604 return options.includeContent ? source.content : null;
1605 }),
1606 names: names,
1607 mappings: mappings.encode()
1608 });
1609 },
1610
1611 getIndentString: function getIndentString () {
1612 var indentStringCounts = {};
1613
1614 this.sources.forEach( function (source) {
1615 var indentStr = source.content.indentStr;
1616
1617 if ( indentStr === null ) { return; }
1618
1619 if ( !indentStringCounts[ indentStr ] ) { indentStringCounts[ indentStr ] = 0; }
1620 indentStringCounts[ indentStr ] += 1;
1621 });
1622
1623 return ( Object.keys( indentStringCounts ).sort( function ( a, b ) {
1624 return indentStringCounts[a] - indentStringCounts[b];
1625 })[0] ) || '\t';
1626 },
1627
1628 indent: function indent ( indentStr ) {
1629 var this$1 = this;
1630
1631 if ( !arguments.length ) {
1632 indentStr = this.getIndentString();
1633 }
1634
1635 if ( indentStr === '' ) { return this; } // noop
1636
1637 var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n';
1638
1639 this.sources.forEach( function ( source, i ) {
1640 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1641 var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) );
1642
1643 source.content.indent( indentStr, {
1644 exclude: source.indentExclusionRanges,
1645 indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1646 });
1647
1648 // TODO this is a very slow way to determine this
1649 trailingNewline = source.content.toString().slice( 0, -1 ) === '\n';
1650 });
1651
1652 if ( this.intro ) {
1653 this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) {
1654 return index > 0 ? indentStr + match : match;
1655 });
1656 }
1657
1658 return this;
1659 },
1660
1661 prepend: function prepend ( str ) {
1662 this.intro = str + this.intro;
1663 return this;
1664 },
1665
1666 toString: function toString () {
1667 var this$1 = this;
1668
1669 var body = this.sources.map( function ( source, i ) {
1670 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1671 var str = ( i > 0 ? separator : '' ) + source.content.toString();
1672
1673 return str;
1674 }).join( '' );
1675
1676 return this.intro + body;
1677 },
1678
1679 trimLines: function trimLines () {
1680 return this.trim('[\\r\\n]');
1681 },
1682
1683 trim: function trim ( charType ) {
1684 return this.trimStart( charType ).trimEnd( charType );
1685 },
1686
1687 trimStart: function trimStart ( charType ) {
1688 var this$1 = this;
1689
1690 var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
1691 this.intro = this.intro.replace( rx, '' );
1692
1693 if ( !this.intro ) {
1694 var source;
1695 var i = 0;
1696
1697 do {
1698 source = this$1.sources[i];
1699
1700 if ( !source ) {
1701 break;
1702 }
1703
1704 source.content.trimStart( charType );
1705 i += 1;
1706 } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
1707 }
1708
1709 return this;
1710 },
1711
1712 trimEnd: function trimEnd ( charType ) {
1713 var this$1 = this;
1714
1715 var rx = new RegExp( ( charType || '\\s' ) + '+$' );
1716
1717 var source;
1718 var i = this.sources.length - 1;
1719
1720 do {
1721 source = this$1.sources[i];
1722
1723 if ( !source ) {
1724 this$1.intro = this$1.intro.replace( rx, '' );
1725 break;
1726 }
1727
1728 source.content.trimEnd( charType );
1729 i -= 1;
1730 } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
1731
1732 return this;
1733 }
1734};
1735
1736// Return the first non-falsy result from an array of
1737// maybe-sync, maybe-promise-returning functions
1738function first ( candidates ) {
1739 return function () {
1740 var args = [], len = arguments.length;
1741 while ( len-- ) args[ len ] = arguments[ len ];
1742
1743 return candidates.reduce( function ( promise, candidate ) {
1744 return promise.then( function (result) { return result != null ?
1745 result :
1746 Promise.resolve( candidate.apply( void 0, args ) ); } );
1747 }, Promise.resolve() );
1748 };
1749}
1750
1751function find ( array, fn ) {
1752 for ( var i = 0; i < array.length; i += 1 ) {
1753 if ( fn( array[i], i ) ) { return array[i]; }
1754 }
1755
1756 return null;
1757}
1758
1759// Reserved word lists for various dialects of the language
1760
1761var reservedWords = {
1762 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",
1763 5: "class enum extends super const export import",
1764 6: "enum",
1765 strict: "implements interface let package private protected public static yield",
1766 strictBind: "eval arguments"
1767};
1768
1769// And the keywords
1770
1771var 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";
1772
1773var keywords = {
1774 5: ecma5AndLessKeywords,
1775 6: ecma5AndLessKeywords + " const class extends export import super"
1776};
1777
1778// ## Character categories
1779
1780// Big ugly regular expressions that match characters in the
1781// whitespace, identifier, and identifier-start categories. These
1782// are only applied when a character is found to actually have a
1783// code point above 128.
1784// Generated by `bin/generate-identifier-regex.js`.
1785
1786var 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-\u08b4\u08b6-\u08bd\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\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\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-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\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-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\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-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
1787var 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\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\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\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\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\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-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
1788
1789var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1790var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1791
1792nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1793
1794// These are a run-length and offset encoded representation of the
1795// >0xffff code points that are a valid part of identifiers. The
1796// offset starts at 0x10000, and each pair of numbers represents an
1797// offset to the next range, and then a size of the range. They were
1798// generated by bin/generate-identifier-regex.js
1799
1800// eslint-disable-next-line comma-spacing
1801var 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,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,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,60,67,1213,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,3,5761,10591,541];
1802
1803// eslint-disable-next-line comma-spacing
1804var 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,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,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,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239];
1805
1806// This has a complexity linear to the value of the code. The
1807// assumption is that looking up astral identifier characters is
1808// rare.
1809function isInAstralSet(code, set) {
1810 var pos = 0x10000;
1811 for (var i = 0; i < set.length; i += 2) {
1812 pos += set[i];
1813 if (pos > code) { return false }
1814 pos += set[i + 1];
1815 if (pos >= code) { return true }
1816 }
1817}
1818
1819// Test whether a given character code starts an identifier.
1820
1821function isIdentifierStart(code, astral) {
1822 if (code < 65) { return code === 36 }
1823 if (code < 91) { return true }
1824 if (code < 97) { return code === 95 }
1825 if (code < 123) { return true }
1826 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
1827 if (astral === false) { return false }
1828 return isInAstralSet(code, astralIdentifierStartCodes)
1829}
1830
1831// Test whether a given character is part of an identifier.
1832
1833function isIdentifierChar(code, astral) {
1834 if (code < 48) { return code === 36 }
1835 if (code < 58) { return true }
1836 if (code < 65) { return false }
1837 if (code < 91) { return true }
1838 if (code < 97) { return code === 95 }
1839 if (code < 123) { return true }
1840 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
1841 if (astral === false) { return false }
1842 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
1843}
1844
1845// ## Token types
1846
1847// The assignment of fine-grained, information-carrying type objects
1848// allows the tokenizer to store the information it has about a
1849// token in a way that is very cheap for the parser to look up.
1850
1851// All token type variables start with an underscore, to make them
1852// easy to recognize.
1853
1854// The `beforeExpr` property is used to disambiguate between regular
1855// expressions and divisions. It is set on all token types that can
1856// be followed by an expression (thus, a slash after them would be a
1857// regular expression).
1858//
1859// The `startsExpr` property is used to check if the token ends a
1860// `yield` expression. It is set on all token types that either can
1861// directly start an expression (like a quotation mark) or can
1862// continue an expression (like the body of a string).
1863//
1864// `isLoop` marks a keyword as starting a loop, which is important
1865// to know when parsing a label, in order to allow or disallow
1866// continue jumps to that label.
1867
1868var TokenType = function TokenType(label, conf) {
1869 if ( conf === void 0 ) { conf = {}; }
1870
1871 this.label = label;
1872 this.keyword = conf.keyword;
1873 this.beforeExpr = !!conf.beforeExpr;
1874 this.startsExpr = !!conf.startsExpr;
1875 this.isLoop = !!conf.isLoop;
1876 this.isAssign = !!conf.isAssign;
1877 this.prefix = !!conf.prefix;
1878 this.postfix = !!conf.postfix;
1879 this.binop = conf.binop || null;
1880 this.updateContext = null;
1881};
1882
1883function binop(name, prec) {
1884 return new TokenType(name, {beforeExpr: true, binop: prec})
1885}
1886var beforeExpr = {beforeExpr: true};
1887var startsExpr = {startsExpr: true};
1888
1889// Map keyword names to token types.
1890
1891var keywords$1 = {};
1892
1893// Succinct definitions of keyword token types
1894function kw(name, options) {
1895 if ( options === void 0 ) { options = {}; }
1896
1897 options.keyword = name;
1898 return keywords$1[name] = new TokenType(name, options)
1899}
1900
1901var types = {
1902 num: new TokenType("num", startsExpr),
1903 regexp: new TokenType("regexp", startsExpr),
1904 string: new TokenType("string", startsExpr),
1905 name: new TokenType("name", startsExpr),
1906 eof: new TokenType("eof"),
1907
1908 // Punctuation token types.
1909 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
1910 bracketR: new TokenType("]"),
1911 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
1912 braceR: new TokenType("}"),
1913 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
1914 parenR: new TokenType(")"),
1915 comma: new TokenType(",", beforeExpr),
1916 semi: new TokenType(";", beforeExpr),
1917 colon: new TokenType(":", beforeExpr),
1918 dot: new TokenType("."),
1919 question: new TokenType("?", beforeExpr),
1920 arrow: new TokenType("=>", beforeExpr),
1921 template: new TokenType("template"),
1922 invalidTemplate: new TokenType("invalidTemplate"),
1923 ellipsis: new TokenType("...", beforeExpr),
1924 backQuote: new TokenType("`", startsExpr),
1925 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
1926
1927 // Operators. These carry several kinds of properties to help the
1928 // parser use them properly (the presence of these properties is
1929 // what categorizes them as operators).
1930 //
1931 // `binop`, when present, specifies that this operator is a binary
1932 // operator, and will refer to its precedence.
1933 //
1934 // `prefix` and `postfix` mark the operator as a prefix or postfix
1935 // unary operator.
1936 //
1937 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1938 // binary operators with a very low precedence, that should result
1939 // in AssignmentExpression nodes.
1940
1941 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
1942 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
1943 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
1944 prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
1945 logicalOR: binop("||", 1),
1946 logicalAND: binop("&&", 2),
1947 bitwiseOR: binop("|", 3),
1948 bitwiseXOR: binop("^", 4),
1949 bitwiseAND: binop("&", 5),
1950 equality: binop("==/!=", 6),
1951 relational: binop("</>", 7),
1952 bitShift: binop("<</>>", 8),
1953 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
1954 modulo: binop("%", 10),
1955 star: binop("*", 10),
1956 slash: binop("/", 10),
1957 starstar: new TokenType("**", {beforeExpr: true}),
1958
1959 // Keyword token types.
1960 _break: kw("break"),
1961 _case: kw("case", beforeExpr),
1962 _catch: kw("catch"),
1963 _continue: kw("continue"),
1964 _debugger: kw("debugger"),
1965 _default: kw("default", beforeExpr),
1966 _do: kw("do", {isLoop: true, beforeExpr: true}),
1967 _else: kw("else", beforeExpr),
1968 _finally: kw("finally"),
1969 _for: kw("for", {isLoop: true}),
1970 _function: kw("function", startsExpr),
1971 _if: kw("if"),
1972 _return: kw("return", beforeExpr),
1973 _switch: kw("switch"),
1974 _throw: kw("throw", beforeExpr),
1975 _try: kw("try"),
1976 _var: kw("var"),
1977 _const: kw("const"),
1978 _while: kw("while", {isLoop: true}),
1979 _with: kw("with"),
1980 _new: kw("new", {beforeExpr: true, startsExpr: true}),
1981 _this: kw("this", startsExpr),
1982 _super: kw("super", startsExpr),
1983 _class: kw("class", startsExpr),
1984 _extends: kw("extends", beforeExpr),
1985 _export: kw("export"),
1986 _import: kw("import"),
1987 _null: kw("null", startsExpr),
1988 _true: kw("true", startsExpr),
1989 _false: kw("false", startsExpr),
1990 _in: kw("in", {beforeExpr: true, binop: 7}),
1991 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
1992 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
1993 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
1994 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
1995};
1996
1997// Matches a whole line break (where CRLF is considered a single
1998// line break). Used to count lines.
1999
2000var lineBreak = /\r\n?|\n|\u2028|\u2029/;
2001var lineBreakG = new RegExp(lineBreak.source, "g");
2002
2003function isNewLine(code) {
2004 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
2005}
2006
2007var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
2008
2009var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
2010
2011var ref = Object.prototype;
2012var hasOwnProperty = ref.hasOwnProperty;
2013var toString = ref.toString;
2014
2015// Checks if an object has a property.
2016
2017function has(obj, propName) {
2018 return hasOwnProperty.call(obj, propName)
2019}
2020
2021var isArray = Array.isArray || (function (obj) { return (
2022 toString.call(obj) === "[object Array]"
2023); });
2024
2025// These are used when `options.locations` is on, for the
2026// `startLoc` and `endLoc` properties.
2027
2028var Position = function Position(line, col) {
2029 this.line = line;
2030 this.column = col;
2031};
2032
2033Position.prototype.offset = function offset (n) {
2034 return new Position(this.line, this.column + n)
2035};
2036
2037var SourceLocation = function SourceLocation(p, start, end) {
2038 this.start = start;
2039 this.end = end;
2040 if (p.sourceFile !== null) { this.source = p.sourceFile; }
2041};
2042
2043// The `getLineInfo` function is mostly useful when the
2044// `locations` option is off (for performance reasons) and you
2045// want to find the line/column position for a given character
2046// offset. `input` should be the code string that the offset refers
2047// into.
2048
2049function getLineInfo(input, offset) {
2050 for (var line = 1, cur = 0;;) {
2051 lineBreakG.lastIndex = cur;
2052 var match = lineBreakG.exec(input);
2053 if (match && match.index < offset) {
2054 ++line;
2055 cur = match.index + match[0].length;
2056 } else {
2057 return new Position(line, offset - cur)
2058 }
2059 }
2060}
2061
2062// A second optional argument can be given to further configure
2063// the parser process. These options are recognized:
2064
2065var defaultOptions = {
2066 // `ecmaVersion` indicates the ECMAScript version to parse. Must
2067 // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
2068 // for strict mode, the set of reserved words, and support for
2069 // new syntax features. The default is 7.
2070 ecmaVersion: 7,
2071 // `sourceType` indicates the mode the code should be parsed in.
2072 // Can be either `"script"` or `"module"`. This influences global
2073 // strict mode and parsing of `import` and `export` declarations.
2074 sourceType: "script",
2075 // `onInsertedSemicolon` can be a callback that will be called
2076 // when a semicolon is automatically inserted. It will be passed
2077 // th position of the comma as an offset, and if `locations` is
2078 // enabled, it is given the location as a `{line, column}` object
2079 // as second argument.
2080 onInsertedSemicolon: null,
2081 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
2082 // trailing commas.
2083 onTrailingComma: null,
2084 // By default, reserved words are only enforced if ecmaVersion >= 5.
2085 // Set `allowReserved` to a boolean value to explicitly turn this on
2086 // an off. When this option has the value "never", reserved words
2087 // and keywords can also not be used as property names.
2088 allowReserved: null,
2089 // When enabled, a return at the top level is not considered an
2090 // error.
2091 allowReturnOutsideFunction: false,
2092 // When enabled, import/export statements are not constrained to
2093 // appearing at the top of the program.
2094 allowImportExportEverywhere: false,
2095 // When enabled, hashbang directive in the beginning of file
2096 // is allowed and treated as a line comment.
2097 allowHashBang: false,
2098 // When `locations` is on, `loc` properties holding objects with
2099 // `start` and `end` properties in `{line, column}` form (with
2100 // line being 1-based and column 0-based) will be attached to the
2101 // nodes.
2102 locations: false,
2103 // A function can be passed as `onToken` option, which will
2104 // cause Acorn to call that function with object in the same
2105 // format as tokens returned from `tokenizer().getToken()`. Note
2106 // that you are not allowed to call the parser from the
2107 // callback—that will corrupt its internal state.
2108 onToken: null,
2109 // A function can be passed as `onComment` option, which will
2110 // cause Acorn to call that function with `(block, text, start,
2111 // end)` parameters whenever a comment is skipped. `block` is a
2112 // boolean indicating whether this is a block (`/* */`) comment,
2113 // `text` is the content of the comment, and `start` and `end` are
2114 // character offsets that denote the start and end of the comment.
2115 // When the `locations` option is on, two more parameters are
2116 // passed, the full `{line, column}` locations of the start and
2117 // end of the comments. Note that you are not allowed to call the
2118 // parser from the callback—that will corrupt its internal state.
2119 onComment: null,
2120 // Nodes have their start and end characters offsets recorded in
2121 // `start` and `end` properties (directly on the node, rather than
2122 // the `loc` object, which holds line/column data. To also add a
2123 // [semi-standardized][range] `range` property holding a `[start,
2124 // end]` array with the same numbers, set the `ranges` option to
2125 // `true`.
2126 //
2127 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
2128 ranges: false,
2129 // It is possible to parse multiple files into a single AST by
2130 // passing the tree produced by parsing the first file as
2131 // `program` option in subsequent parses. This will add the
2132 // toplevel forms of the parsed file to the `Program` (top) node
2133 // of an existing parse tree.
2134 program: null,
2135 // When `locations` is on, you can pass this to record the source
2136 // file in every node's `loc` object.
2137 sourceFile: null,
2138 // This value, if given, is stored in every node, whether
2139 // `locations` is on or off.
2140 directSourceFile: null,
2141 // When enabled, parenthesized expressions are represented by
2142 // (non-standard) ParenthesizedExpression nodes
2143 preserveParens: false,
2144 plugins: {}
2145};
2146
2147// Interpret and default an options object
2148
2149function getOptions(opts) {
2150 var options = {};
2151
2152 for (var opt in defaultOptions)
2153 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
2154
2155 if (options.ecmaVersion >= 2015)
2156 { options.ecmaVersion -= 2009; }
2157
2158 if (options.allowReserved == null)
2159 { options.allowReserved = options.ecmaVersion < 5; }
2160
2161 if (isArray(options.onToken)) {
2162 var tokens = options.onToken;
2163 options.onToken = function (token) { return tokens.push(token); };
2164 }
2165 if (isArray(options.onComment))
2166 { options.onComment = pushComment(options, options.onComment); }
2167
2168 return options
2169}
2170
2171function pushComment(options, array) {
2172 return function(block, text, start, end, startLoc, endLoc) {
2173 var comment = {
2174 type: block ? "Block" : "Line",
2175 value: text,
2176 start: start,
2177 end: end
2178 };
2179 if (options.locations)
2180 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
2181 if (options.ranges)
2182 { comment.range = [start, end]; }
2183 array.push(comment);
2184 }
2185}
2186
2187// Registered plugins
2188var plugins = {};
2189
2190function keywordRegexp(words) {
2191 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
2192}
2193
2194var Parser = function Parser(options, input, startPos) {
2195 this.options = options = getOptions(options);
2196 this.sourceFile = options.sourceFile;
2197 this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
2198 var reserved = "";
2199 if (!options.allowReserved) {
2200 for (var v = options.ecmaVersion;; v--)
2201 { if (reserved = reservedWords[v]) { break } }
2202 if (options.sourceType == "module") { reserved += " await"; }
2203 }
2204 this.reservedWords = keywordRegexp(reserved);
2205 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
2206 this.reservedWordsStrict = keywordRegexp(reservedStrict);
2207 this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind);
2208 this.input = String(input);
2209
2210 // Used to signal to callers of `readWord1` whether the word
2211 // contained any escape sequences. This is needed because words with
2212 // escape sequences must not be interpreted as keywords.
2213 this.containsEsc = false;
2214
2215 // Load plugins
2216 this.loadPlugins(options.plugins);
2217
2218 // Set up token state
2219
2220 // The current position of the tokenizer in the input.
2221 if (startPos) {
2222 this.pos = startPos;
2223 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
2224 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
2225 } else {
2226 this.pos = this.lineStart = 0;
2227 this.curLine = 1;
2228 }
2229
2230 // Properties of the current token:
2231 // Its type
2232 this.type = types.eof;
2233 // For tokens that include more information than their type, the value
2234 this.value = null;
2235 // Its start and end offset
2236 this.start = this.end = this.pos;
2237 // And, if locations are used, the {line, column} object
2238 // corresponding to those offsets
2239 this.startLoc = this.endLoc = this.curPosition();
2240
2241 // Position information for the previous token
2242 this.lastTokEndLoc = this.lastTokStartLoc = null;
2243 this.lastTokStart = this.lastTokEnd = this.pos;
2244
2245 // The context stack is used to superficially track syntactic
2246 // context to predict whether a regular expression is allowed in a
2247 // given position.
2248 this.context = this.initialContext();
2249 this.exprAllowed = true;
2250
2251 // Figure out if it's a module code.
2252 this.inModule = options.sourceType === "module";
2253 this.strict = this.inModule || this.strictDirective(this.pos);
2254
2255 // Used to signify the start of a potential arrow function
2256 this.potentialArrowAt = -1;
2257
2258 // Flags to track whether we are in a function, a generator, an async function.
2259 this.inFunction = this.inGenerator = this.inAsync = false;
2260 // Positions to delayed-check that yield/await does not exist in default parameters.
2261 this.yieldPos = this.awaitPos = 0;
2262 // Labels in scope.
2263 this.labels = [];
2264
2265 // If enabled, skip leading hashbang line.
2266 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
2267 { this.skipLineComment(2); }
2268
2269 // Scope tracking for duplicate variable names (see scope.js)
2270 this.scopeStack = [];
2271 this.enterFunctionScope();
2272};
2273
2274// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
2275Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
2276Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
2277
2278Parser.prototype.extend = function extend (name, f) {
2279 this[name] = f(this[name]);
2280};
2281
2282Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
2283 var this$1 = this;
2284
2285 for (var name in pluginConfigs) {
2286 var plugin = plugins[name];
2287 if (!plugin) { throw new Error("Plugin '" + name + "' not found") }
2288 plugin(this$1, pluginConfigs[name]);
2289 }
2290};
2291
2292Parser.prototype.parse = function parse () {
2293 var node = this.options.program || this.startNode();
2294 this.nextToken();
2295 return this.parseTopLevel(node)
2296};
2297
2298var pp = Parser.prototype;
2299
2300// ## Parser utilities
2301
2302var literal = /^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/;
2303pp.strictDirective = function(start) {
2304 var this$1 = this;
2305
2306 for (;;) {
2307 skipWhiteSpace.lastIndex = start;
2308 start += skipWhiteSpace.exec(this$1.input)[0].length;
2309 var match = literal.exec(this$1.input.slice(start));
2310 if (!match) { return false }
2311 if ((match[1] || match[2]) == "use strict") { return true }
2312 start += match[0].length;
2313 }
2314};
2315
2316// Predicate that tests whether the next token is of the given
2317// type, and if yes, consumes it as a side effect.
2318
2319pp.eat = function(type) {
2320 if (this.type === type) {
2321 this.next();
2322 return true
2323 } else {
2324 return false
2325 }
2326};
2327
2328// Tests whether parsed token is a contextual keyword.
2329
2330pp.isContextual = function(name) {
2331 return this.type === types.name && this.value === name
2332};
2333
2334// Consumes contextual keyword if possible.
2335
2336pp.eatContextual = function(name) {
2337 return this.value === name && this.eat(types.name)
2338};
2339
2340// Asserts that following token is given contextual keyword.
2341
2342pp.expectContextual = function(name) {
2343 if (!this.eatContextual(name)) { this.unexpected(); }
2344};
2345
2346// Test whether a semicolon can be inserted at the current position.
2347
2348pp.canInsertSemicolon = function() {
2349 return this.type === types.eof ||
2350 this.type === types.braceR ||
2351 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
2352};
2353
2354pp.insertSemicolon = function() {
2355 if (this.canInsertSemicolon()) {
2356 if (this.options.onInsertedSemicolon)
2357 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
2358 return true
2359 }
2360};
2361
2362// Consume a semicolon, or, failing that, see if we are allowed to
2363// pretend that there is a semicolon at this position.
2364
2365pp.semicolon = function() {
2366 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
2367};
2368
2369pp.afterTrailingComma = function(tokType, notNext) {
2370 if (this.type == tokType) {
2371 if (this.options.onTrailingComma)
2372 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
2373 if (!notNext)
2374 { this.next(); }
2375 return true
2376 }
2377};
2378
2379// Expect a token of a given type. If found, consume it, otherwise,
2380// raise an unexpected token error.
2381
2382pp.expect = function(type) {
2383 this.eat(type) || this.unexpected();
2384};
2385
2386// Raise an unexpected token error.
2387
2388pp.unexpected = function(pos) {
2389 this.raise(pos != null ? pos : this.start, "Unexpected token");
2390};
2391
2392function DestructuringErrors() {
2393 this.shorthandAssign =
2394 this.trailingComma =
2395 this.parenthesizedAssign =
2396 this.parenthesizedBind =
2397 -1;
2398}
2399
2400pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
2401 if (!refDestructuringErrors) { return }
2402 if (refDestructuringErrors.trailingComma > -1)
2403 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
2404 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
2405 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
2406};
2407
2408pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
2409 var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1;
2410 if (!andThrow) { return pos >= 0 }
2411 if (pos > -1) { this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); }
2412};
2413
2414pp.checkYieldAwaitInDefaultParams = function() {
2415 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
2416 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
2417 if (this.awaitPos)
2418 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
2419};
2420
2421pp.isSimpleAssignTarget = function(expr) {
2422 if (expr.type === "ParenthesizedExpression")
2423 { return this.isSimpleAssignTarget(expr.expression) }
2424 return expr.type === "Identifier" || expr.type === "MemberExpression"
2425};
2426
2427var pp$1 = Parser.prototype;
2428
2429// ### Statement parsing
2430
2431// Parse a program. Initializes the parser, reads any number of
2432// statements, and wraps them in a Program node. Optionally takes a
2433// `program` argument. If present, the statements will be appended
2434// to its body instead of creating a new node.
2435
2436pp$1.parseTopLevel = function(node) {
2437 var this$1 = this;
2438
2439 var exports = {};
2440 if (!node.body) { node.body = []; }
2441 while (this.type !== types.eof) {
2442 var stmt = this$1.parseStatement(true, true, exports);
2443 node.body.push(stmt);
2444 }
2445 this.next();
2446 if (this.options.ecmaVersion >= 6) {
2447 node.sourceType = this.options.sourceType;
2448 }
2449 return this.finishNode(node, "Program")
2450};
2451
2452var loopLabel = {kind: "loop"};
2453var switchLabel = {kind: "switch"};
2454
2455pp$1.isLet = function() {
2456 if (this.type !== types.name || this.options.ecmaVersion < 6 || this.value != "let") { return false }
2457 skipWhiteSpace.lastIndex = this.pos;
2458 var skip = skipWhiteSpace.exec(this.input);
2459 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
2460 if (nextCh === 91 || nextCh == 123) { return true } // '{' and '['
2461 if (isIdentifierStart(nextCh, true)) {
2462 var pos = next + 1;
2463 while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
2464 var ident = this.input.slice(next, pos);
2465 if (!this.isKeyword(ident)) { return true }
2466 }
2467 return false
2468};
2469
2470// check 'async [no LineTerminator here] function'
2471// - 'async /*foo*/ function' is OK.
2472// - 'async /*\n*/ function' is invalid.
2473pp$1.isAsyncFunction = function() {
2474 if (this.type !== types.name || this.options.ecmaVersion < 8 || this.value != "async")
2475 { return false }
2476
2477 skipWhiteSpace.lastIndex = this.pos;
2478 var skip = skipWhiteSpace.exec(this.input);
2479 var next = this.pos + skip[0].length;
2480 return !lineBreak.test(this.input.slice(this.pos, next)) &&
2481 this.input.slice(next, next + 8) === "function" &&
2482 (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
2483};
2484
2485// Parse a single statement.
2486//
2487// If expecting a statement and finding a slash operator, parse a
2488// regular expression literal. This is to handle cases like
2489// `if (foo) /blah/.exec(foo)`, where looking at the previous token
2490// does not help.
2491
2492pp$1.parseStatement = function(declaration, topLevel, exports) {
2493 var starttype = this.type, node = this.startNode(), kind;
2494
2495 if (this.isLet()) {
2496 starttype = types._var;
2497 kind = "let";
2498 }
2499
2500 // Most types of statements are recognized by the keyword they
2501 // start with. Many are trivial to parse, some require a bit of
2502 // complexity.
2503
2504 switch (starttype) {
2505 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
2506 case types._debugger: return this.parseDebuggerStatement(node)
2507 case types._do: return this.parseDoStatement(node)
2508 case types._for: return this.parseForStatement(node)
2509 case types._function:
2510 if (!declaration && this.options.ecmaVersion >= 6) { this.unexpected(); }
2511 return this.parseFunctionStatement(node, false)
2512 case types._class:
2513 if (!declaration) { this.unexpected(); }
2514 return this.parseClass(node, true)
2515 case types._if: return this.parseIfStatement(node)
2516 case types._return: return this.parseReturnStatement(node)
2517 case types._switch: return this.parseSwitchStatement(node)
2518 case types._throw: return this.parseThrowStatement(node)
2519 case types._try: return this.parseTryStatement(node)
2520 case types._const: case types._var:
2521 kind = kind || this.value;
2522 if (!declaration && kind != "var") { this.unexpected(); }
2523 return this.parseVarStatement(node, kind)
2524 case types._while: return this.parseWhileStatement(node)
2525 case types._with: return this.parseWithStatement(node)
2526 case types.braceL: return this.parseBlock()
2527 case types.semi: return this.parseEmptyStatement(node)
2528 case types._export:
2529 case types._import:
2530 if (!this.options.allowImportExportEverywhere) {
2531 if (!topLevel)
2532 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
2533 if (!this.inModule)
2534 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
2535 }
2536 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
2537
2538 // If the statement does not start with a statement keyword or a
2539 // brace, it's an ExpressionStatement or LabeledStatement. We
2540 // simply start parsing an expression, and afterwards, if the
2541 // next token is a colon and the expression was a simple
2542 // Identifier node, we switch to interpreting it as a label.
2543 default:
2544 if (this.isAsyncFunction() && declaration) {
2545 this.next();
2546 return this.parseFunctionStatement(node, true)
2547 }
2548
2549 var maybeName = this.value, expr = this.parseExpression();
2550 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
2551 { return this.parseLabeledStatement(node, maybeName, expr) }
2552 else { return this.parseExpressionStatement(node, expr) }
2553 }
2554};
2555
2556pp$1.parseBreakContinueStatement = function(node, keyword) {
2557 var this$1 = this;
2558
2559 var isBreak = keyword == "break";
2560 this.next();
2561 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
2562 else if (this.type !== types.name) { this.unexpected(); }
2563 else {
2564 node.label = this.parseIdent();
2565 this.semicolon();
2566 }
2567
2568 // Verify that there is an actual destination to break or
2569 // continue to.
2570 var i = 0;
2571 for (; i < this.labels.length; ++i) {
2572 var lab = this$1.labels[i];
2573 if (node.label == null || lab.name === node.label.name) {
2574 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
2575 if (node.label && isBreak) { break }
2576 }
2577 }
2578 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
2579 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
2580};
2581
2582pp$1.parseDebuggerStatement = function(node) {
2583 this.next();
2584 this.semicolon();
2585 return this.finishNode(node, "DebuggerStatement")
2586};
2587
2588pp$1.parseDoStatement = function(node) {
2589 this.next();
2590 this.labels.push(loopLabel);
2591 node.body = this.parseStatement(false);
2592 this.labels.pop();
2593 this.expect(types._while);
2594 node.test = this.parseParenExpression();
2595 if (this.options.ecmaVersion >= 6)
2596 { this.eat(types.semi); }
2597 else
2598 { this.semicolon(); }
2599 return this.finishNode(node, "DoWhileStatement")
2600};
2601
2602// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
2603// loop is non-trivial. Basically, we have to parse the init `var`
2604// statement or expression, disallowing the `in` operator (see
2605// the second parameter to `parseExpression`), and then check
2606// whether the next token is `in` or `of`. When there is no init
2607// part (semicolon immediately after the opening parenthesis), it
2608// is a regular `for` loop.
2609
2610pp$1.parseForStatement = function(node) {
2611 this.next();
2612 this.labels.push(loopLabel);
2613 this.enterLexicalScope();
2614 this.expect(types.parenL);
2615 if (this.type === types.semi) { return this.parseFor(node, null) }
2616 var isLet = this.isLet();
2617 if (this.type === types._var || this.type === types._const || isLet) {
2618 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
2619 this.next();
2620 this.parseVar(init$1, true, kind);
2621 this.finishNode(init$1, "VariableDeclaration");
2622 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
2623 !(kind !== "var" && init$1.declarations[0].init))
2624 { return this.parseForIn(node, init$1) }
2625 return this.parseFor(node, init$1)
2626 }
2627 var refDestructuringErrors = new DestructuringErrors;
2628 var init = this.parseExpression(true, refDestructuringErrors);
2629 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
2630 this.toAssignable(init);
2631 this.checkLVal(init);
2632 this.checkPatternErrors(refDestructuringErrors, true);
2633 return this.parseForIn(node, init)
2634 } else {
2635 this.checkExpressionErrors(refDestructuringErrors, true);
2636 }
2637 return this.parseFor(node, init)
2638};
2639
2640pp$1.parseFunctionStatement = function(node, isAsync) {
2641 this.next();
2642 return this.parseFunction(node, true, false, isAsync)
2643};
2644
2645pp$1.isFunction = function() {
2646 return this.type === types._function || this.isAsyncFunction()
2647};
2648
2649pp$1.parseIfStatement = function(node) {
2650 this.next();
2651 node.test = this.parseParenExpression();
2652 // allow function declarations in branches, but only in non-strict mode
2653 node.consequent = this.parseStatement(!this.strict && this.isFunction());
2654 node.alternate = this.eat(types._else) ? this.parseStatement(!this.strict && this.isFunction()) : null;
2655 return this.finishNode(node, "IfStatement")
2656};
2657
2658pp$1.parseReturnStatement = function(node) {
2659 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
2660 { this.raise(this.start, "'return' outside of function"); }
2661 this.next();
2662
2663 // In `return` (and `break`/`continue`), the keywords with
2664 // optional arguments, we eagerly look for a semicolon or the
2665 // possibility to insert one.
2666
2667 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
2668 else { node.argument = this.parseExpression(); this.semicolon(); }
2669 return this.finishNode(node, "ReturnStatement")
2670};
2671
2672pp$1.parseSwitchStatement = function(node) {
2673 var this$1 = this;
2674
2675 this.next();
2676 node.discriminant = this.parseParenExpression();
2677 node.cases = [];
2678 this.expect(types.braceL);
2679 this.labels.push(switchLabel);
2680 this.enterLexicalScope();
2681
2682 // Statements under must be grouped (by label) in SwitchCase
2683 // nodes. `cur` is used to keep the node that we are currently
2684 // adding statements to.
2685
2686 var cur;
2687 for (var sawDefault = false; this.type != types.braceR;) {
2688 if (this$1.type === types._case || this$1.type === types._default) {
2689 var isCase = this$1.type === types._case;
2690 if (cur) { this$1.finishNode(cur, "SwitchCase"); }
2691 node.cases.push(cur = this$1.startNode());
2692 cur.consequent = [];
2693 this$1.next();
2694 if (isCase) {
2695 cur.test = this$1.parseExpression();
2696 } else {
2697 if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); }
2698 sawDefault = true;
2699 cur.test = null;
2700 }
2701 this$1.expect(types.colon);
2702 } else {
2703 if (!cur) { this$1.unexpected(); }
2704 cur.consequent.push(this$1.parseStatement(true));
2705 }
2706 }
2707 this.exitLexicalScope();
2708 if (cur) { this.finishNode(cur, "SwitchCase"); }
2709 this.next(); // Closing brace
2710 this.labels.pop();
2711 return this.finishNode(node, "SwitchStatement")
2712};
2713
2714pp$1.parseThrowStatement = function(node) {
2715 this.next();
2716 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
2717 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
2718 node.argument = this.parseExpression();
2719 this.semicolon();
2720 return this.finishNode(node, "ThrowStatement")
2721};
2722
2723// Reused empty array added for node fields that are always empty.
2724
2725var empty = [];
2726
2727pp$1.parseTryStatement = function(node) {
2728 this.next();
2729 node.block = this.parseBlock();
2730 node.handler = null;
2731 if (this.type === types._catch) {
2732 var clause = this.startNode();
2733 this.next();
2734 this.expect(types.parenL);
2735 clause.param = this.parseBindingAtom();
2736 this.enterLexicalScope();
2737 this.checkLVal(clause.param, "let");
2738 this.expect(types.parenR);
2739 clause.body = this.parseBlock(false);
2740 this.exitLexicalScope();
2741 node.handler = this.finishNode(clause, "CatchClause");
2742 }
2743 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
2744 if (!node.handler && !node.finalizer)
2745 { this.raise(node.start, "Missing catch or finally clause"); }
2746 return this.finishNode(node, "TryStatement")
2747};
2748
2749pp$1.parseVarStatement = function(node, kind) {
2750 this.next();
2751 this.parseVar(node, false, kind);
2752 this.semicolon();
2753 return this.finishNode(node, "VariableDeclaration")
2754};
2755
2756pp$1.parseWhileStatement = function(node) {
2757 this.next();
2758 node.test = this.parseParenExpression();
2759 this.labels.push(loopLabel);
2760 node.body = this.parseStatement(false);
2761 this.labels.pop();
2762 return this.finishNode(node, "WhileStatement")
2763};
2764
2765pp$1.parseWithStatement = function(node) {
2766 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
2767 this.next();
2768 node.object = this.parseParenExpression();
2769 node.body = this.parseStatement(false);
2770 return this.finishNode(node, "WithStatement")
2771};
2772
2773pp$1.parseEmptyStatement = function(node) {
2774 this.next();
2775 return this.finishNode(node, "EmptyStatement")
2776};
2777
2778pp$1.parseLabeledStatement = function(node, maybeName, expr) {
2779 var this$1 = this;
2780
2781 for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1)
2782 {
2783 var label = list[i$1];
2784
2785 if (label.name === maybeName)
2786 { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared");
2787 } }
2788 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
2789 for (var i = this.labels.length - 1; i >= 0; i--) {
2790 var label$1 = this$1.labels[i];
2791 if (label$1.statementStart == node.start) {
2792 label$1.statementStart = this$1.start;
2793 label$1.kind = kind;
2794 } else { break }
2795 }
2796 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
2797 node.body = this.parseStatement(true);
2798 if (node.body.type == "ClassDeclaration" ||
2799 node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
2800 node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
2801 { this.raiseRecoverable(node.body.start, "Invalid labeled declaration"); }
2802 this.labels.pop();
2803 node.label = expr;
2804 return this.finishNode(node, "LabeledStatement")
2805};
2806
2807pp$1.parseExpressionStatement = function(node, expr) {
2808 node.expression = expr;
2809 this.semicolon();
2810 return this.finishNode(node, "ExpressionStatement")
2811};
2812
2813// Parse a semicolon-enclosed block of statements, handling `"use
2814// strict"` declarations when `allowStrict` is true (used for
2815// function bodies).
2816
2817pp$1.parseBlock = function(createNewLexicalScope) {
2818 var this$1 = this;
2819 if ( createNewLexicalScope === void 0 ) { createNewLexicalScope = true; }
2820
2821 var node = this.startNode();
2822 node.body = [];
2823 this.expect(types.braceL);
2824 if (createNewLexicalScope) {
2825 this.enterLexicalScope();
2826 }
2827 while (!this.eat(types.braceR)) {
2828 var stmt = this$1.parseStatement(true);
2829 node.body.push(stmt);
2830 }
2831 if (createNewLexicalScope) {
2832 this.exitLexicalScope();
2833 }
2834 return this.finishNode(node, "BlockStatement")
2835};
2836
2837// Parse a regular `for` loop. The disambiguation code in
2838// `parseStatement` will already have parsed the init statement or
2839// expression.
2840
2841pp$1.parseFor = function(node, init) {
2842 node.init = init;
2843 this.expect(types.semi);
2844 node.test = this.type === types.semi ? null : this.parseExpression();
2845 this.expect(types.semi);
2846 node.update = this.type === types.parenR ? null : this.parseExpression();
2847 this.expect(types.parenR);
2848 this.exitLexicalScope();
2849 node.body = this.parseStatement(false);
2850 this.labels.pop();
2851 return this.finishNode(node, "ForStatement")
2852};
2853
2854// Parse a `for`/`in` and `for`/`of` loop, which are almost
2855// same from parser's perspective.
2856
2857pp$1.parseForIn = function(node, init) {
2858 var type = this.type === types._in ? "ForInStatement" : "ForOfStatement";
2859 this.next();
2860 node.left = init;
2861 node.right = this.parseExpression();
2862 this.expect(types.parenR);
2863 this.exitLexicalScope();
2864 node.body = this.parseStatement(false);
2865 this.labels.pop();
2866 return this.finishNode(node, type)
2867};
2868
2869// Parse a list of variable declarations.
2870
2871pp$1.parseVar = function(node, isFor, kind) {
2872 var this$1 = this;
2873
2874 node.declarations = [];
2875 node.kind = kind;
2876 for (;;) {
2877 var decl = this$1.startNode();
2878 this$1.parseVarId(decl, kind);
2879 if (this$1.eat(types.eq)) {
2880 decl.init = this$1.parseMaybeAssign(isFor);
2881 } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
2882 this$1.unexpected();
2883 } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) {
2884 this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value");
2885 } else {
2886 decl.init = null;
2887 }
2888 node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"));
2889 if (!this$1.eat(types.comma)) { break }
2890 }
2891 return node
2892};
2893
2894pp$1.parseVarId = function(decl, kind) {
2895 decl.id = this.parseBindingAtom(kind);
2896 this.checkLVal(decl.id, kind, false);
2897};
2898
2899// Parse a function declaration or literal (depending on the
2900// `isStatement` parameter).
2901
2902pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
2903 this.initFunction(node);
2904 if (this.options.ecmaVersion >= 6 && !isAsync)
2905 { node.generator = this.eat(types.star); }
2906 if (this.options.ecmaVersion >= 8)
2907 { node.async = !!isAsync; }
2908
2909 if (isStatement) {
2910 node.id = isStatement === "nullableID" && this.type != types.name ? null : this.parseIdent();
2911 if (node.id) {
2912 this.checkLVal(node.id, "var");
2913 }
2914 }
2915
2916 var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
2917 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
2918 this.inGenerator = node.generator;
2919 this.inAsync = node.async;
2920 this.yieldPos = 0;
2921 this.awaitPos = 0;
2922 this.inFunction = true;
2923 this.enterFunctionScope();
2924
2925 if (!isStatement)
2926 { node.id = this.type == types.name ? this.parseIdent() : null; }
2927
2928 this.parseFunctionParams(node);
2929 this.parseFunctionBody(node, allowExpressionBody);
2930
2931 this.inGenerator = oldInGen;
2932 this.inAsync = oldInAsync;
2933 this.yieldPos = oldYieldPos;
2934 this.awaitPos = oldAwaitPos;
2935 this.inFunction = oldInFunc;
2936 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
2937};
2938
2939pp$1.parseFunctionParams = function(node) {
2940 this.expect(types.parenL);
2941 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
2942 this.checkYieldAwaitInDefaultParams();
2943};
2944
2945// Parse a class declaration or literal (depending on the
2946// `isStatement` parameter).
2947
2948pp$1.parseClass = function(node, isStatement) {
2949 var this$1 = this;
2950
2951 this.next();
2952
2953 this.parseClassId(node, isStatement);
2954 this.parseClassSuper(node);
2955 var classBody = this.startNode();
2956 var hadConstructor = false;
2957 classBody.body = [];
2958 this.expect(types.braceL);
2959 while (!this.eat(types.braceR)) {
2960 if (this$1.eat(types.semi)) { continue }
2961 var method = this$1.startNode();
2962 var isGenerator = this$1.eat(types.star);
2963 var isAsync = false;
2964 var isMaybeStatic = this$1.type === types.name && this$1.value === "static";
2965 this$1.parsePropertyName(method);
2966 method.static = isMaybeStatic && this$1.type !== types.parenL;
2967 if (method.static) {
2968 if (isGenerator) { this$1.unexpected(); }
2969 isGenerator = this$1.eat(types.star);
2970 this$1.parsePropertyName(method);
2971 }
2972 if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
2973 method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== types.parenL &&
2974 !this$1.canInsertSemicolon()) {
2975 isAsync = true;
2976 this$1.parsePropertyName(method);
2977 }
2978 method.kind = "method";
2979 var isGetSet = false;
2980 if (!method.computed) {
2981 var key = method.key;
2982 if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== types.parenL && (key.name === "get" || key.name === "set")) {
2983 isGetSet = true;
2984 method.kind = key.name;
2985 key = this$1.parsePropertyName(method);
2986 }
2987 if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
2988 key.type === "Literal" && key.value === "constructor")) {
2989 if (hadConstructor) { this$1.raise(key.start, "Duplicate constructor in the same class"); }
2990 if (isGetSet) { this$1.raise(key.start, "Constructor can't have get/set modifier"); }
2991 if (isGenerator) { this$1.raise(key.start, "Constructor can't be a generator"); }
2992 if (isAsync) { this$1.raise(key.start, "Constructor can't be an async method"); }
2993 method.kind = "constructor";
2994 hadConstructor = true;
2995 }
2996 }
2997 this$1.parseClassMethod(classBody, method, isGenerator, isAsync);
2998 if (isGetSet) {
2999 var paramCount = method.kind === "get" ? 0 : 1;
3000 if (method.value.params.length !== paramCount) {
3001 var start = method.value.start;
3002 if (method.kind === "get")
3003 { this$1.raiseRecoverable(start, "getter should have no params"); }
3004 else
3005 { this$1.raiseRecoverable(start, "setter should have exactly one param"); }
3006 } else {
3007 if (method.kind === "set" && method.value.params[0].type === "RestElement")
3008 { this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
3009 }
3010 }
3011 }
3012 node.body = this.finishNode(classBody, "ClassBody");
3013 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
3014};
3015
3016pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
3017 method.value = this.parseMethod(isGenerator, isAsync);
3018 classBody.body.push(this.finishNode(method, "MethodDefinition"));
3019};
3020
3021pp$1.parseClassId = function(node, isStatement) {
3022 node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null;
3023};
3024
3025pp$1.parseClassSuper = function(node) {
3026 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
3027};
3028
3029// Parses module export declaration.
3030
3031pp$1.parseExport = function(node, exports) {
3032 var this$1 = this;
3033
3034 this.next();
3035 // export * from '...'
3036 if (this.eat(types.star)) {
3037 this.expectContextual("from");
3038 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3039 this.semicolon();
3040 return this.finishNode(node, "ExportAllDeclaration")
3041 }
3042 if (this.eat(types._default)) { // export default ...
3043 this.checkExport(exports, "default", this.lastTokStart);
3044 var isAsync;
3045 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
3046 var fNode = this.startNode();
3047 this.next();
3048 if (isAsync) { this.next(); }
3049 node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync);
3050 } else if (this.type === types._class) {
3051 var cNode = this.startNode();
3052 node.declaration = this.parseClass(cNode, "nullableID");
3053 } else {
3054 node.declaration = this.parseMaybeAssign();
3055 this.semicolon();
3056 }
3057 return this.finishNode(node, "ExportDefaultDeclaration")
3058 }
3059 // export var|const|let|function|class ...
3060 if (this.shouldParseExportStatement()) {
3061 node.declaration = this.parseStatement(true);
3062 if (node.declaration.type === "VariableDeclaration")
3063 { this.checkVariableExport(exports, node.declaration.declarations); }
3064 else
3065 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
3066 node.specifiers = [];
3067 node.source = null;
3068 } else { // export { x, y as z } [from '...']
3069 node.declaration = null;
3070 node.specifiers = this.parseExportSpecifiers(exports);
3071 if (this.eatContextual("from")) {
3072 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3073 } else {
3074 // check for keywords used as local names
3075 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
3076 var spec = list[i];
3077
3078 this$1.checkUnreserved(spec.local);
3079 }
3080
3081 node.source = null;
3082 }
3083 this.semicolon();
3084 }
3085 return this.finishNode(node, "ExportNamedDeclaration")
3086};
3087
3088pp$1.checkExport = function(exports, name, pos) {
3089 if (!exports) { return }
3090 if (has(exports, name))
3091 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
3092 exports[name] = true;
3093};
3094
3095pp$1.checkPatternExport = function(exports, pat) {
3096 var this$1 = this;
3097
3098 var type = pat.type;
3099 if (type == "Identifier")
3100 { this.checkExport(exports, pat.name, pat.start); }
3101 else if (type == "ObjectPattern")
3102 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
3103 {
3104 var prop = list[i];
3105
3106 this$1.checkPatternExport(exports, prop.value);
3107 } }
3108 else if (type == "ArrayPattern")
3109 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
3110 var elt = list$1[i$1];
3111
3112 if (elt) { this$1.checkPatternExport(exports, elt); }
3113 } }
3114 else if (type == "AssignmentPattern")
3115 { this.checkPatternExport(exports, pat.left); }
3116 else if (type == "ParenthesizedExpression")
3117 { this.checkPatternExport(exports, pat.expression); }
3118};
3119
3120pp$1.checkVariableExport = function(exports, decls) {
3121 var this$1 = this;
3122
3123 if (!exports) { return }
3124 for (var i = 0, list = decls; i < list.length; i += 1)
3125 {
3126 var decl = list[i];
3127
3128 this$1.checkPatternExport(exports, decl.id);
3129 }
3130};
3131
3132pp$1.shouldParseExportStatement = function() {
3133 return this.type.keyword === "var" ||
3134 this.type.keyword === "const" ||
3135 this.type.keyword === "class" ||
3136 this.type.keyword === "function" ||
3137 this.isLet() ||
3138 this.isAsyncFunction()
3139};
3140
3141// Parses a comma-separated list of module exports.
3142
3143pp$1.parseExportSpecifiers = function(exports) {
3144 var this$1 = this;
3145
3146 var nodes = [], first = true;
3147 // export { x, y as z } [from '...']
3148 this.expect(types.braceL);
3149 while (!this.eat(types.braceR)) {
3150 if (!first) {
3151 this$1.expect(types.comma);
3152 if (this$1.afterTrailingComma(types.braceR)) { break }
3153 } else { first = false; }
3154
3155 var node = this$1.startNode();
3156 node.local = this$1.parseIdent(true);
3157 node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local;
3158 this$1.checkExport(exports, node.exported.name, node.exported.start);
3159 nodes.push(this$1.finishNode(node, "ExportSpecifier"));
3160 }
3161 return nodes
3162};
3163
3164// Parses import declaration.
3165
3166pp$1.parseImport = function(node) {
3167 this.next();
3168 // import '...'
3169 if (this.type === types.string) {
3170 node.specifiers = empty;
3171 node.source = this.parseExprAtom();
3172 } else {
3173 node.specifiers = this.parseImportSpecifiers();
3174 this.expectContextual("from");
3175 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3176 }
3177 this.semicolon();
3178 return this.finishNode(node, "ImportDeclaration")
3179};
3180
3181// Parses a comma-separated list of module imports.
3182
3183pp$1.parseImportSpecifiers = function() {
3184 var this$1 = this;
3185
3186 var nodes = [], first = true;
3187 if (this.type === types.name) {
3188 // import defaultObj, { x, y as z } from '...'
3189 var node = this.startNode();
3190 node.local = this.parseIdent();
3191 this.checkLVal(node.local, "let");
3192 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
3193 if (!this.eat(types.comma)) { return nodes }
3194 }
3195 if (this.type === types.star) {
3196 var node$1 = this.startNode();
3197 this.next();
3198 this.expectContextual("as");
3199 node$1.local = this.parseIdent();
3200 this.checkLVal(node$1.local, "let");
3201 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
3202 return nodes
3203 }
3204 this.expect(types.braceL);
3205 while (!this.eat(types.braceR)) {
3206 if (!first) {
3207 this$1.expect(types.comma);
3208 if (this$1.afterTrailingComma(types.braceR)) { break }
3209 } else { first = false; }
3210
3211 var node$2 = this$1.startNode();
3212 node$2.imported = this$1.parseIdent(true);
3213 if (this$1.eatContextual("as")) {
3214 node$2.local = this$1.parseIdent();
3215 } else {
3216 this$1.checkUnreserved(node$2.imported);
3217 node$2.local = node$2.imported;
3218 }
3219 this$1.checkLVal(node$2.local, "let");
3220 nodes.push(this$1.finishNode(node$2, "ImportSpecifier"));
3221 }
3222 return nodes
3223};
3224
3225var pp$2 = Parser.prototype;
3226
3227// Convert existing expression atom to assignable pattern
3228// if possible.
3229
3230pp$2.toAssignable = function(node, isBinding) {
3231 var this$1 = this;
3232
3233 if (this.options.ecmaVersion >= 6 && node) {
3234 switch (node.type) {
3235 case "Identifier":
3236 if (this.inAsync && node.name === "await")
3237 { this.raise(node.start, "Can not use 'await' as identifier inside an async function"); }
3238 break
3239
3240 case "ObjectPattern":
3241 case "ArrayPattern":
3242 break
3243
3244 case "ObjectExpression":
3245 node.type = "ObjectPattern";
3246 for (var i = 0, list = node.properties; i < list.length; i += 1) {
3247 var prop = list[i];
3248
3249 if (prop.kind !== "init") { this$1.raise(prop.key.start, "Object pattern can't contain getter or setter"); }
3250 this$1.toAssignable(prop.value, isBinding);
3251 }
3252 break
3253
3254 case "ArrayExpression":
3255 node.type = "ArrayPattern";
3256 this.toAssignableList(node.elements, isBinding);
3257 break
3258
3259 case "AssignmentExpression":
3260 if (node.operator === "=") {
3261 node.type = "AssignmentPattern";
3262 delete node.operator;
3263 this.toAssignable(node.left, isBinding);
3264 // falls through to AssignmentPattern
3265 } else {
3266 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
3267 break
3268 }
3269
3270 case "AssignmentPattern":
3271 break
3272
3273 case "ParenthesizedExpression":
3274 this.toAssignable(node.expression, isBinding);
3275 break
3276
3277 case "MemberExpression":
3278 if (!isBinding) { break }
3279
3280 default:
3281 this.raise(node.start, "Assigning to rvalue");
3282 }
3283 }
3284 return node
3285};
3286
3287// Convert list of expression atoms to binding list.
3288
3289pp$2.toAssignableList = function(exprList, isBinding) {
3290 var this$1 = this;
3291
3292 var end = exprList.length;
3293 if (end) {
3294 var last = exprList[end - 1];
3295 if (last && last.type == "RestElement") {
3296 --end;
3297 } else if (last && last.type == "SpreadElement") {
3298 last.type = "RestElement";
3299 var arg = last.argument;
3300 this.toAssignable(arg, isBinding);
3301 --end;
3302 }
3303
3304 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
3305 { this.unexpected(last.argument.start); }
3306 }
3307 for (var i = 0; i < end; i++) {
3308 var elt = exprList[i];
3309 if (elt) { this$1.toAssignable(elt, isBinding); }
3310 }
3311 return exprList
3312};
3313
3314// Parses spread element.
3315
3316pp$2.parseSpread = function(refDestructuringErrors) {
3317 var node = this.startNode();
3318 this.next();
3319 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
3320 return this.finishNode(node, "SpreadElement")
3321};
3322
3323pp$2.parseRestBinding = function() {
3324 var node = this.startNode();
3325 this.next();
3326
3327 // RestElement inside of a function parameter must be an identifier
3328 if (this.options.ecmaVersion === 6 && this.type !== types.name)
3329 { this.unexpected(); }
3330
3331 node.argument = this.parseBindingAtom();
3332
3333 return this.finishNode(node, "RestElement")
3334};
3335
3336// Parses lvalue (assignable) atom.
3337
3338pp$2.parseBindingAtom = function() {
3339 if (this.options.ecmaVersion < 6) { return this.parseIdent() }
3340 switch (this.type) {
3341 case types.name:
3342 return this.parseIdent()
3343
3344 case types.bracketL:
3345 var node = this.startNode();
3346 this.next();
3347 node.elements = this.parseBindingList(types.bracketR, true, true);
3348 return this.finishNode(node, "ArrayPattern")
3349
3350 case types.braceL:
3351 return this.parseObj(true)
3352
3353 default:
3354 this.unexpected();
3355 }
3356};
3357
3358pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
3359 var this$1 = this;
3360
3361 var elts = [], first = true;
3362 while (!this.eat(close)) {
3363 if (first) { first = false; }
3364 else { this$1.expect(types.comma); }
3365 if (allowEmpty && this$1.type === types.comma) {
3366 elts.push(null);
3367 } else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
3368 break
3369 } else if (this$1.type === types.ellipsis) {
3370 var rest = this$1.parseRestBinding();
3371 this$1.parseBindingListItem(rest);
3372 elts.push(rest);
3373 if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
3374 this$1.expect(close);
3375 break
3376 } else {
3377 var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc);
3378 this$1.parseBindingListItem(elem);
3379 elts.push(elem);
3380 }
3381 }
3382 return elts
3383};
3384
3385pp$2.parseBindingListItem = function(param) {
3386 return param
3387};
3388
3389// Parses assignment pattern around given atom if possible.
3390
3391pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
3392 left = left || this.parseBindingAtom();
3393 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
3394 var node = this.startNodeAt(startPos, startLoc);
3395 node.left = left;
3396 node.right = this.parseMaybeAssign();
3397 return this.finishNode(node, "AssignmentPattern")
3398};
3399
3400// Verify that a node is an lval — something that can be assigned
3401// to.
3402// bindingType can be either:
3403// 'var' indicating that the lval creates a 'var' binding
3404// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
3405// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
3406
3407pp$2.checkLVal = function(expr, bindingType, checkClashes) {
3408 var this$1 = this;
3409
3410 switch (expr.type) {
3411 case "Identifier":
3412 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
3413 { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
3414 if (checkClashes) {
3415 if (has(checkClashes, expr.name))
3416 { this.raiseRecoverable(expr.start, "Argument name clash"); }
3417 checkClashes[expr.name] = true;
3418 }
3419 if (bindingType && bindingType !== "none") {
3420 if (
3421 bindingType === "var" && !this.canDeclareVarName(expr.name) ||
3422 bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
3423 ) {
3424 this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"));
3425 }
3426 if (bindingType === "var") {
3427 this.declareVarName(expr.name);
3428 } else {
3429 this.declareLexicalName(expr.name);
3430 }
3431 }
3432 break
3433
3434 case "MemberExpression":
3435 if (bindingType) { this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression"); }
3436 break
3437
3438 case "ObjectPattern":
3439 for (var i = 0, list = expr.properties; i < list.length; i += 1)
3440 {
3441 var prop = list[i];
3442
3443 this$1.checkLVal(prop.value, bindingType, checkClashes);
3444 }
3445 break
3446
3447 case "ArrayPattern":
3448 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
3449 var elem = list$1[i$1];
3450
3451 if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); }
3452 }
3453 break
3454
3455 case "AssignmentPattern":
3456 this.checkLVal(expr.left, bindingType, checkClashes);
3457 break
3458
3459 case "RestElement":
3460 this.checkLVal(expr.argument, bindingType, checkClashes);
3461 break
3462
3463 case "ParenthesizedExpression":
3464 this.checkLVal(expr.expression, bindingType, checkClashes);
3465 break
3466
3467 default:
3468 this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
3469 }
3470};
3471
3472// A recursive descent parser operates by defining functions for all
3473// syntactic elements, and recursively calling those, each function
3474// advancing the input stream and returning an AST node. Precedence
3475// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
3476// instead of `(!x)[1]` is handled by the fact that the parser
3477// function that parses unary prefix operators is called first, and
3478// in turn calls the function that parses `[]` subscripts — that
3479// way, it'll receive the node for `x[1]` already parsed, and wraps
3480// *that* in the unary operator node.
3481//
3482// Acorn uses an [operator precedence parser][opp] to handle binary
3483// operator precedence, because it is much more compact than using
3484// the technique outlined above, which uses different, nesting
3485// functions to specify precedence, for all of the ten binary
3486// precedence levels that JavaScript defines.
3487//
3488// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
3489
3490var pp$3 = Parser.prototype;
3491
3492// Check if property name clashes with already added.
3493// Object/class getters and setters are not allowed to clash —
3494// either with each other or with an init property — and in
3495// strict mode, init properties are also not allowed to be repeated.
3496
3497pp$3.checkPropClash = function(prop, propHash) {
3498 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
3499 { return }
3500 var key = prop.key;
3501 var name;
3502 switch (key.type) {
3503 case "Identifier": name = key.name; break
3504 case "Literal": name = String(key.value); break
3505 default: return
3506 }
3507 var kind = prop.kind;
3508 if (this.options.ecmaVersion >= 6) {
3509 if (name === "__proto__" && kind === "init") {
3510 if (propHash.proto) { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
3511 propHash.proto = true;
3512 }
3513 return
3514 }
3515 name = "$" + name;
3516 var other = propHash[name];
3517 if (other) {
3518 var redefinition;
3519 if (kind === "init") {
3520 redefinition = this.strict && other.init || other.get || other.set;
3521 } else {
3522 redefinition = other.init || other[kind];
3523 }
3524 if (redefinition)
3525 { this.raiseRecoverable(key.start, "Redefinition of property"); }
3526 } else {
3527 other = propHash[name] = {
3528 init: false,
3529 get: false,
3530 set: false
3531 };
3532 }
3533 other[kind] = true;
3534};
3535
3536// ### Expression parsing
3537
3538// These nest, from the most general expression type at the top to
3539// 'atomic', nondivisible expression types at the bottom. Most of
3540// the functions will simply let the function(s) below them parse,
3541// and, *if* the syntactic construct they handle is present, wrap
3542// the AST node that the inner parser gave them in another node.
3543
3544// Parse a full expression. The optional arguments are used to
3545// forbid the `in` operator (in for loops initalization expressions)
3546// and provide reference for storing '=' operator inside shorthand
3547// property assignment in contexts where both object expression
3548// and object pattern might appear (so it's possible to raise
3549// delayed syntax error at correct position).
3550
3551pp$3.parseExpression = function(noIn, refDestructuringErrors) {
3552 var this$1 = this;
3553
3554 var startPos = this.start, startLoc = this.startLoc;
3555 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
3556 if (this.type === types.comma) {
3557 var node = this.startNodeAt(startPos, startLoc);
3558 node.expressions = [expr];
3559 while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); }
3560 return this.finishNode(node, "SequenceExpression")
3561 }
3562 return expr
3563};
3564
3565// Parse an assignment expression. This includes applications of
3566// operators like `+=`.
3567
3568pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
3569 if (this.inGenerator && this.isContextual("yield")) { return this.parseYield() }
3570
3571 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
3572 if (refDestructuringErrors) {
3573 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
3574 oldTrailingComma = refDestructuringErrors.trailingComma;
3575 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
3576 } else {
3577 refDestructuringErrors = new DestructuringErrors;
3578 ownDestructuringErrors = true;
3579 }
3580
3581 var startPos = this.start, startLoc = this.startLoc;
3582 if (this.type == types.parenL || this.type == types.name)
3583 { this.potentialArrowAt = this.start; }
3584 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
3585 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
3586 if (this.type.isAssign) {
3587 this.checkPatternErrors(refDestructuringErrors, true);
3588 if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
3589 var node = this.startNodeAt(startPos, startLoc);
3590 node.operator = this.value;
3591 node.left = this.type === types.eq ? this.toAssignable(left) : left;
3592 refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
3593 this.checkLVal(left);
3594 this.next();
3595 node.right = this.parseMaybeAssign(noIn);
3596 return this.finishNode(node, "AssignmentExpression")
3597 } else {
3598 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
3599 }
3600 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
3601 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
3602 return left
3603};
3604
3605// Parse a ternary conditional (`?:`) operator.
3606
3607pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
3608 var startPos = this.start, startLoc = this.startLoc;
3609 var expr = this.parseExprOps(noIn, refDestructuringErrors);
3610 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3611 if (this.eat(types.question)) {
3612 var node = this.startNodeAt(startPos, startLoc);
3613 node.test = expr;
3614 node.consequent = this.parseMaybeAssign();
3615 this.expect(types.colon);
3616 node.alternate = this.parseMaybeAssign(noIn);
3617 return this.finishNode(node, "ConditionalExpression")
3618 }
3619 return expr
3620};
3621
3622// Start the precedence parser.
3623
3624pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
3625 var startPos = this.start, startLoc = this.startLoc;
3626 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
3627 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3628 return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
3629};
3630
3631// Parse binary operators with the operator precedence parsing
3632// algorithm. `left` is the left-hand side of the operator.
3633// `minPrec` provides context that allows the function to stop and
3634// defer further parser to one of its callers when it encounters an
3635// operator that has a lower precedence than the set it is parsing.
3636
3637pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
3638 var prec = this.type.binop;
3639 if (prec != null && (!noIn || this.type !== types._in)) {
3640 if (prec > minPrec) {
3641 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
3642 var op = this.value;
3643 this.next();
3644 var startPos = this.start, startLoc = this.startLoc;
3645 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
3646 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
3647 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
3648 }
3649 }
3650 return left
3651};
3652
3653pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
3654 var node = this.startNodeAt(startPos, startLoc);
3655 node.left = left;
3656 node.operator = op;
3657 node.right = right;
3658 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
3659};
3660
3661// Parse unary operators, both prefix and postfix.
3662
3663pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
3664 var this$1 = this;
3665
3666 var startPos = this.start, startLoc = this.startLoc, expr;
3667 if (this.inAsync && this.isContextual("await")) {
3668 expr = this.parseAwait(refDestructuringErrors);
3669 sawUnary = true;
3670 } else if (this.type.prefix) {
3671 var node = this.startNode(), update = this.type === types.incDec;
3672 node.operator = this.value;
3673 node.prefix = true;
3674 this.next();
3675 node.argument = this.parseMaybeUnary(null, true);
3676 this.checkExpressionErrors(refDestructuringErrors, true);
3677 if (update) { this.checkLVal(node.argument); }
3678 else if (this.strict && node.operator === "delete" &&
3679 node.argument.type === "Identifier")
3680 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
3681 else { sawUnary = true; }
3682 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
3683 } else {
3684 expr = this.parseExprSubscripts(refDestructuringErrors);
3685 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3686 while (this.type.postfix && !this.canInsertSemicolon()) {
3687 var node$1 = this$1.startNodeAt(startPos, startLoc);
3688 node$1.operator = this$1.value;
3689 node$1.prefix = false;
3690 node$1.argument = expr;
3691 this$1.checkLVal(expr);
3692 this$1.next();
3693 expr = this$1.finishNode(node$1, "UpdateExpression");
3694 }
3695 }
3696
3697 if (!sawUnary && this.eat(types.starstar))
3698 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
3699 else
3700 { return expr }
3701};
3702
3703// Parse call, dot, and `[]`-subscript expressions.
3704
3705pp$3.parseExprSubscripts = function(refDestructuringErrors) {
3706 var startPos = this.start, startLoc = this.startLoc;
3707 var expr = this.parseExprAtom(refDestructuringErrors);
3708 var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
3709 if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
3710 var result = this.parseSubscripts(expr, startPos, startLoc);
3711 if (refDestructuringErrors && result.type === "MemberExpression") {
3712 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
3713 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
3714 }
3715 return result
3716};
3717
3718pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
3719 var this$1 = this;
3720
3721 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
3722 this.lastTokEnd == base.end && !this.canInsertSemicolon();
3723 for (var computed = (void 0);;) {
3724 if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) {
3725 var node = this$1.startNodeAt(startPos, startLoc);
3726 node.object = base;
3727 node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true);
3728 node.computed = !!computed;
3729 if (computed) { this$1.expect(types.bracketR); }
3730 base = this$1.finishNode(node, "MemberExpression");
3731 } else if (!noCalls && this$1.eat(types.parenL)) {
3732 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos;
3733 this$1.yieldPos = 0;
3734 this$1.awaitPos = 0;
3735 var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors);
3736 if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) {
3737 this$1.checkPatternErrors(refDestructuringErrors, false);
3738 this$1.checkYieldAwaitInDefaultParams();
3739 this$1.yieldPos = oldYieldPos;
3740 this$1.awaitPos = oldAwaitPos;
3741 return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
3742 }
3743 this$1.checkExpressionErrors(refDestructuringErrors, true);
3744 this$1.yieldPos = oldYieldPos || this$1.yieldPos;
3745 this$1.awaitPos = oldAwaitPos || this$1.awaitPos;
3746 var node$1 = this$1.startNodeAt(startPos, startLoc);
3747 node$1.callee = base;
3748 node$1.arguments = exprList;
3749 base = this$1.finishNode(node$1, "CallExpression");
3750 } else if (this$1.type === types.backQuote) {
3751 var node$2 = this$1.startNodeAt(startPos, startLoc);
3752 node$2.tag = base;
3753 node$2.quasi = this$1.parseTemplate({isTagged: true});
3754 base = this$1.finishNode(node$2, "TaggedTemplateExpression");
3755 } else {
3756 return base
3757 }
3758 }
3759};
3760
3761// Parse an atomic expression — either a single token that is an
3762// expression, an expression started by a keyword like `function` or
3763// `new`, or an expression wrapped in punctuation like `()`, `[]`,
3764// or `{}`.
3765
3766pp$3.parseExprAtom = function(refDestructuringErrors) {
3767 var node, canBeArrow = this.potentialArrowAt == this.start;
3768 switch (this.type) {
3769 case types._super:
3770 if (!this.inFunction)
3771 { this.raise(this.start, "'super' outside of function or class"); }
3772
3773 case types._this:
3774 var type = this.type === types._this ? "ThisExpression" : "Super";
3775 node = this.startNode();
3776 this.next();
3777 return this.finishNode(node, type)
3778
3779 case types.name:
3780 var startPos = this.start, startLoc = this.startLoc;
3781 var id = this.parseIdent(this.type !== types.name);
3782 if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
3783 { return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) }
3784 if (canBeArrow && !this.canInsertSemicolon()) {
3785 if (this.eat(types.arrow))
3786 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
3787 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name) {
3788 id = this.parseIdent();
3789 if (this.canInsertSemicolon() || !this.eat(types.arrow))
3790 { this.unexpected(); }
3791 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
3792 }
3793 }
3794 return id
3795
3796 case types.regexp:
3797 var value = this.value;
3798 node = this.parseLiteral(value.value);
3799 node.regex = {pattern: value.pattern, flags: value.flags};
3800 return node
3801
3802 case types.num: case types.string:
3803 return this.parseLiteral(this.value)
3804
3805 case types._null: case types._true: case types._false:
3806 node = this.startNode();
3807 node.value = this.type === types._null ? null : this.type === types._true;
3808 node.raw = this.type.keyword;
3809 this.next();
3810 return this.finishNode(node, "Literal")
3811
3812 case types.parenL:
3813 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
3814 if (refDestructuringErrors) {
3815 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
3816 { refDestructuringErrors.parenthesizedAssign = start; }
3817 if (refDestructuringErrors.parenthesizedBind < 0)
3818 { refDestructuringErrors.parenthesizedBind = start; }
3819 }
3820 return expr
3821
3822 case types.bracketL:
3823 node = this.startNode();
3824 this.next();
3825 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
3826 return this.finishNode(node, "ArrayExpression")
3827
3828 case types.braceL:
3829 return this.parseObj(false, refDestructuringErrors)
3830
3831 case types._function:
3832 node = this.startNode();
3833 this.next();
3834 return this.parseFunction(node, false)
3835
3836 case types._class:
3837 return this.parseClass(this.startNode(), false)
3838
3839 case types._new:
3840 return this.parseNew()
3841
3842 case types.backQuote:
3843 return this.parseTemplate()
3844
3845 default:
3846 this.unexpected();
3847 }
3848};
3849
3850pp$3.parseLiteral = function(value) {
3851 var node = this.startNode();
3852 node.value = value;
3853 node.raw = this.input.slice(this.start, this.end);
3854 this.next();
3855 return this.finishNode(node, "Literal")
3856};
3857
3858pp$3.parseParenExpression = function() {
3859 this.expect(types.parenL);
3860 var val = this.parseExpression();
3861 this.expect(types.parenR);
3862 return val
3863};
3864
3865pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
3866 var this$1 = this;
3867
3868 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
3869 if (this.options.ecmaVersion >= 6) {
3870 this.next();
3871
3872 var innerStartPos = this.start, innerStartLoc = this.startLoc;
3873 var exprList = [], first = true, lastIsComma = false;
3874 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart;
3875 this.yieldPos = 0;
3876 this.awaitPos = 0;
3877 while (this.type !== types.parenR) {
3878 first ? first = false : this$1.expect(types.comma);
3879 if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) {
3880 lastIsComma = true;
3881 break
3882 } else if (this$1.type === types.ellipsis) {
3883 spreadStart = this$1.start;
3884 exprList.push(this$1.parseParenItem(this$1.parseRestBinding()));
3885 if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
3886 break
3887 } else {
3888 if (this$1.type === types.parenL && !innerParenStart) {
3889 innerParenStart = this$1.start;
3890 }
3891 exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem));
3892 }
3893 }
3894 var innerEndPos = this.start, innerEndLoc = this.startLoc;
3895 this.expect(types.parenR);
3896
3897 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
3898 this.checkPatternErrors(refDestructuringErrors, false);
3899 this.checkYieldAwaitInDefaultParams();
3900 if (innerParenStart) { this.unexpected(innerParenStart); }
3901 this.yieldPos = oldYieldPos;
3902 this.awaitPos = oldAwaitPos;
3903 return this.parseParenArrowList(startPos, startLoc, exprList)
3904 }
3905
3906 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
3907 if (spreadStart) { this.unexpected(spreadStart); }
3908 this.checkExpressionErrors(refDestructuringErrors, true);
3909 this.yieldPos = oldYieldPos || this.yieldPos;
3910 this.awaitPos = oldAwaitPos || this.awaitPos;
3911
3912 if (exprList.length > 1) {
3913 val = this.startNodeAt(innerStartPos, innerStartLoc);
3914 val.expressions = exprList;
3915 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
3916 } else {
3917 val = exprList[0];
3918 }
3919 } else {
3920 val = this.parseParenExpression();
3921 }
3922
3923 if (this.options.preserveParens) {
3924 var par = this.startNodeAt(startPos, startLoc);
3925 par.expression = val;
3926 return this.finishNode(par, "ParenthesizedExpression")
3927 } else {
3928 return val
3929 }
3930};
3931
3932pp$3.parseParenItem = function(item) {
3933 return item
3934};
3935
3936pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
3937 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
3938};
3939
3940// New's precedence is slightly tricky. It must allow its argument to
3941// be a `[]` or dot subscript expression, but not a call — at least,
3942// not without wrapping it in parentheses. Thus, it uses the noCalls
3943// argument to parseSubscripts to prevent it from consuming the
3944// argument list.
3945
3946var empty$1 = [];
3947
3948pp$3.parseNew = function() {
3949 var node = this.startNode();
3950 var meta = this.parseIdent(true);
3951 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
3952 node.meta = meta;
3953 node.property = this.parseIdent(true);
3954 if (node.property.name !== "target")
3955 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
3956 if (!this.inFunction)
3957 { this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
3958 return this.finishNode(node, "MetaProperty")
3959 }
3960 var startPos = this.start, startLoc = this.startLoc;
3961 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
3962 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
3963 else { node.arguments = empty$1; }
3964 return this.finishNode(node, "NewExpression")
3965};
3966
3967// Parse template expression.
3968
3969pp$3.parseTemplateElement = function(ref) {
3970 var isTagged = ref.isTagged;
3971
3972 var elem = this.startNode();
3973 if (this.type === types.invalidTemplate) {
3974 if (!isTagged) {
3975 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
3976 }
3977 elem.value = {
3978 raw: this.value,
3979 cooked: null
3980 };
3981 } else {
3982 elem.value = {
3983 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
3984 cooked: this.value
3985 };
3986 }
3987 this.next();
3988 elem.tail = this.type === types.backQuote;
3989 return this.finishNode(elem, "TemplateElement")
3990};
3991
3992pp$3.parseTemplate = function(ref) {
3993 var this$1 = this;
3994 if ( ref === void 0 ) { ref = {}; }
3995 var isTagged = ref.isTagged; if ( isTagged === void 0 ) { isTagged = false; }
3996
3997 var node = this.startNode();
3998 this.next();
3999 node.expressions = [];
4000 var curElt = this.parseTemplateElement({isTagged: isTagged});
4001 node.quasis = [curElt];
4002 while (!curElt.tail) {
4003 this$1.expect(types.dollarBraceL);
4004 node.expressions.push(this$1.parseExpression());
4005 this$1.expect(types.braceR);
4006 node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged}));
4007 }
4008 this.next();
4009 return this.finishNode(node, "TemplateLiteral")
4010};
4011
4012// Parse an object literal or binding pattern.
4013
4014pp$3.isAsyncProp = function(prop) {
4015 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
4016 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL) &&
4017 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
4018};
4019
4020pp$3.parseObj = function(isPattern, refDestructuringErrors) {
4021 var this$1 = this;
4022
4023 var node = this.startNode(), first = true, propHash = {};
4024 node.properties = [];
4025 this.next();
4026 while (!this.eat(types.braceR)) {
4027 if (!first) {
4028 this$1.expect(types.comma);
4029 if (this$1.afterTrailingComma(types.braceR)) { break }
4030 } else { first = false; }
4031
4032 var prop = this$1.startNode(), isGenerator = (void 0), isAsync = (void 0), startPos = (void 0), startLoc = (void 0);
4033 if (this$1.options.ecmaVersion >= 6) {
4034 prop.method = false;
4035 prop.shorthand = false;
4036 if (isPattern || refDestructuringErrors) {
4037 startPos = this$1.start;
4038 startLoc = this$1.startLoc;
4039 }
4040 if (!isPattern)
4041 { isGenerator = this$1.eat(types.star); }
4042 }
4043 this$1.parsePropertyName(prop);
4044 if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && this$1.isAsyncProp(prop)) {
4045 isAsync = true;
4046 this$1.parsePropertyName(prop, refDestructuringErrors);
4047 } else {
4048 isAsync = false;
4049 }
4050 this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors);
4051 this$1.checkPropClash(prop, propHash);
4052 node.properties.push(this$1.finishNode(prop, "Property"));
4053 }
4054 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
4055};
4056
4057pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
4058 if ((isGenerator || isAsync) && this.type === types.colon)
4059 { this.unexpected(); }
4060
4061 if (this.eat(types.colon)) {
4062 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
4063 prop.kind = "init";
4064 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
4065 if (isPattern) { this.unexpected(); }
4066 prop.kind = "init";
4067 prop.method = true;
4068 prop.value = this.parseMethod(isGenerator, isAsync);
4069 } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
4070 (prop.key.name === "get" || prop.key.name === "set") &&
4071 (this.type != types.comma && this.type != types.braceR)) {
4072 if (isGenerator || isAsync || isPattern) { this.unexpected(); }
4073 prop.kind = prop.key.name;
4074 this.parsePropertyName(prop);
4075 prop.value = this.parseMethod(false);
4076 var paramCount = prop.kind === "get" ? 0 : 1;
4077 if (prop.value.params.length !== paramCount) {
4078 var start = prop.value.start;
4079 if (prop.kind === "get")
4080 { this.raiseRecoverable(start, "getter should have no params"); }
4081 else
4082 { this.raiseRecoverable(start, "setter should have exactly one param"); }
4083 } else {
4084 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
4085 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
4086 }
4087 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
4088 this.checkUnreserved(prop.key);
4089 prop.kind = "init";
4090 if (isPattern) {
4091 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4092 } else if (this.type === types.eq && refDestructuringErrors) {
4093 if (refDestructuringErrors.shorthandAssign < 0)
4094 { refDestructuringErrors.shorthandAssign = this.start; }
4095 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4096 } else {
4097 prop.value = prop.key;
4098 }
4099 prop.shorthand = true;
4100 } else { this.unexpected(); }
4101};
4102
4103pp$3.parsePropertyName = function(prop) {
4104 if (this.options.ecmaVersion >= 6) {
4105 if (this.eat(types.bracketL)) {
4106 prop.computed = true;
4107 prop.key = this.parseMaybeAssign();
4108 this.expect(types.bracketR);
4109 return prop.key
4110 } else {
4111 prop.computed = false;
4112 }
4113 }
4114 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
4115};
4116
4117// Initialize empty function node.
4118
4119pp$3.initFunction = function(node) {
4120 node.id = null;
4121 if (this.options.ecmaVersion >= 6) {
4122 node.generator = false;
4123 node.expression = false;
4124 }
4125 if (this.options.ecmaVersion >= 8)
4126 { node.async = false; }
4127};
4128
4129// Parse object or class method.
4130
4131pp$3.parseMethod = function(isGenerator, isAsync) {
4132 var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
4133 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
4134
4135 this.initFunction(node);
4136 if (this.options.ecmaVersion >= 6)
4137 { node.generator = isGenerator; }
4138 if (this.options.ecmaVersion >= 8)
4139 { node.async = !!isAsync; }
4140
4141 this.inGenerator = node.generator;
4142 this.inAsync = node.async;
4143 this.yieldPos = 0;
4144 this.awaitPos = 0;
4145 this.inFunction = true;
4146 this.enterFunctionScope();
4147
4148 this.expect(types.parenL);
4149 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
4150 this.checkYieldAwaitInDefaultParams();
4151 this.parseFunctionBody(node, false);
4152
4153 this.inGenerator = oldInGen;
4154 this.inAsync = oldInAsync;
4155 this.yieldPos = oldYieldPos;
4156 this.awaitPos = oldAwaitPos;
4157 this.inFunction = oldInFunc;
4158 return this.finishNode(node, "FunctionExpression")
4159};
4160
4161// Parse arrow function expression with given parameters.
4162
4163pp$3.parseArrowExpression = function(node, params, isAsync) {
4164 var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
4165 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
4166
4167 this.enterFunctionScope();
4168 this.initFunction(node);
4169 if (this.options.ecmaVersion >= 8)
4170 { node.async = !!isAsync; }
4171
4172 this.inGenerator = false;
4173 this.inAsync = node.async;
4174 this.yieldPos = 0;
4175 this.awaitPos = 0;
4176 this.inFunction = true;
4177
4178 node.params = this.toAssignableList(params, true);
4179 this.parseFunctionBody(node, true);
4180
4181 this.inGenerator = oldInGen;
4182 this.inAsync = oldInAsync;
4183 this.yieldPos = oldYieldPos;
4184 this.awaitPos = oldAwaitPos;
4185 this.inFunction = oldInFunc;
4186 return this.finishNode(node, "ArrowFunctionExpression")
4187};
4188
4189// Parse function body and check parameters.
4190
4191pp$3.parseFunctionBody = function(node, isArrowFunction) {
4192 var isExpression = isArrowFunction && this.type !== types.braceL;
4193 var oldStrict = this.strict, useStrict = false;
4194
4195 if (isExpression) {
4196 node.body = this.parseMaybeAssign();
4197 node.expression = true;
4198 this.checkParams(node, false);
4199 } else {
4200 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
4201 if (!oldStrict || nonSimple) {
4202 useStrict = this.strictDirective(this.end);
4203 // If this is a strict mode function, verify that argument names
4204 // are not repeated, and it does not try to bind the words `eval`
4205 // or `arguments`.
4206 if (useStrict && nonSimple)
4207 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
4208 }
4209 // Start a new scope with regard to labels and the `inFunction`
4210 // flag (restore them to their old value afterwards).
4211 var oldLabels = this.labels;
4212 this.labels = [];
4213 if (useStrict) { this.strict = true; }
4214
4215 // Add the params to varDeclaredNames to ensure that an error is thrown
4216 // if a let/const declaration in the function clashes with one of the params.
4217 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params));
4218 node.body = this.parseBlock(false);
4219 node.expression = false;
4220 this.labels = oldLabels;
4221 }
4222 this.exitFunctionScope();
4223
4224 if (this.strict && node.id) {
4225 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
4226 this.checkLVal(node.id, "none");
4227 }
4228 this.strict = oldStrict;
4229};
4230
4231pp$3.isSimpleParamList = function(params) {
4232 for (var i = 0, list = params; i < list.length; i += 1)
4233 {
4234 var param = list[i];
4235
4236 if (param.type !== "Identifier") { return false
4237 } }
4238 return true
4239};
4240
4241// Checks function params for various disallowed patterns such as using "eval"
4242// or "arguments" and duplicate parameters.
4243
4244pp$3.checkParams = function(node, allowDuplicates) {
4245 var this$1 = this;
4246
4247 var nameHash = {};
4248 for (var i = 0, list = node.params; i < list.length; i += 1)
4249 {
4250 var param = list[i];
4251
4252 this$1.checkLVal(param, "var", allowDuplicates ? null : nameHash);
4253 }
4254};
4255
4256// Parses a comma-separated list of expressions, and returns them as
4257// an array. `close` is the token type that ends the list, and
4258// `allowEmpty` can be turned on to allow subsequent commas with
4259// nothing in between them to be parsed as `null` (which is needed
4260// for array literals).
4261
4262pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
4263 var this$1 = this;
4264
4265 var elts = [], first = true;
4266 while (!this.eat(close)) {
4267 if (!first) {
4268 this$1.expect(types.comma);
4269 if (allowTrailingComma && this$1.afterTrailingComma(close)) { break }
4270 } else { first = false; }
4271
4272 var elt = (void 0);
4273 if (allowEmpty && this$1.type === types.comma)
4274 { elt = null; }
4275 else if (this$1.type === types.ellipsis) {
4276 elt = this$1.parseSpread(refDestructuringErrors);
4277 if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0)
4278 { refDestructuringErrors.trailingComma = this$1.start; }
4279 } else {
4280 elt = this$1.parseMaybeAssign(false, refDestructuringErrors);
4281 }
4282 elts.push(elt);
4283 }
4284 return elts
4285};
4286
4287// Parse the next token as an identifier. If `liberal` is true (used
4288// when parsing properties), it will also convert keywords into
4289// identifiers.
4290
4291pp$3.checkUnreserved = function(ref) {
4292 var start = ref.start;
4293 var end = ref.end;
4294 var name = ref.name;
4295
4296 if (this.inGenerator && name === "yield")
4297 { this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator"); }
4298 if (this.inAsync && name === "await")
4299 { this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function"); }
4300 if (this.isKeyword(name))
4301 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
4302 if (this.options.ecmaVersion < 6 &&
4303 this.input.slice(start, end).indexOf("\\") != -1) { return }
4304 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4305 if (re.test(name))
4306 { this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); }
4307};
4308
4309pp$3.parseIdent = function(liberal, isBinding) {
4310 var node = this.startNode();
4311 if (liberal && this.options.allowReserved == "never") { liberal = false; }
4312 if (this.type === types.name) {
4313 node.name = this.value;
4314 } else if (this.type.keyword) {
4315 node.name = this.type.keyword;
4316 } else {
4317 this.unexpected();
4318 }
4319 this.next();
4320 this.finishNode(node, "Identifier");
4321 if (!liberal) { this.checkUnreserved(node); }
4322 return node
4323};
4324
4325// Parses yield expression inside generator.
4326
4327pp$3.parseYield = function() {
4328 if (!this.yieldPos) { this.yieldPos = this.start; }
4329
4330 var node = this.startNode();
4331 this.next();
4332 if (this.type == types.semi || this.canInsertSemicolon() || (this.type != types.star && !this.type.startsExpr)) {
4333 node.delegate = false;
4334 node.argument = null;
4335 } else {
4336 node.delegate = this.eat(types.star);
4337 node.argument = this.parseMaybeAssign();
4338 }
4339 return this.finishNode(node, "YieldExpression")
4340};
4341
4342pp$3.parseAwait = function() {
4343 if (!this.awaitPos) { this.awaitPos = this.start; }
4344
4345 var node = this.startNode();
4346 this.next();
4347 node.argument = this.parseMaybeUnary(null, true);
4348 return this.finishNode(node, "AwaitExpression")
4349};
4350
4351var pp$4 = Parser.prototype;
4352
4353// This function is used to raise exceptions on parse errors. It
4354// takes an offset integer (into the current `input`) to indicate
4355// the location of the error, attaches the position to the end
4356// of the error message, and then raises a `SyntaxError` with that
4357// message.
4358
4359pp$4.raise = function(pos, message) {
4360 var loc = getLineInfo(this.input, pos);
4361 message += " (" + loc.line + ":" + loc.column + ")";
4362 var err = new SyntaxError(message);
4363 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
4364 throw err
4365};
4366
4367pp$4.raiseRecoverable = pp$4.raise;
4368
4369pp$4.curPosition = function() {
4370 if (this.options.locations) {
4371 return new Position(this.curLine, this.pos - this.lineStart)
4372 }
4373};
4374
4375var pp$5 = Parser.prototype;
4376
4377// Object.assign polyfill
4378var assign$1 = Object.assign || function(target) {
4379 var arguments$1 = arguments;
4380
4381 var sources = [], len = arguments.length - 1;
4382 while ( len-- > 0 ) { sources[ len ] = arguments$1[ len + 1 ]; }
4383
4384 for (var i = 0, list = sources; i < list.length; i += 1) {
4385 var source = list[i];
4386
4387 for (var key in source) {
4388 if (has(source, key)) {
4389 target[key] = source[key];
4390 }
4391 }
4392 }
4393 return target
4394};
4395
4396// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
4397
4398pp$5.enterFunctionScope = function() {
4399 // var: a hash of var-declared names in the current lexical scope
4400 // lexical: a hash of lexically-declared names in the current lexical scope
4401 // childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
4402 // parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
4403 this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}});
4404};
4405
4406pp$5.exitFunctionScope = function() {
4407 this.scopeStack.pop();
4408};
4409
4410pp$5.enterLexicalScope = function() {
4411 var parentScope = this.scopeStack[this.scopeStack.length - 1];
4412 var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}};
4413
4414 this.scopeStack.push(childScope);
4415 assign$1(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical);
4416};
4417
4418pp$5.exitLexicalScope = function() {
4419 var childScope = this.scopeStack.pop();
4420 var parentScope = this.scopeStack[this.scopeStack.length - 1];
4421
4422 assign$1(parentScope.childVar, childScope.var, childScope.childVar);
4423};
4424
4425/**
4426 * A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
4427 * in the current lexical scope or any of the parent lexical scopes in this function.
4428 */
4429pp$5.canDeclareVarName = function(name) {
4430 var currentScope = this.scopeStack[this.scopeStack.length - 1];
4431
4432 return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
4433};
4434
4435/**
4436 * A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
4437 * in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
4438 * any child lexical scopes in this function.
4439 */
4440pp$5.canDeclareLexicalName = function(name) {
4441 var currentScope = this.scopeStack[this.scopeStack.length - 1];
4442
4443 return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
4444};
4445
4446pp$5.declareVarName = function(name) {
4447 this.scopeStack[this.scopeStack.length - 1].var[name] = true;
4448};
4449
4450pp$5.declareLexicalName = function(name) {
4451 this.scopeStack[this.scopeStack.length - 1].lexical[name] = true;
4452};
4453
4454var Node = function Node(parser, pos, loc) {
4455 this.type = "";
4456 this.start = pos;
4457 this.end = 0;
4458 if (parser.options.locations)
4459 { this.loc = new SourceLocation(parser, loc); }
4460 if (parser.options.directSourceFile)
4461 { this.sourceFile = parser.options.directSourceFile; }
4462 if (parser.options.ranges)
4463 { this.range = [pos, 0]; }
4464};
4465
4466// Start an AST node, attaching a start offset.
4467
4468var pp$6 = Parser.prototype;
4469
4470pp$6.startNode = function() {
4471 return new Node(this, this.start, this.startLoc)
4472};
4473
4474pp$6.startNodeAt = function(pos, loc) {
4475 return new Node(this, pos, loc)
4476};
4477
4478// Finish an AST node, adding `type` and `end` properties.
4479
4480function finishNodeAt(node, type, pos, loc) {
4481 node.type = type;
4482 node.end = pos;
4483 if (this.options.locations)
4484 { node.loc.end = loc; }
4485 if (this.options.ranges)
4486 { node.range[1] = pos; }
4487 return node
4488}
4489
4490pp$6.finishNode = function(node, type) {
4491 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
4492};
4493
4494// Finish node at given position
4495
4496pp$6.finishNodeAt = function(node, type, pos, loc) {
4497 return finishNodeAt.call(this, node, type, pos, loc)
4498};
4499
4500// The algorithm used to determine whether a regexp can appear at a
4501// given point in the program is loosely based on sweet.js' approach.
4502// See https://github.com/mozilla/sweet.js/wiki/design
4503
4504var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
4505 this.token = token;
4506 this.isExpr = !!isExpr;
4507 this.preserveSpace = !!preserveSpace;
4508 this.override = override;
4509 this.generator = !!generator;
4510};
4511
4512var types$1 = {
4513 b_stat: new TokContext("{", false),
4514 b_expr: new TokContext("{", true),
4515 b_tmpl: new TokContext("${", false),
4516 p_stat: new TokContext("(", false),
4517 p_expr: new TokContext("(", true),
4518 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
4519 f_stat: new TokContext("function", false),
4520 f_expr: new TokContext("function", true),
4521 f_expr_gen: new TokContext("function", true, false, null, true),
4522 f_gen: new TokContext("function", false, false, null, true)
4523};
4524
4525var pp$7 = Parser.prototype;
4526
4527pp$7.initialContext = function() {
4528 return [types$1.b_stat]
4529};
4530
4531pp$7.braceIsBlock = function(prevType) {
4532 var parent = this.curContext();
4533 if (parent === types$1.f_expr || parent === types$1.f_stat)
4534 { return true }
4535 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
4536 { return !parent.isExpr }
4537
4538 // The check for `tt.name && exprAllowed` detects whether we are
4539 // after a `yield` or `of` construct. See the `updateContext` for
4540 // `tt.name`.
4541 if (prevType === types._return || prevType == types.name && this.exprAllowed)
4542 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
4543 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType == types.arrow)
4544 { return true }
4545 if (prevType == types.braceL)
4546 { return parent === types$1.b_stat }
4547 if (prevType == types._var || prevType == types.name)
4548 { return false }
4549 return !this.exprAllowed
4550};
4551
4552pp$7.inGeneratorContext = function() {
4553 var this$1 = this;
4554
4555 for (var i = this.context.length - 1; i >= 1; i--) {
4556 var context = this$1.context[i];
4557 if (context.token === "function")
4558 { return context.generator }
4559 }
4560 return false
4561};
4562
4563pp$7.updateContext = function(prevType) {
4564 var update, type = this.type;
4565 if (type.keyword && prevType == types.dot)
4566 { this.exprAllowed = false; }
4567 else if (update = type.updateContext)
4568 { update.call(this, prevType); }
4569 else
4570 { this.exprAllowed = type.beforeExpr; }
4571};
4572
4573// Token-specific context update code
4574
4575types.parenR.updateContext = types.braceR.updateContext = function() {
4576 if (this.context.length == 1) {
4577 this.exprAllowed = true;
4578 return
4579 }
4580 var out = this.context.pop();
4581 if (out === types$1.b_stat && this.curContext().token === "function") {
4582 out = this.context.pop();
4583 }
4584 this.exprAllowed = !out.isExpr;
4585};
4586
4587types.braceL.updateContext = function(prevType) {
4588 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
4589 this.exprAllowed = true;
4590};
4591
4592types.dollarBraceL.updateContext = function() {
4593 this.context.push(types$1.b_tmpl);
4594 this.exprAllowed = true;
4595};
4596
4597types.parenL.updateContext = function(prevType) {
4598 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
4599 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
4600 this.exprAllowed = true;
4601};
4602
4603types.incDec.updateContext = function() {
4604 // tokExprAllowed stays unchanged
4605};
4606
4607types._function.updateContext = types._class.updateContext = function(prevType) {
4608 if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&
4609 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
4610 { this.context.push(types$1.f_expr); }
4611 else
4612 { this.context.push(types$1.f_stat); }
4613 this.exprAllowed = false;
4614};
4615
4616types.backQuote.updateContext = function() {
4617 if (this.curContext() === types$1.q_tmpl)
4618 { this.context.pop(); }
4619 else
4620 { this.context.push(types$1.q_tmpl); }
4621 this.exprAllowed = false;
4622};
4623
4624types.star.updateContext = function(prevType) {
4625 if (prevType == types._function) {
4626 var index = this.context.length - 1;
4627 if (this.context[index] === types$1.f_expr)
4628 { this.context[index] = types$1.f_expr_gen; }
4629 else
4630 { this.context[index] = types$1.f_gen; }
4631 }
4632 this.exprAllowed = true;
4633};
4634
4635types.name.updateContext = function(prevType) {
4636 var allowed = false;
4637 if (this.options.ecmaVersion >= 6) {
4638 if (this.value == "of" && !this.exprAllowed ||
4639 this.value == "yield" && this.inGeneratorContext())
4640 { allowed = true; }
4641 }
4642 this.exprAllowed = allowed;
4643};
4644
4645// Object type used to represent tokens. Note that normally, tokens
4646// simply exist as properties on the parser object. This is only
4647// used for the onToken callback and the external tokenizer.
4648
4649var Token = function Token(p) {
4650 this.type = p.type;
4651 this.value = p.value;
4652 this.start = p.start;
4653 this.end = p.end;
4654 if (p.options.locations)
4655 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
4656 if (p.options.ranges)
4657 { this.range = [p.start, p.end]; }
4658};
4659
4660// ## Tokenizer
4661
4662var pp$8 = Parser.prototype;
4663
4664// Are we running under Rhino?
4665var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
4666
4667// Move to the next token
4668
4669pp$8.next = function() {
4670 if (this.options.onToken)
4671 { this.options.onToken(new Token(this)); }
4672
4673 this.lastTokEnd = this.end;
4674 this.lastTokStart = this.start;
4675 this.lastTokEndLoc = this.endLoc;
4676 this.lastTokStartLoc = this.startLoc;
4677 this.nextToken();
4678};
4679
4680pp$8.getToken = function() {
4681 this.next();
4682 return new Token(this)
4683};
4684
4685// If we're in an ES6 environment, make parsers iterable
4686if (typeof Symbol !== "undefined")
4687 { pp$8[Symbol.iterator] = function() {
4688 var this$1 = this;
4689
4690 return {
4691 next: function () {
4692 var token = this$1.getToken();
4693 return {
4694 done: token.type === types.eof,
4695 value: token
4696 }
4697 }
4698 }
4699 }; }
4700
4701// Toggle strict mode. Re-reads the next number or string to please
4702// pedantic tests (`"use strict"; 010;` should fail).
4703
4704pp$8.curContext = function() {
4705 return this.context[this.context.length - 1]
4706};
4707
4708// Read a single token, updating the parser object's token-related
4709// properties.
4710
4711pp$8.nextToken = function() {
4712 var curContext = this.curContext();
4713 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
4714
4715 this.start = this.pos;
4716 if (this.options.locations) { this.startLoc = this.curPosition(); }
4717 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
4718
4719 if (curContext.override) { return curContext.override(this) }
4720 else { this.readToken(this.fullCharCodeAtPos()); }
4721};
4722
4723pp$8.readToken = function(code) {
4724 // Identifier or keyword. '\uXXXX' sequences are allowed in
4725 // identifiers, so '\' also dispatches to that.
4726 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
4727 { return this.readWord() }
4728
4729 return this.getTokenFromCode(code)
4730};
4731
4732pp$8.fullCharCodeAtPos = function() {
4733 var code = this.input.charCodeAt(this.pos);
4734 if (code <= 0xd7ff || code >= 0xe000) { return code }
4735 var next = this.input.charCodeAt(this.pos + 1);
4736 return (code << 10) + next - 0x35fdc00
4737};
4738
4739pp$8.skipBlockComment = function() {
4740 var this$1 = this;
4741
4742 var startLoc = this.options.onComment && this.curPosition();
4743 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
4744 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
4745 this.pos = end + 2;
4746 if (this.options.locations) {
4747 lineBreakG.lastIndex = start;
4748 var match;
4749 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
4750 ++this$1.curLine;
4751 this$1.lineStart = match.index + match[0].length;
4752 }
4753 }
4754 if (this.options.onComment)
4755 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
4756 startLoc, this.curPosition()); }
4757};
4758
4759pp$8.skipLineComment = function(startSkip) {
4760 var this$1 = this;
4761
4762 var start = this.pos;
4763 var startLoc = this.options.onComment && this.curPosition();
4764 var ch = this.input.charCodeAt(this.pos += startSkip);
4765 while (this.pos < this.input.length && !isNewLine(ch)) {
4766 ch = this$1.input.charCodeAt(++this$1.pos);
4767 }
4768 if (this.options.onComment)
4769 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
4770 startLoc, this.curPosition()); }
4771};
4772
4773// Called at the start of the parse and after every token. Skips
4774// whitespace and comments, and.
4775
4776pp$8.skipSpace = function() {
4777 var this$1 = this;
4778
4779 loop: while (this.pos < this.input.length) {
4780 var ch = this$1.input.charCodeAt(this$1.pos);
4781 switch (ch) {
4782 case 32: case 160: // ' '
4783 ++this$1.pos;
4784 break
4785 case 13:
4786 if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
4787 ++this$1.pos;
4788 }
4789 case 10: case 8232: case 8233:
4790 ++this$1.pos;
4791 if (this$1.options.locations) {
4792 ++this$1.curLine;
4793 this$1.lineStart = this$1.pos;
4794 }
4795 break
4796 case 47: // '/'
4797 switch (this$1.input.charCodeAt(this$1.pos + 1)) {
4798 case 42: // '*'
4799 this$1.skipBlockComment();
4800 break
4801 case 47:
4802 this$1.skipLineComment(2);
4803 break
4804 default:
4805 break loop
4806 }
4807 break
4808 default:
4809 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
4810 ++this$1.pos;
4811 } else {
4812 break loop
4813 }
4814 }
4815 }
4816};
4817
4818// Called at the end of every token. Sets `end`, `val`, and
4819// maintains `context` and `exprAllowed`, and skips the space after
4820// the token, so that the next one's `start` will point at the
4821// right position.
4822
4823pp$8.finishToken = function(type, val) {
4824 this.end = this.pos;
4825 if (this.options.locations) { this.endLoc = this.curPosition(); }
4826 var prevType = this.type;
4827 this.type = type;
4828 this.value = val;
4829
4830 this.updateContext(prevType);
4831};
4832
4833// ### Token reading
4834
4835// This is the function that is called to fetch the next token. It
4836// is somewhat obscure, because it works in character codes rather
4837// than characters, and because operator parsing has been inlined
4838// into it.
4839//
4840// All in the name of speed.
4841//
4842pp$8.readToken_dot = function() {
4843 var next = this.input.charCodeAt(this.pos + 1);
4844 if (next >= 48 && next <= 57) { return this.readNumber(true) }
4845 var next2 = this.input.charCodeAt(this.pos + 2);
4846 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
4847 this.pos += 3;
4848 return this.finishToken(types.ellipsis)
4849 } else {
4850 ++this.pos;
4851 return this.finishToken(types.dot)
4852 }
4853};
4854
4855pp$8.readToken_slash = function() { // '/'
4856 var next = this.input.charCodeAt(this.pos + 1);
4857 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
4858 if (next === 61) { return this.finishOp(types.assign, 2) }
4859 return this.finishOp(types.slash, 1)
4860};
4861
4862pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
4863 var next = this.input.charCodeAt(this.pos + 1);
4864 var size = 1;
4865 var tokentype = code === 42 ? types.star : types.modulo;
4866
4867 // exponentiation operator ** and **=
4868 if (this.options.ecmaVersion >= 7 && next === 42) {
4869 ++size;
4870 tokentype = types.starstar;
4871 next = this.input.charCodeAt(this.pos + 2);
4872 }
4873
4874 if (next === 61) { return this.finishOp(types.assign, size + 1) }
4875 return this.finishOp(tokentype, size)
4876};
4877
4878pp$8.readToken_pipe_amp = function(code) { // '|&'
4879 var next = this.input.charCodeAt(this.pos + 1);
4880 if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) }
4881 if (next === 61) { return this.finishOp(types.assign, 2) }
4882 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
4883};
4884
4885pp$8.readToken_caret = function() { // '^'
4886 var next = this.input.charCodeAt(this.pos + 1);
4887 if (next === 61) { return this.finishOp(types.assign, 2) }
4888 return this.finishOp(types.bitwiseXOR, 1)
4889};
4890
4891pp$8.readToken_plus_min = function(code) { // '+-'
4892 var next = this.input.charCodeAt(this.pos + 1);
4893 if (next === code) {
4894 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
4895 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
4896 // A `-->` line comment
4897 this.skipLineComment(3);
4898 this.skipSpace();
4899 return this.nextToken()
4900 }
4901 return this.finishOp(types.incDec, 2)
4902 }
4903 if (next === 61) { return this.finishOp(types.assign, 2) }
4904 return this.finishOp(types.plusMin, 1)
4905};
4906
4907pp$8.readToken_lt_gt = function(code) { // '<>'
4908 var next = this.input.charCodeAt(this.pos + 1);
4909 var size = 1;
4910 if (next === code) {
4911 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
4912 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
4913 return this.finishOp(types.bitShift, size)
4914 }
4915 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
4916 this.input.charCodeAt(this.pos + 3) == 45) {
4917 if (this.inModule) { this.unexpected(); }
4918 // `<!--`, an XML-style comment that should be interpreted as a line comment
4919 this.skipLineComment(4);
4920 this.skipSpace();
4921 return this.nextToken()
4922 }
4923 if (next === 61) { size = 2; }
4924 return this.finishOp(types.relational, size)
4925};
4926
4927pp$8.readToken_eq_excl = function(code) { // '=!'
4928 var next = this.input.charCodeAt(this.pos + 1);
4929 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
4930 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
4931 this.pos += 2;
4932 return this.finishToken(types.arrow)
4933 }
4934 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
4935};
4936
4937pp$8.getTokenFromCode = function(code) {
4938 switch (code) {
4939 // The interpretation of a dot depends on whether it is followed
4940 // by a digit or another two dots.
4941 case 46: // '.'
4942 return this.readToken_dot()
4943
4944 // Punctuation tokens.
4945 case 40: ++this.pos; return this.finishToken(types.parenL)
4946 case 41: ++this.pos; return this.finishToken(types.parenR)
4947 case 59: ++this.pos; return this.finishToken(types.semi)
4948 case 44: ++this.pos; return this.finishToken(types.comma)
4949 case 91: ++this.pos; return this.finishToken(types.bracketL)
4950 case 93: ++this.pos; return this.finishToken(types.bracketR)
4951 case 123: ++this.pos; return this.finishToken(types.braceL)
4952 case 125: ++this.pos; return this.finishToken(types.braceR)
4953 case 58: ++this.pos; return this.finishToken(types.colon)
4954 case 63: ++this.pos; return this.finishToken(types.question)
4955
4956 case 96: // '`'
4957 if (this.options.ecmaVersion < 6) { break }
4958 ++this.pos;
4959 return this.finishToken(types.backQuote)
4960
4961 case 48: // '0'
4962 var next = this.input.charCodeAt(this.pos + 1);
4963 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
4964 if (this.options.ecmaVersion >= 6) {
4965 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
4966 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
4967 }
4968 // Anything else beginning with a digit is an integer, octal
4969 // number, or float.
4970 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
4971 return this.readNumber(false)
4972
4973 // Quotes produce strings.
4974 case 34: case 39: // '"', "'"
4975 return this.readString(code)
4976
4977 // Operators are parsed inline in tiny state machines. '=' (61) is
4978 // often referred to. `finishOp` simply skips the amount of
4979 // characters it is given as second argument, and returns a token
4980 // of the type given by its first argument.
4981
4982 case 47: // '/'
4983 return this.readToken_slash()
4984
4985 case 37: case 42: // '%*'
4986 return this.readToken_mult_modulo_exp(code)
4987
4988 case 124: case 38: // '|&'
4989 return this.readToken_pipe_amp(code)
4990
4991 case 94: // '^'
4992 return this.readToken_caret()
4993
4994 case 43: case 45: // '+-'
4995 return this.readToken_plus_min(code)
4996
4997 case 60: case 62: // '<>'
4998 return this.readToken_lt_gt(code)
4999
5000 case 61: case 33: // '=!'
5001 return this.readToken_eq_excl(code)
5002
5003 case 126: // '~'
5004 return this.finishOp(types.prefix, 1)
5005 }
5006
5007 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
5008};
5009
5010pp$8.finishOp = function(type, size) {
5011 var str = this.input.slice(this.pos, this.pos + size);
5012 this.pos += size;
5013 return this.finishToken(type, str)
5014};
5015
5016// Parse a regular expression. Some context-awareness is necessary,
5017// since a '/' inside a '[]' set does not end the expression.
5018
5019function tryCreateRegexp(src, flags, throwErrorAt, parser) {
5020 try {
5021 return new RegExp(src, flags)
5022 } catch (e) {
5023 if (throwErrorAt !== undefined) {
5024 if (e instanceof SyntaxError) { parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message); }
5025 throw e
5026 }
5027 }
5028}
5029
5030var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
5031
5032pp$8.readRegexp = function() {
5033 var this$1 = this;
5034
5035 var escaped, inClass, start = this.pos;
5036 for (;;) {
5037 if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression"); }
5038 var ch = this$1.input.charAt(this$1.pos);
5039 if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression"); }
5040 if (!escaped) {
5041 if (ch === "[") { inClass = true; }
5042 else if (ch === "]" && inClass) { inClass = false; }
5043 else if (ch === "/" && !inClass) { break }
5044 escaped = ch === "\\";
5045 } else { escaped = false; }
5046 ++this$1.pos;
5047 }
5048 var content = this.input.slice(start, this.pos);
5049 ++this.pos;
5050 // Need to use `readWord1` because '\uXXXX' sequences are allowed
5051 // here (don't ask).
5052 var mods = this.readWord1();
5053 var tmp = content, tmpFlags = "";
5054 if (mods) {
5055 var validFlags = /^[gim]*$/;
5056 if (this.options.ecmaVersion >= 6) { validFlags = /^[gimuy]*$/; }
5057 if (!validFlags.test(mods)) { this.raise(start, "Invalid regular expression flag"); }
5058 if (mods.indexOf("u") >= 0) {
5059 if (regexpUnicodeSupport) {
5060 tmpFlags = "u";
5061 } else {
5062 // Replace each astral symbol and every Unicode escape sequence that
5063 // possibly represents an astral symbol or a paired surrogate with a
5064 // single ASCII symbol to avoid throwing on regular expressions that
5065 // are only valid in combination with the `/u` flag.
5066 // Note: replacing with the ASCII symbol `x` might cause false
5067 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
5068 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
5069 // be replaced by `[x-b]` which throws an error.
5070 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
5071 code = Number("0x" + code);
5072 if (code > 0x10FFFF) { this$1.raise(start + offset + 3, "Code point out of bounds"); }
5073 return "x"
5074 });
5075 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
5076 tmpFlags = tmpFlags.replace("u", "");
5077 }
5078 }
5079 }
5080 // Detect invalid regular expressions.
5081 var value = null;
5082 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
5083 // so don't do detection if we are running under Rhino
5084 if (!isRhino) {
5085 tryCreateRegexp(tmp, tmpFlags, start, this);
5086 // Get a regular expression object for this pattern-flag pair, or `null` in
5087 // case the current environment doesn't support the flags it uses.
5088 value = tryCreateRegexp(content, mods);
5089 }
5090 return this.finishToken(types.regexp, {pattern: content, flags: mods, value: value})
5091};
5092
5093// Read an integer in the given radix. Return null if zero digits
5094// were read, the integer value otherwise. When `len` is given, this
5095// will return `null` unless the integer has exactly `len` digits.
5096
5097pp$8.readInt = function(radix, len) {
5098 var this$1 = this;
5099
5100 var start = this.pos, total = 0;
5101 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
5102 var code = this$1.input.charCodeAt(this$1.pos), val = (void 0);
5103 if (code >= 97) { val = code - 97 + 10; } // a
5104 else if (code >= 65) { val = code - 65 + 10; } // A
5105 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
5106 else { val = Infinity; }
5107 if (val >= radix) { break }
5108 ++this$1.pos;
5109 total = total * radix + val;
5110 }
5111 if (this.pos === start || len != null && this.pos - start !== len) { return null }
5112
5113 return total
5114};
5115
5116pp$8.readRadixNumber = function(radix) {
5117 this.pos += 2; // 0x
5118 var val = this.readInt(radix);
5119 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
5120 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5121 return this.finishToken(types.num, val)
5122};
5123
5124// Read an integer, octal integer, or floating-point number.
5125
5126pp$8.readNumber = function(startsWithDot) {
5127 var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48;
5128 if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
5129 if (octal && this.pos == start + 1) { octal = false; }
5130 var next = this.input.charCodeAt(this.pos);
5131 if (next === 46 && !octal) { // '.'
5132 ++this.pos;
5133 this.readInt(10);
5134 isFloat = true;
5135 next = this.input.charCodeAt(this.pos);
5136 }
5137 if ((next === 69 || next === 101) && !octal) { // 'eE'
5138 next = this.input.charCodeAt(++this.pos);
5139 if (next === 43 || next === 45) { ++this.pos; } // '+-'
5140 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
5141 isFloat = true;
5142 }
5143 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5144
5145 var str = this.input.slice(start, this.pos), val;
5146 if (isFloat) { val = parseFloat(str); }
5147 else if (!octal || str.length === 1) { val = parseInt(str, 10); }
5148 else if (this.strict) { this.raise(start, "Invalid number"); }
5149 else if (/[89]/.test(str)) { val = parseInt(str, 10); }
5150 else { val = parseInt(str, 8); }
5151 return this.finishToken(types.num, val)
5152};
5153
5154// Read a string value, interpreting backslash-escapes.
5155
5156pp$8.readCodePoint = function() {
5157 var ch = this.input.charCodeAt(this.pos), code;
5158
5159 if (ch === 123) { // '{'
5160 if (this.options.ecmaVersion < 6) { this.unexpected(); }
5161 var codePos = ++this.pos;
5162 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
5163 ++this.pos;
5164 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
5165 } else {
5166 code = this.readHexChar(4);
5167 }
5168 return code
5169};
5170
5171function codePointToString(code) {
5172 // UTF-16 Decoding
5173 if (code <= 0xFFFF) { return String.fromCharCode(code) }
5174 code -= 0x10000;
5175 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
5176}
5177
5178pp$8.readString = function(quote) {
5179 var this$1 = this;
5180
5181 var out = "", chunkStart = ++this.pos;
5182 for (;;) {
5183 if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant"); }
5184 var ch = this$1.input.charCodeAt(this$1.pos);
5185 if (ch === quote) { break }
5186 if (ch === 92) { // '\'
5187 out += this$1.input.slice(chunkStart, this$1.pos);
5188 out += this$1.readEscapedChar(false);
5189 chunkStart = this$1.pos;
5190 } else {
5191 if (isNewLine(ch)) { this$1.raise(this$1.start, "Unterminated string constant"); }
5192 ++this$1.pos;
5193 }
5194 }
5195 out += this.input.slice(chunkStart, this.pos++);
5196 return this.finishToken(types.string, out)
5197};
5198
5199// Reads template string tokens.
5200
5201var INVALID_TEMPLATE_ESCAPE_ERROR = {};
5202
5203pp$8.tryReadTemplateToken = function() {
5204 this.inTemplateElement = true;
5205 try {
5206 this.readTmplToken();
5207 } catch (err) {
5208 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
5209 this.readInvalidTemplateToken();
5210 } else {
5211 throw err
5212 }
5213 }
5214
5215 this.inTemplateElement = false;
5216};
5217
5218pp$8.invalidStringToken = function(position, message) {
5219 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
5220 throw INVALID_TEMPLATE_ESCAPE_ERROR
5221 } else {
5222 this.raise(position, message);
5223 }
5224};
5225
5226pp$8.readTmplToken = function() {
5227 var this$1 = this;
5228
5229 var out = "", chunkStart = this.pos;
5230 for (;;) {
5231 if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template"); }
5232 var ch = this$1.input.charCodeAt(this$1.pos);
5233 if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
5234 if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) {
5235 if (ch === 36) {
5236 this$1.pos += 2;
5237 return this$1.finishToken(types.dollarBraceL)
5238 } else {
5239 ++this$1.pos;
5240 return this$1.finishToken(types.backQuote)
5241 }
5242 }
5243 out += this$1.input.slice(chunkStart, this$1.pos);
5244 return this$1.finishToken(types.template, out)
5245 }
5246 if (ch === 92) { // '\'
5247 out += this$1.input.slice(chunkStart, this$1.pos);
5248 out += this$1.readEscapedChar(true);
5249 chunkStart = this$1.pos;
5250 } else if (isNewLine(ch)) {
5251 out += this$1.input.slice(chunkStart, this$1.pos);
5252 ++this$1.pos;
5253 switch (ch) {
5254 case 13:
5255 if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos; }
5256 case 10:
5257 out += "\n";
5258 break
5259 default:
5260 out += String.fromCharCode(ch);
5261 break
5262 }
5263 if (this$1.options.locations) {
5264 ++this$1.curLine;
5265 this$1.lineStart = this$1.pos;
5266 }
5267 chunkStart = this$1.pos;
5268 } else {
5269 ++this$1.pos;
5270 }
5271 }
5272};
5273
5274// Reads a template token to search for the end, without validating any escape sequences
5275pp$8.readInvalidTemplateToken = function() {
5276 var this$1 = this;
5277
5278 for (; this.pos < this.input.length; this.pos++) {
5279 switch (this$1.input[this$1.pos]) {
5280 case "\\":
5281 ++this$1.pos;
5282 break
5283
5284 case "$":
5285 if (this$1.input[this$1.pos + 1] !== "{") {
5286 break
5287 }
5288 // falls through
5289
5290 case "`":
5291 return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos))
5292
5293 // no default
5294 }
5295 }
5296 this.raise(this.start, "Unterminated template");
5297};
5298
5299// Used to read escaped characters
5300
5301pp$8.readEscapedChar = function(inTemplate) {
5302 var ch = this.input.charCodeAt(++this.pos);
5303 ++this.pos;
5304 switch (ch) {
5305 case 110: return "\n" // 'n' -> '\n'
5306 case 114: return "\r" // 'r' -> '\r'
5307 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
5308 case 117: return codePointToString(this.readCodePoint()) // 'u'
5309 case 116: return "\t" // 't' -> '\t'
5310 case 98: return "\b" // 'b' -> '\b'
5311 case 118: return "\u000b" // 'v' -> '\u000b'
5312 case 102: return "\f" // 'f' -> '\f'
5313 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
5314 case 10: // ' \n'
5315 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
5316 return ""
5317 default:
5318 if (ch >= 48 && ch <= 55) {
5319 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
5320 var octal = parseInt(octalStr, 8);
5321 if (octal > 255) {
5322 octalStr = octalStr.slice(0, -1);
5323 octal = parseInt(octalStr, 8);
5324 }
5325 if (octalStr !== "0" && (this.strict || inTemplate)) {
5326 this.invalidStringToken(this.pos - 2, "Octal literal in strict mode");
5327 }
5328 this.pos += octalStr.length - 1;
5329 return String.fromCharCode(octal)
5330 }
5331 return String.fromCharCode(ch)
5332 }
5333};
5334
5335// Used to read character escape sequences ('\x', '\u', '\U').
5336
5337pp$8.readHexChar = function(len) {
5338 var codePos = this.pos;
5339 var n = this.readInt(16, len);
5340 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
5341 return n
5342};
5343
5344// Read an identifier, and return it as a string. Sets `this.containsEsc`
5345// to whether the word contained a '\u' escape.
5346//
5347// Incrementally adds only escaped chars, adding other chunks as-is
5348// as a micro-optimization.
5349
5350pp$8.readWord1 = function() {
5351 var this$1 = this;
5352
5353 this.containsEsc = false;
5354 var word = "", first = true, chunkStart = this.pos;
5355 var astral = this.options.ecmaVersion >= 6;
5356 while (this.pos < this.input.length) {
5357 var ch = this$1.fullCharCodeAtPos();
5358 if (isIdentifierChar(ch, astral)) {
5359 this$1.pos += ch <= 0xffff ? 1 : 2;
5360 } else if (ch === 92) { // "\"
5361 this$1.containsEsc = true;
5362 word += this$1.input.slice(chunkStart, this$1.pos);
5363 var escStart = this$1.pos;
5364 if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
5365 { this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX"); }
5366 ++this$1.pos;
5367 var esc = this$1.readCodePoint();
5368 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
5369 { this$1.invalidStringToken(escStart, "Invalid Unicode escape"); }
5370 word += codePointToString(esc);
5371 chunkStart = this$1.pos;
5372 } else {
5373 break
5374 }
5375 first = false;
5376 }
5377 return word + this.input.slice(chunkStart, this.pos)
5378};
5379
5380// Read an identifier or keyword token. Will check for reserved
5381// words when necessary.
5382
5383pp$8.readWord = function() {
5384 var word = this.readWord1();
5385 var type = types.name;
5386 if (this.keywords.test(word)) {
5387 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
5388 type = keywords$1[word];
5389 }
5390 return this.finishToken(type, word)
5391};
5392
5393// The main exported interface (under `self.acorn` when in the
5394// browser) is a `parse` function that takes a code string and
5395// returns an abstract syntax tree as specified by [Mozilla parser
5396// API][api].
5397//
5398// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
5399
5400function parse(input, options) {
5401 return new Parser(options, input).parse()
5402}
5403
5404function getLocator$1(source, options) {
5405 if (options === void 0) { options = {}; }
5406 var offsetLine = options.offsetLine || 0;
5407 var offsetColumn = options.offsetColumn || 0;
5408 var originalLines = source.split('\n');
5409 var start = 0;
5410 var lineRanges = originalLines.map(function (line, i) {
5411 var end = start + line.length + 1;
5412 var range = { start: start, end: end, line: i };
5413 start = end;
5414 return range;
5415 });
5416 var i = 0;
5417 function rangeContains(range, index) {
5418 return range.start <= index && index < range.end;
5419 }
5420 function getLocation(range, index) {
5421 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
5422 }
5423 function locate(search, startIndex) {
5424 if (typeof search === 'string') {
5425 search = source.indexOf(search, startIndex || 0);
5426 }
5427 var range = lineRanges[i];
5428 var d = search >= range.end ? 1 : -1;
5429 while (range) {
5430 if (rangeContains(range, search))
5431 return getLocation(range, search);
5432 i += d;
5433 range = lineRanges[i];
5434 }
5435 }
5436
5437 return locate;
5438}
5439function locate(source, search, options) {
5440 if (typeof options === 'number') {
5441 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
5442 }
5443 return getLocator$1(source, options)(search, options && options.startIndex);
5444}
5445
5446var reservedWords$1 = '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( ' ' );
5447var 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( ' ' );
5448
5449var blacklisted = blank();
5450reservedWords$1.concat( builtins ).forEach( function (word) { return blacklisted[ word ] = true; } );
5451
5452var illegalCharacters = /[^$_a-zA-Z0-9]/g;
5453
5454var startsWithDigit = function (str) { return /\d/.test( str[0] ); };
5455
5456function isLegal ( str ) {
5457 if ( startsWithDigit(str) || blacklisted[ str ] ) {
5458 return false;
5459 }
5460 if ( illegalCharacters.test(str) ) {
5461 return false;
5462 }
5463 return true;
5464}
5465
5466function makeLegal ( str ) {
5467 str = str
5468 .replace( /-(\w)/g, function ( _, letter ) { return letter.toUpperCase(); } )
5469 .replace( illegalCharacters, '_' );
5470
5471 if ( startsWithDigit(str) || blacklisted[ str ] ) { str = "_" + str; }
5472
5473 return str;
5474}
5475
5476function spaces ( i ) {
5477 var result = '';
5478 while ( i-- ) { result += ' '; }
5479 return result;
5480}
5481
5482
5483function tabsToSpaces ( str ) {
5484 return str.replace( /^\t+/, function (match) { return match.split( '\t' ).join( ' ' ); } );
5485}
5486
5487function getCodeFrame ( source, line, column ) {
5488 var lines = source.split( '\n' );
5489
5490 var frameStart = Math.max( 0, line - 3 );
5491 var frameEnd = Math.min( line + 2, lines.length );
5492
5493 lines = lines.slice( frameStart, frameEnd );
5494 while ( !/\S/.test( lines[ lines.length - 1 ] ) ) {
5495 lines.pop();
5496 frameEnd -= 1;
5497 }
5498
5499 var digits = String( frameEnd ).length;
5500
5501 return lines
5502 .map( function ( str, i ) {
5503 var isErrorLine = frameStart + i + 1 === line;
5504
5505 var lineNum = String( i + frameStart + 1 );
5506 while ( lineNum.length < digits ) { lineNum = " " + lineNum; }
5507
5508 if ( isErrorLine ) {
5509 var indicator = spaces( digits + 2 + tabsToSpaces( str.slice( 0, column ) ).length ) + '^';
5510 return (lineNum + ": " + (tabsToSpaces( str )) + "\n" + indicator);
5511 }
5512
5513 return (lineNum + ": " + (tabsToSpaces( str )));
5514 })
5515 .join( '\n' );
5516}
5517
5518function relativeId ( id ) {
5519 if ( typeof process === 'undefined' || !isAbsolute( id ) ) { return id; }
5520 return path.relative( process.cwd(), id );
5521}
5522
5523// properties are for debugging purposes only
5524var ARRAY = { ARRAY: true, toString: function () { return '[[ARRAY]]'; } };
5525
5526
5527var NUMBER = { NUMBER: true, toString: function () { return '[[NUMBER]]'; } };
5528var OBJECT = { OBJECT: true, toString: function () { return '[[OBJECT]]'; } };
5529var STRING = { STRING: true, toString: function () { return '[[STRING]]'; } };
5530var UNKNOWN = { UNKNOWN: true, toString: function () { return '[[UNKNOWN]]'; } };
5531
5532var Declaration = function Declaration ( node, isParam ) {
5533 this.node = node;
5534
5535 this.name = node.id ? node.id.name : node.name;
5536 this.exportName = null;
5537 this.isParam = isParam;
5538
5539 this.isReassigned = false;
5540};
5541
5542Declaration.prototype.activate = function activate () {
5543 if ( this.activated ) { return; }
5544 this.activated = true;
5545
5546 if ( this.isParam ) { return; }
5547 this.node.activate();
5548};
5549
5550Declaration.prototype.addReference = function addReference ( reference ) {
5551 reference.declaration = this;
5552
5553 if ( reference.name !== this.name ) {
5554 this.name = makeLegal( reference.name ); // TODO handle differences of opinion
5555 }
5556
5557 if ( reference.isReassignment ) { this.isReassigned = true; }
5558};
5559
5560Declaration.prototype.render = function render ( es ) {
5561 if ( es ) { return this.name; }
5562 if ( !this.isReassigned || !this.exportName ) { return this.name; }
5563
5564 return ("exports." + (this.exportName));
5565};
5566
5567var SyntheticNamespaceDeclaration = function SyntheticNamespaceDeclaration ( module ) {
5568 var this$1 = this;
5569
5570 this.isNamespace = true;
5571 this.module = module;
5572 this.name = module.basename();
5573
5574 this.needsNamespaceBlock = false;
5575
5576 this.originals = blank();
5577 module.getExports().concat( module.getReexports() ).forEach( function (name) {
5578 this$1.originals[ name ] = module.traceExport( name );
5579 });
5580};
5581
5582SyntheticNamespaceDeclaration.prototype.activate = function activate () {
5583 this.needsNamespaceBlock = true;
5584
5585 // add synthetic references, in case of chained
5586 // namespace imports
5587 forOwn( this.originals, function (original) {
5588 original.activate();
5589 });
5590};
5591
5592SyntheticNamespaceDeclaration.prototype.addReference = function addReference ( node ) {
5593 this.name = node.name;
5594};
5595
5596SyntheticNamespaceDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5597 values.add( UNKNOWN );
5598};
5599
5600SyntheticNamespaceDeclaration.prototype.getName = function getName () {
5601 return this.name;
5602};
5603
5604SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock ( es, legacy, indentString ) {
5605 var this$1 = this;
5606
5607 var members = keys( this.originals ).map( function (name) {
5608 var original = this$1.originals[ name ];
5609
5610 if ( original.isReassigned && !legacy ) {
5611 return (indentString + "get " + name + " () { return " + (original.getName( es )) + "; }");
5612 }
5613
5614 if ( legacy && ~reservedWords$1.indexOf( name ) ) { name = "'" + name + "'"; }
5615 return ("" + indentString + name + ": " + (original.getName( es )));
5616 });
5617
5618 var callee = legacy ? "(Object.freeze || Object)" : "Object.freeze";
5619 return ((this.module.bundle.varOrConst) + " " + (this.getName( es )) + " = " + callee + "({\n" + (members.join( ',\n' )) + "\n});\n\n");
5620};
5621
5622var ExternalDeclaration = function ExternalDeclaration ( module, name ) {
5623 this.module = module;
5624 this.name = name;
5625 this.safeName = null;
5626 this.isExternal = true;
5627
5628 this.activated = false;
5629
5630 this.isNamespace = name === '*';
5631};
5632
5633ExternalDeclaration.prototype.activate = function activate () {
5634 this.module.used = true;
5635 this.activated = true;
5636};
5637
5638ExternalDeclaration.prototype.addReference = function addReference ( reference ) {
5639 reference.declaration = this;
5640
5641 if ( this.name === 'default' || this.name === '*' ) {
5642 this.module.suggestName( reference.name );
5643 }
5644};
5645
5646ExternalDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5647 values.add( UNKNOWN );
5648};
5649
5650ExternalDeclaration.prototype.getName = function getName ( es ) {
5651 if ( this.name === '*' ) {
5652 return this.module.name;
5653 }
5654
5655 if ( this.name === 'default' ) {
5656 return this.module.exportsNamespace || ( !es && this.module.exportsNames ) ?
5657 ((this.module.name) + "__default") :
5658 this.module.name;
5659 }
5660
5661 return es ? this.safeName : ((this.module.name) + "." + (this.name));
5662};
5663
5664ExternalDeclaration.prototype.setSafeName = function setSafeName ( name ) {
5665 this.safeName = name;
5666};
5667
5668function extractNames ( param ) {
5669 var names = [];
5670 extractors[ param.type ]( names, param );
5671 return names;
5672}
5673
5674var extractors = {
5675 Identifier: function Identifier ( names, param ) {
5676 names.push( param.name );
5677 },
5678
5679 ObjectPattern: function ObjectPattern ( names, param ) {
5680 param.properties.forEach( function (prop) {
5681 extractors[ prop.value.type ]( names, prop.value );
5682 });
5683 },
5684
5685 ArrayPattern: function ArrayPattern ( names, param ) {
5686 param.elements.forEach( function (element) {
5687 if ( element ) { extractors[ element.type ]( names, element ); }
5688 });
5689 },
5690
5691 RestElement: function RestElement ( names, param ) {
5692 extractors[ param.argument.type ]( names, param.argument );
5693 },
5694
5695 AssignmentPattern: function AssignmentPattern ( names, param ) {
5696 extractors[ param.left.type ]( names, param.left );
5697 }
5698};
5699
5700var Node$1 = function Node () {};
5701
5702Node$1.prototype.bind = function bind () {
5703 this.eachChild( function (child) { return child.bind(); } );
5704};
5705
5706Node$1.prototype.eachChild = function eachChild ( callback ) {
5707 var this$1 = this;
5708
5709 for ( var key of this$1.keys ) {
5710 if ( this$1.shorthand && key === 'key' ) { continue; } // key and value are the same
5711
5712 var value = this$1[ key ];
5713
5714 if ( value ) {
5715 if ( 'length' in value ) {
5716 for ( var child of value ) {
5717 if ( child ) { callback( child ); }
5718 }
5719 } else if ( value ) {
5720 callback( value );
5721 }
5722 }
5723 }
5724};
5725
5726Node$1.prototype.findParent = function findParent ( selector ) {
5727 return selector.test( this.type ) ? this : this.parent.findParent( selector );
5728};
5729
5730Node$1.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5731 //this.eachChild( child => child.gatherPossibleValues( values ) );
5732 values.add( UNKNOWN );
5733};
5734
5735Node$1.prototype.getValue = function getValue () {
5736 return UNKNOWN;
5737};
5738
5739Node$1.prototype.hasEffects = function hasEffects () {
5740 var this$1 = this;
5741
5742 for ( var key of this$1.keys ) {
5743 var value = this$1[ key ];
5744
5745 if ( value ) {
5746 if ( 'length' in value ) {
5747 for ( var child of value ) {
5748 if ( child && child.hasEffects() ) {
5749 return true;
5750 }
5751 }
5752 } else if ( value.hasEffects() ) {
5753 return true;
5754 }
5755 }
5756 }
5757};
5758
5759Node$1.prototype.initialise = function initialise ( parentScope ) {
5760 this.initialiseScope( parentScope );
5761 this.initialiseNode( parentScope );
5762 this.initialiseChildren( parentScope );
5763};
5764
5765// Override if e.g. some children need to be initialised with the parent scope
5766Node$1.prototype.initialiseChildren = function initialiseChildren () {
5767 var this$1 = this;
5768
5769 this.eachChild( function (child) { return child.initialise( this$1.scope ); } );
5770};
5771
5772// Override to perform special initialisation steps after the scope is initialised
5773Node$1.prototype.initialiseNode = function initialiseNode () {};
5774
5775// Overwrite to create a new scope
5776Node$1.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5777 this.scope = parentScope;
5778};
5779
5780Node$1.prototype.insertSemicolon = function insertSemicolon ( code ) {
5781 if ( code.original[ this.end - 1 ] !== ';' ) {
5782 code.appendLeft( this.end, ';' );
5783 }
5784};
5785
5786Node$1.prototype.locate = function locate$1 () {
5787 // useful for debugging
5788 var location = locate( this.module.code, this.start, { offsetLine: 1 } );
5789 location.file = this.module.id;
5790 location.toString = function () { return JSON.stringify( location ); };
5791
5792 return location;
5793};
5794
5795Node$1.prototype.render = function render ( code, es ) {
5796 this.eachChild( function (child) { return child.render( code, es ); } );
5797};
5798
5799Node$1.prototype.run = function run () {
5800 if ( this.ran ) { return; }
5801 this.ran = true;
5802
5803 this.eachChild( function (child) { return child.run(); } );
5804};
5805
5806Node$1.prototype.toString = function toString () {
5807 return this.module.code.slice( this.start, this.end );
5808};
5809
5810var ArrayExpression = (function (Node) {
5811 function ArrayExpression () {
5812 Node.apply(this, arguments);
5813 }
5814
5815 if ( Node ) ArrayExpression.__proto__ = Node;
5816 ArrayExpression.prototype = Object.create( Node && Node.prototype );
5817 ArrayExpression.prototype.constructor = ArrayExpression;
5818
5819 ArrayExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5820 values.add( ARRAY );
5821 };
5822
5823 return ArrayExpression;
5824}(Node$1));
5825
5826var Parameter = function Parameter ( name ) {
5827 this.name = name;
5828
5829 this.isParam = true;
5830 this.activated = true;
5831};
5832
5833Parameter.prototype.activate = function activate () {
5834 // noop
5835};
5836
5837Parameter.prototype.addReference = function addReference () {
5838 // noop?
5839};
5840
5841Parameter.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5842 values.add( UNKNOWN ); // TODO populate this at call time
5843};
5844
5845Parameter.prototype.getName = function getName () {
5846 return this.name;
5847};
5848
5849var Scope = function Scope ( options ) {
5850 if ( options === void 0 ) options = {};
5851
5852 this.parent = options.parent;
5853 this.isBlockScope = !!options.isBlockScope;
5854 this.isLexicalBoundary = !!options.isLexicalBoundary;
5855 this.isModuleScope = !!options.isModuleScope;
5856
5857 this.children = [];
5858 if ( this.parent ) { this.parent.children.push( this ); }
5859
5860 this.declarations = blank();
5861
5862 if ( this.isLexicalBoundary && !this.isModuleScope ) {
5863 this.declarations.arguments = new Parameter( 'arguments' );
5864 }
5865};
5866
5867Scope.prototype.addDeclaration = function addDeclaration ( name, declaration, isVar, isParam ) {
5868 if ( isVar && this.isBlockScope ) {
5869 this.parent.addDeclaration( name, declaration, isVar, isParam );
5870 } else {
5871 var existingDeclaration = this.declarations[ name ];
5872
5873 if ( existingDeclaration && existingDeclaration.duplicates ) {
5874 // TODO warn/throw on duplicates?
5875 existingDeclaration.duplicates.push( declaration );
5876 } else {
5877 this.declarations[ name ] = isParam ? new Parameter( name ) : declaration;
5878 }
5879 }
5880};
5881
5882Scope.prototype.contains = function contains ( name ) {
5883 return !!this.declarations[ name ] ||
5884 ( this.parent ? this.parent.contains( name ) : false );
5885};
5886
5887Scope.prototype.deshadow = function deshadow ( names ) {
5888 var this$1 = this;
5889
5890 keys( this.declarations ).forEach( function (key) {
5891 var declaration = this$1.declarations[ key ];
5892
5893 // we can disregard exports.foo etc
5894 if ( declaration.exportName && declaration.isReassigned ) { return; }
5895
5896 var name = declaration.getName( true );
5897 var deshadowed = name;
5898
5899 var i = 1;
5900
5901 while ( names.has( deshadowed ) ) {
5902 deshadowed = name + "$$" + (i++);
5903 }
5904
5905 declaration.name = deshadowed;
5906 });
5907
5908 this.children.forEach( function (scope) { return scope.deshadow( names ); } );
5909};
5910
5911Scope.prototype.findDeclaration = function findDeclaration ( name ) {
5912 return this.declarations[ name ] ||
5913 ( this.parent && this.parent.findDeclaration( name ) );
5914};
5915
5916Scope.prototype.findLexicalBoundary = function findLexicalBoundary () {
5917 return this.isLexicalBoundary ? this : this.parent.findLexicalBoundary();
5918};
5919
5920var Function$1 = (function (Node) {
5921 function Function () {
5922 Node.apply(this, arguments);
5923 }
5924
5925 if ( Node ) Function.__proto__ = Node;
5926 Function.prototype = Object.create( Node && Node.prototype );
5927 Function.prototype.constructor = Function;
5928
5929 Function.prototype.bind = function bind () {
5930 if ( this.id ) { this.id.bind(); }
5931 this.params.forEach( function (param) { return param.bind(); } );
5932 this.body.bind();
5933 };
5934
5935 Function.prototype.hasEffects = function hasEffects () {
5936 return false;
5937 };
5938
5939 Function.prototype.initialiseChildren = function initialiseChildren () {
5940 var this$1 = this;
5941
5942 this.params.forEach( function (param) {
5943 param.initialise( this$1.scope );
5944 extractNames( param ).forEach( function (name) { return this$1.scope.addDeclaration( name, null, false, true ); } );
5945 } );
5946 this.body.initialiseAndReplaceScope ?
5947 this.body.initialiseAndReplaceScope( this.scope ) :
5948 this.body.initialise( this.scope );
5949 };
5950
5951 Function.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5952 this.scope = new Scope( {
5953 parent: parentScope,
5954 isBlockScope: false,
5955 isLexicalBoundary: true
5956 } );
5957 };
5958
5959 return Function;
5960}(Node$1));
5961
5962var ArrowFunctionExpression = (function (Function) {
5963 function ArrowFunctionExpression () {
5964 Function.apply(this, arguments);
5965 }
5966
5967 if ( Function ) ArrowFunctionExpression.__proto__ = Function;
5968 ArrowFunctionExpression.prototype = Object.create( Function && Function.prototype );
5969 ArrowFunctionExpression.prototype.constructor = ArrowFunctionExpression;
5970
5971 ArrowFunctionExpression.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5972 this.scope = new Scope( {
5973 parent: parentScope,
5974 isBlockScope: false,
5975 isLexicalBoundary: false
5976 } );
5977 };
5978
5979 return ArrowFunctionExpression;
5980}(Function$1));
5981
5982// TODO tidy this up a bit (e.g. they can both use node.module.imports)
5983function disallowIllegalReassignment ( scope, node ) {
5984 if ( node.type === 'MemberExpression' && node.object.type === 'Identifier' ) {
5985 var declaration = scope.findDeclaration( node.object.name );
5986 if ( declaration.isNamespace ) {
5987 node.module.error({
5988 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
5989 message: ("Illegal reassignment to import '" + (node.object.name) + "'")
5990 }, node.start );
5991 }
5992 }
5993
5994 else if ( node.type === 'Identifier' ) {
5995 if ( node.module.imports[ node.name ] && !scope.contains( node.name ) ) {
5996 node.module.error({
5997 code: 'ILLEGAL_REASSIGNMENT',
5998 message: ("Illegal reassignment to import '" + (node.name) + "'")
5999 }, node.start );
6000 }
6001 }
6002}
6003
6004function isUsedByBundle ( scope, node ) {
6005 // const expression = node;
6006 while ( node.type === 'MemberExpression' ) { node = node.object; }
6007
6008 var declaration = scope.findDeclaration( node.name );
6009
6010 if ( declaration.isParam ) {
6011 return true;
6012
6013 // TODO if we mutate a parameter, assume the worst
6014 // return node !== expression;
6015 }
6016
6017 if ( declaration.activated ) { return true; }
6018
6019 var values = new Set();
6020 declaration.gatherPossibleValues( values );
6021 for ( var value of values ) {
6022 if ( value === UNKNOWN ) {
6023 return true;
6024 }
6025
6026 if ( value.type === 'Identifier' ) {
6027 if ( value.declaration.activated ) {
6028 return true;
6029 }
6030 value.declaration.gatherPossibleValues( values );
6031 }
6032
6033 else if ( value.gatherPossibleValues ) {
6034 value.gatherPossibleValues( values );
6035 }
6036 }
6037
6038 return false;
6039}
6040
6041function isProgramLevel ( node ) {
6042 do {
6043 if ( node.type === 'Program' ) {
6044 return true;
6045 }
6046 node = node.parent;
6047 } while ( node && !/Function/.test( node.type ) );
6048
6049 return false;
6050}
6051
6052var AssignmentExpression = (function (Node) {
6053 function AssignmentExpression () {
6054 Node.apply(this, arguments);
6055 }
6056
6057 if ( Node ) AssignmentExpression.__proto__ = Node;
6058 AssignmentExpression.prototype = Object.create( Node && Node.prototype );
6059 AssignmentExpression.prototype.constructor = AssignmentExpression;
6060
6061 AssignmentExpression.prototype.bind = function bind () {
6062 var subject = this.left;
6063
6064 this.subject = subject;
6065 disallowIllegalReassignment( this.scope, subject );
6066
6067 if ( subject.type === 'Identifier' ) {
6068 var declaration = this.scope.findDeclaration( subject.name );
6069 declaration.isReassigned = true;
6070
6071 if ( declaration.possibleValues ) { // TODO this feels hacky
6072 if ( this.operator === '=' ) {
6073 declaration.possibleValues.add( this.right );
6074 } else if ( this.operator === '+=' ) {
6075 declaration.possibleValues.add( STRING ).add( NUMBER );
6076 } else {
6077 declaration.possibleValues.add( NUMBER );
6078 }
6079 }
6080 }
6081
6082 Node.prototype.bind.call(this);
6083 };
6084
6085 AssignmentExpression.prototype.hasEffects = function hasEffects () {
6086 var hasEffects = this.isUsedByBundle() || this.right.hasEffects();
6087 return hasEffects;
6088 };
6089
6090 AssignmentExpression.prototype.initialiseNode = function initialiseNode () {
6091 if ( isProgramLevel( this ) ) {
6092 this.module.bundle.dependentExpressions.push( this );
6093 }
6094 };
6095
6096 AssignmentExpression.prototype.isUsedByBundle = function isUsedByBundle$1 () {
6097 return isUsedByBundle( this.scope, this.subject );
6098 };
6099
6100 return AssignmentExpression;
6101}(Node$1));
6102
6103var operators = {
6104 '==': function ( left, right ) { return left == right; },
6105 '!=': function ( left, right ) { return left != right; },
6106 '===': function ( left, right ) { return left === right; },
6107 '!==': function ( left, right ) { return left !== right; },
6108 '<': function ( left, right ) { return left < right; },
6109 '<=': function ( left, right ) { return left <= right; },
6110 '>': function ( left, right ) { return left > right; },
6111 '>=': function ( left, right ) { return left >= right; },
6112 '<<': function ( left, right ) { return left << right; },
6113 '>>': function ( left, right ) { return left >> right; },
6114 '>>>': function ( left, right ) { return left >>> right; },
6115 '+': function ( left, right ) { return left + right; },
6116 '-': function ( left, right ) { return left - right; },
6117 '*': function ( left, right ) { return left * right; },
6118 '/': function ( left, right ) { return left / right; },
6119 '%': function ( left, right ) { return left % right; },
6120 '|': function ( left, right ) { return left | right; },
6121 '^': function ( left, right ) { return left ^ right; },
6122 '&': function ( left, right ) { return left & right; },
6123 '**': function ( left, right ) { return Math.pow( left, right ); },
6124 in: function ( left, right ) { return left in right; },
6125 instanceof: function ( left, right ) { return left instanceof right; }
6126};
6127
6128var BinaryExpression = (function (Node) {
6129 function BinaryExpression () {
6130 Node.apply(this, arguments);
6131 }
6132
6133 if ( Node ) BinaryExpression.__proto__ = Node;
6134 BinaryExpression.prototype = Object.create( Node && Node.prototype );
6135 BinaryExpression.prototype.constructor = BinaryExpression;
6136
6137 BinaryExpression.prototype.getValue = function getValue () {
6138 var leftValue = this.left.getValue();
6139 if ( leftValue === UNKNOWN ) { return UNKNOWN; }
6140
6141 var rightValue = this.right.getValue();
6142 if ( rightValue === UNKNOWN ) { return UNKNOWN; }
6143
6144 if ( !operators[ this.operator ] ) { return UNKNOWN; }
6145
6146 return operators[ this.operator ]( leftValue, rightValue );
6147 };
6148
6149 return BinaryExpression;
6150}(Node$1));
6151
6152var Statement = (function (Node) {
6153 function Statement () {
6154 Node.apply(this, arguments);
6155 }
6156
6157 if ( Node ) Statement.__proto__ = Node;
6158 Statement.prototype = Object.create( Node && Node.prototype );
6159 Statement.prototype.constructor = Statement;
6160
6161 Statement.prototype.render = function render ( code, es ) {
6162 if ( !this.module.bundle.treeshake || this.shouldInclude ) {
6163 Node.prototype.render.call( this, code, es );
6164 } else {
6165 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6166 }
6167 };
6168
6169 Statement.prototype.run = function run () {
6170 this.shouldInclude = true;
6171 Node.prototype.run.call(this);
6172 };
6173
6174 return Statement;
6175}(Node$1));
6176
6177var BlockStatement = (function (Statement$$1) {
6178 function BlockStatement () {
6179 Statement$$1.apply(this, arguments);
6180 }
6181
6182 if ( Statement$$1 ) BlockStatement.__proto__ = Statement$$1;
6183 BlockStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6184 BlockStatement.prototype.constructor = BlockStatement;
6185
6186 BlockStatement.prototype.bind = function bind () {
6187 this.body.forEach( function (node) { return node.bind(); } );
6188 };
6189
6190 BlockStatement.prototype.initialiseAndReplaceScope = function initialiseAndReplaceScope ( scope ) {
6191 this.scope = scope;
6192 this.initialiseNode();
6193 this.initialiseChildren( scope );
6194 };
6195
6196 BlockStatement.prototype.initialiseChildren = function initialiseChildren () {
6197 var this$1 = this;
6198
6199 var lastNode;
6200 for ( var node of this$1.body ) {
6201 node.initialise( this$1.scope );
6202
6203 if ( lastNode ) { lastNode.next = node.start; }
6204 lastNode = node;
6205 }
6206 };
6207
6208 BlockStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6209 this.scope = new Scope( {
6210 parent: parentScope,
6211 isBlockScope: true,
6212 isLexicalBoundary: false
6213 } );
6214 };
6215
6216 BlockStatement.prototype.render = function render ( code, es ) {
6217 var this$1 = this;
6218
6219 if ( this.body.length ) {
6220 for ( var node of this$1.body ) {
6221 node.render( code, es );
6222 }
6223 } else {
6224 Statement$$1.prototype.render.call( this, code, es );
6225 }
6226 };
6227
6228 return BlockStatement;
6229}(Statement));
6230
6231function isReference (node, parent) {
6232 if (node.type === 'MemberExpression') {
6233 return !node.computed && isReference(node.object, node);
6234 }
6235
6236 if (node.type === 'Identifier') {
6237 // the only time we could have an identifier node without a parent is
6238 // if it's the entire body of a function without a block statement –
6239 // i.e. an arrow function expression like `a => a`
6240 if (!parent) return true;
6241
6242 // TODO is this right?
6243 if (parent.type === 'MemberExpression' || parent.type === 'MethodDefinition') {
6244 return parent.computed || node === parent.object;
6245 }
6246
6247 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6248 if (parent.type === 'Property') return parent.computed || node === parent.value;
6249
6250 // disregard the `bar` in `class Foo { bar () {...} }`
6251 if (parent.type === 'MethodDefinition') return false;
6252
6253 // disregard the `bar` in `export { foo as bar }`
6254 if (parent.type === 'ExportSpecifier' && node !== parent.local) return false;
6255
6256 return true;
6257 }
6258
6259 return false;
6260}
6261
6262function flatten ( node ) {
6263 var parts = [];
6264 while ( node.type === 'MemberExpression' ) {
6265 if ( node.computed ) { return null; }
6266 parts.unshift( node.property.name );
6267
6268 node = node.object;
6269 }
6270
6271 if ( node.type !== 'Identifier' ) { return null; }
6272
6273 var name = node.name;
6274 parts.unshift( name );
6275
6276 return { name: name, keypath: parts.join( '.' ) };
6277}
6278
6279var pureFunctions = {};
6280
6281var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split( ' ' );
6282var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split( ' ' );
6283var 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( ' ' );
6284var allSimdMethods = [];
6285simdTypes.forEach( function (t) {
6286 simdMethods.forEach( function (m) {
6287 allSimdMethods.push( ("SIMD." + t + "." + m) );
6288 });
6289});
6290
6291[
6292 'Array.isArray',
6293 'Error', 'EvalError', 'InternalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',
6294 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'unescape',
6295 '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',
6296 'Function', 'Boolean',
6297 'Number', 'Number.isFinite', 'Number.isInteger', 'Number.isNaN', 'Number.isSafeInteger', 'Number.parseFloat', 'Number.parseInt',
6298 'Symbol', 'Symbol.for', 'Symbol.keyFor',
6299 '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',
6300 'Date', 'Date.UTC', 'Date.now', 'Date.parse',
6301 'String', 'String.fromCharCode', 'String.fromCodePoint', 'String.raw',
6302 'RegExp',
6303 'Map', 'Set', 'WeakMap', 'WeakSet',
6304 'ArrayBuffer', 'ArrayBuffer.isView',
6305 'DataView',
6306 'JSON.parse', 'JSON.stringify',
6307 'Promise', 'Promise.all', 'Promise.race', 'Promise.reject', 'Promise.resolve',
6308 'Intl.Collator', 'Intl.Collator.supportedLocalesOf', 'Intl.DateTimeFormat', 'Intl.DateTimeFormat.supportedLocalesOf', 'Intl.NumberFormat', 'Intl.NumberFormat.supportedLocalesOf'
6309
6310 // TODO properties of e.g. window...
6311].concat(
6312 arrayTypes,
6313 arrayTypes.map( function (t) { return (t + ".from"); } ),
6314 arrayTypes.map( function (t) { return (t + ".of"); } ),
6315 simdTypes.map( function (t) { return ("SIMD." + t); } ),
6316 allSimdMethods
6317).forEach( function (name) { return pureFunctions[ name ] = true; } );
6318
6319var currentlyCalling = new Set();
6320
6321function isES5Function ( node ) {
6322 return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
6323}
6324
6325function hasEffectsNew ( node ) {
6326 var inner = node;
6327
6328 if ( inner.type === 'ExpressionStatement' ) {
6329 inner = inner.expression;
6330
6331 if ( inner.type === 'AssignmentExpression' ) {
6332 if ( inner.right.hasEffects() ) {
6333 return true;
6334
6335 } else {
6336 inner = inner.left;
6337
6338 if ( inner.type === 'MemberExpression' ) {
6339 if ( inner.computed && inner.property.hasEffects() ) {
6340 return true;
6341
6342 } else {
6343 inner = inner.object;
6344
6345 if ( inner.type === 'ThisExpression' ) {
6346 return false;
6347 }
6348 }
6349 }
6350 }
6351 }
6352 }
6353
6354 return node.hasEffects();
6355}
6356
6357function fnHasEffects ( fn, isNew ) {
6358 if ( currentlyCalling.has( fn ) ) { return false; } // prevent infinite loops... TODO there must be a better way
6359 currentlyCalling.add( fn );
6360
6361 // handle body-less arrow functions
6362 var body = fn.body.type === 'BlockStatement' ? fn.body.body : [ fn.body ];
6363
6364 for ( var node of body ) {
6365 if ( isNew ? hasEffectsNew( node ) : node.hasEffects() ) {
6366 currentlyCalling.delete( fn );
6367 return true;
6368 }
6369 }
6370
6371 currentlyCalling.delete( fn );
6372 return false;
6373}
6374
6375function callHasEffects ( scope, callee, isNew ) {
6376 var values = new Set( [ callee ] );
6377
6378 for ( var node of values ) {
6379 if ( node === UNKNOWN ) { return true; } // err on side of caution
6380
6381 if ( /Function/.test( node.type ) ) {
6382 if ( fnHasEffects( node, isNew && isES5Function( node ) ) ) { return true; }
6383 }
6384
6385 else if ( /Class/.test( node.type ) ) {
6386 // TODO find constructor (may belong to a superclass)
6387 return true;
6388 }
6389
6390 else if ( isReference( node ) ) {
6391 var flattened = flatten( node );
6392 var declaration = scope.findDeclaration( flattened.name );
6393
6394 if ( declaration.isGlobal ) {
6395 if ( !pureFunctions[ flattened.keypath ] ) { return true; }
6396 }
6397
6398 else if ( declaration.isExternal ) {
6399 return true; // TODO make this configurable? e.g. `path.[whatever]`
6400 }
6401
6402 else {
6403 if ( node.declaration ) {
6404 node.declaration.gatherPossibleValues( values );
6405 } else {
6406 return true;
6407 }
6408 }
6409 }
6410
6411 else if ( node.gatherPossibleValues ) {
6412 node.gatherPossibleValues( values );
6413 }
6414
6415 else {
6416 // probably an error in the user's code — err on side of caution
6417 return true;
6418 }
6419 }
6420
6421 return false;
6422}
6423
6424var CallExpression = (function (Node) {
6425 function CallExpression () {
6426 Node.apply(this, arguments);
6427 }
6428
6429 if ( Node ) CallExpression.__proto__ = Node;
6430 CallExpression.prototype = Object.create( Node && Node.prototype );
6431 CallExpression.prototype.constructor = CallExpression;
6432
6433 CallExpression.prototype.bind = function bind () {
6434 if ( this.callee.type === 'Identifier' ) {
6435 var declaration = this.scope.findDeclaration( this.callee.name );
6436
6437 if ( declaration.isNamespace ) {
6438 this.module.error( {
6439 code: 'CANNOT_CALL_NAMESPACE',
6440 message: ("Cannot call a namespace ('" + (this.callee.name) + "')")
6441 }, this.start );
6442 }
6443
6444 if ( this.callee.name === 'eval' && declaration.isGlobal ) {
6445 this.module.warn( {
6446 code: 'EVAL',
6447 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
6448 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval'
6449 }, this.start );
6450 }
6451 }
6452
6453 Node.prototype.bind.call(this);
6454 };
6455
6456 CallExpression.prototype.hasEffects = function hasEffects () {
6457 return callHasEffects( this.scope, this.callee, false );
6458 };
6459
6460 CallExpression.prototype.initialiseNode = function initialiseNode () {
6461 if ( isProgramLevel( this ) ) {
6462 this.module.bundle.dependentExpressions.push( this );
6463 }
6464 };
6465
6466 CallExpression.prototype.isUsedByBundle = function isUsedByBundle () {
6467 return this.hasEffects();
6468 };
6469
6470 return CallExpression;
6471}(Node$1));
6472
6473var CatchClause = (function (Node) {
6474 function CatchClause () {
6475 Node.apply(this, arguments);
6476 }
6477
6478 if ( Node ) CatchClause.__proto__ = Node;
6479 CatchClause.prototype = Object.create( Node && Node.prototype );
6480 CatchClause.prototype.constructor = CatchClause;
6481
6482 CatchClause.prototype.initialiseChildren = function initialiseChildren () {
6483 var this$1 = this;
6484
6485 if ( this.param ) {
6486 this.param.initialise( this.scope );
6487 extractNames( this.param ).forEach( function (name) { return this$1.scope.addDeclaration( name, null, false, true ); } );
6488 }
6489 this.body.initialiseAndReplaceScope( this.scope );
6490 };
6491
6492 CatchClause.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6493 this.scope = new Scope( {
6494 parent: parentScope,
6495 isBlockScope: true,
6496 isLexicalBoundary: false
6497 } );
6498 };
6499
6500 return CatchClause;
6501}(Node$1));
6502
6503var ClassExpression = (function (Node) {
6504 function ClassExpression () {
6505 Node.apply(this, arguments);
6506 }
6507
6508 if ( Node ) ClassExpression.__proto__ = Node;
6509 ClassExpression.prototype = Object.create( Node && Node.prototype );
6510 ClassExpression.prototype.constructor = ClassExpression;
6511
6512 ClassExpression.prototype.activate = function activate () {
6513 if ( this.activated ) { return; }
6514 this.activated = true;
6515
6516 if ( this.superClass ) { this.superClass.run(); }
6517 this.body.run();
6518 };
6519
6520 ClassExpression.prototype.addReference = function addReference () {};
6521
6522 ClassExpression.prototype.getName = function getName () {
6523 return this.name;
6524 };
6525
6526 ClassExpression.prototype.initialiseChildren = function initialiseChildren () {
6527 if ( this.superClass ) {
6528 this.superClass.initialise( this.scope );
6529 }
6530 this.body.initialise( this.scope );
6531 };
6532
6533 ClassExpression.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6534 this.scope = new Scope( {
6535 parent: parentScope,
6536 isBlockScope: true
6537 } );
6538 };
6539
6540 return ClassExpression;
6541}(Node$1));
6542
6543var ClassDeclaration = (function (Class$$1) {
6544 function ClassDeclaration () {
6545 Class$$1.apply(this, arguments);
6546 }
6547
6548 if ( Class$$1 ) ClassDeclaration.__proto__ = Class$$1;
6549 ClassDeclaration.prototype = Object.create( Class$$1 && Class$$1.prototype );
6550 ClassDeclaration.prototype.constructor = ClassDeclaration;
6551
6552 ClassDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6553 values.add( this );
6554 };
6555
6556 ClassDeclaration.prototype.hasEffects = function hasEffects () {
6557 return false;
6558 };
6559
6560 ClassDeclaration.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
6561 if ( this.id ) {
6562 this.name = this.id.name;
6563 parentScope.addDeclaration( this.name, this, false, false );
6564 this.id.initialise( parentScope );
6565 }
6566 Class$$1.prototype.initialiseChildren.call( this, parentScope );
6567 };
6568
6569 ClassDeclaration.prototype.render = function render ( code, es ) {
6570 if ( !this.module.bundle.treeshake || this.activated ) {
6571 Class$$1.prototype.render.call( this, code, es );
6572 } else {
6573 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6574 }
6575 };
6576
6577 ClassDeclaration.prototype.run = function run () {
6578 if ( this.parent.type === 'ExportDefaultDeclaration' ) {
6579 Class$$1.prototype.run.call(this);
6580 }
6581 };
6582
6583 return ClassDeclaration;
6584}(ClassExpression));
6585
6586var ClassExpression$1 = (function (Class) {
6587 function ClassExpression$$1 () {
6588 Class.apply(this, arguments);
6589 }
6590
6591 if ( Class ) ClassExpression$$1.__proto__ = Class;
6592 ClassExpression$$1.prototype = Object.create( Class && Class.prototype );
6593 ClassExpression$$1.prototype.constructor = ClassExpression$$1;
6594
6595 ClassExpression$$1.prototype.initialiseChildren = function initialiseChildren (parentScope) {
6596 if ( this.id ) {
6597 this.name = this.id.name;
6598 this.scope.addDeclaration( this.name, this, false, false );
6599 this.id.initialise( this.scope );
6600 }
6601 Class.prototype.initialiseChildren.call(this, parentScope);
6602 };
6603
6604 return ClassExpression$$1;
6605}(ClassExpression));
6606
6607var ConditionalExpression = (function (Node) {
6608 function ConditionalExpression () {
6609 Node.apply(this, arguments);
6610 }
6611
6612 if ( Node ) ConditionalExpression.__proto__ = Node;
6613 ConditionalExpression.prototype = Object.create( Node && Node.prototype );
6614 ConditionalExpression.prototype.constructor = ConditionalExpression;
6615
6616 ConditionalExpression.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
6617 if ( this.module.bundle.treeshake ) {
6618 this.testValue = this.test.getValue();
6619
6620 if ( this.testValue === UNKNOWN ) {
6621 Node.prototype.initialiseChildren.call( this, parentScope );
6622 } else if ( this.testValue ) {
6623 this.consequent.initialise( this.scope );
6624 this.alternate = null;
6625 } else if ( this.alternate ) {
6626 this.alternate.initialise( this.scope );
6627 this.consequent = null;
6628 }
6629 } else {
6630 Node.prototype.initialiseChildren.call( this, parentScope );
6631 }
6632 };
6633
6634 ConditionalExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6635 var testValue = this.test.getValue();
6636
6637 if ( testValue === UNKNOWN ) {
6638 values.add( this.consequent ).add( this.alternate );
6639 } else {
6640 values.add( testValue ? this.consequent : this.alternate );
6641 }
6642 };
6643
6644 ConditionalExpression.prototype.getValue = function getValue () {
6645 var testValue = this.test.getValue();
6646 if ( testValue === UNKNOWN ) { return UNKNOWN; }
6647
6648 return testValue ? this.consequent.getValue() : this.alternate.getValue();
6649 };
6650
6651 ConditionalExpression.prototype.render = function render ( code, es ) {
6652 if ( !this.module.bundle.treeshake ) {
6653 Node.prototype.render.call( this, code, es );
6654 }
6655
6656 else {
6657 if ( this.testValue === UNKNOWN ) {
6658 Node.prototype.render.call( this, code, es );
6659 }
6660
6661 else if ( this.testValue ) {
6662 code.remove( this.start, this.consequent.start );
6663 code.remove( this.consequent.end, this.end );
6664 if ( this.consequent.type === 'SequenceExpression' ) {
6665 code.prependRight( this.consequent.start, '(' );
6666 code.appendLeft( this.consequent.end, ')' );
6667 }
6668 this.consequent.render( code, es );
6669 } else {
6670 code.remove( this.start, this.alternate.start );
6671 code.remove( this.alternate.end, this.end );
6672 if ( this.alternate.type === 'SequenceExpression' ) {
6673 code.prependRight( this.alternate.start, '(' );
6674 code.appendLeft( this.alternate.end, ')' );
6675 }
6676 this.alternate.render( code, es );
6677 }
6678 }
6679 };
6680
6681 return ConditionalExpression;
6682}(Node$1));
6683
6684var EmptyStatement = (function (Statement$$1) {
6685 function EmptyStatement () {
6686 Statement$$1.apply(this, arguments);
6687 }
6688
6689 if ( Statement$$1 ) EmptyStatement.__proto__ = Statement$$1;
6690 EmptyStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6691 EmptyStatement.prototype.constructor = EmptyStatement;
6692
6693 EmptyStatement.prototype.render = function render ( code ) {
6694 if ( this.parent.type === 'BlockStatement' || this.parent.type === 'Program' ) {
6695 code.remove( this.start, this.end );
6696 }
6697 };
6698
6699 return EmptyStatement;
6700}(Statement));
6701
6702var ExportAllDeclaration = (function (Node) {
6703 function ExportAllDeclaration () {
6704 Node.apply(this, arguments);
6705 }
6706
6707 if ( Node ) ExportAllDeclaration.__proto__ = Node;
6708 ExportAllDeclaration.prototype = Object.create( Node && Node.prototype );
6709 ExportAllDeclaration.prototype.constructor = ExportAllDeclaration;
6710
6711 ExportAllDeclaration.prototype.initialiseNode = function initialiseNode () {
6712 this.isExportDeclaration = true;
6713 };
6714
6715 ExportAllDeclaration.prototype.render = function render ( code ) {
6716 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6717 };
6718
6719 return ExportAllDeclaration;
6720}(Node$1));
6721
6722var functionOrClassDeclaration = /^(?:Function|Class)Declaration/;
6723
6724var ExportDefaultDeclaration = (function (Node) {
6725 function ExportDefaultDeclaration () {
6726 Node.apply(this, arguments);
6727 }
6728
6729 if ( Node ) ExportDefaultDeclaration.__proto__ = Node;
6730 ExportDefaultDeclaration.prototype = Object.create( Node && Node.prototype );
6731 ExportDefaultDeclaration.prototype.constructor = ExportDefaultDeclaration;
6732
6733 ExportDefaultDeclaration.prototype.activate = function activate () {
6734 if ( this.activated ) { return; }
6735 this.activated = true;
6736
6737 this.run();
6738 };
6739
6740 ExportDefaultDeclaration.prototype.addReference = function addReference ( reference ) {
6741 this.name = reference.name;
6742 if ( this.original ) { this.original.addReference( reference ); }
6743 };
6744
6745 ExportDefaultDeclaration.prototype.bind = function bind () {
6746 var name = ( this.declaration.id && this.declaration.id.name ) || this.declaration.name;
6747 if ( name ) { this.original = this.scope.findDeclaration( name ); }
6748
6749 this.declaration.bind();
6750 };
6751
6752 ExportDefaultDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6753 this.declaration.gatherPossibleValues( values );
6754 };
6755
6756 ExportDefaultDeclaration.prototype.getName = function getName ( es ) {
6757 if ( this.original && !this.original.isReassigned ) {
6758 return this.original.getName( es );
6759 }
6760
6761 return this.name;
6762 };
6763
6764 ExportDefaultDeclaration.prototype.initialiseNode = function initialiseNode () {
6765 this.isExportDeclaration = true;
6766 this.isDefault = true;
6767
6768 this.name = ( this.declaration.id && this.declaration.id.name ) || this.declaration.name || this.module.basename();
6769 this.scope.declarations.default = this;
6770 };
6771
6772 // TODO this is total chaos, tidy it up
6773 ExportDefaultDeclaration.prototype.render = function render ( code, es ) {
6774 var treeshake = this.module.bundle.treeshake;
6775 var name = this.getName( es );
6776
6777 // paren workaround: find first non-whitespace character position after `export default`
6778 var declaration_start;
6779 if ( this.declaration ) {
6780 var statementStr = code.original.slice( this.start, this.end );
6781 declaration_start = this.start + statementStr.match( /^\s*export\s+default\s*/ )[ 0 ].length;
6782 }
6783
6784 if ( this.shouldInclude || this.declaration.activated ) {
6785 if ( this.activated ) {
6786 if ( functionOrClassDeclaration.test( this.declaration.type ) ) {
6787 if ( this.declaration.id ) {
6788 code.remove( this.start, declaration_start );
6789 } else {
6790 code.overwrite( this.start, declaration_start, ("var " + (this.name) + " = ") );
6791 if ( code.original[ this.end - 1 ] !== ';' ) { code.appendLeft( this.end, ';' ); }
6792 }
6793 }
6794
6795 else {
6796 if ( this.original && this.original.getName( es ) === name ) {
6797 // prevent `var foo = foo`
6798 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6799 return; // don't render children. TODO this seems like a bit of a hack
6800 } else {
6801 code.overwrite( this.start, declaration_start, ((this.module.bundle.varOrConst) + " " + name + " = ") );
6802 }
6803
6804 this.insertSemicolon( code );
6805 }
6806 } else {
6807 // remove `var foo` from `var foo = bar()`, if `foo` is unused
6808 code.remove( this.start, declaration_start );
6809 }
6810
6811 Node.prototype.render.call( this, code, es );
6812 } else {
6813 if ( treeshake ) {
6814 if ( functionOrClassDeclaration.test( this.declaration.type ) ) {
6815 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6816 } else {
6817 var hasEffects = this.declaration.hasEffects();
6818 code.remove( this.start, hasEffects ? declaration_start : this.next || this.end );
6819 }
6820 } else if ( name === this.declaration.name ) {
6821 code.remove( this.start, this.next || this.end );
6822 } else {
6823 code.overwrite( this.start, declaration_start, ((this.module.bundle.varOrConst) + " " + name + " = ") );
6824 }
6825 // code.remove( this.start, this.next || this.end );
6826 }
6827 };
6828
6829 ExportDefaultDeclaration.prototype.run = function run () {
6830 this.shouldInclude = true;
6831 Node.prototype.run.call(this);
6832
6833 // special case (TODO is this correct?)
6834 if ( functionOrClassDeclaration.test( this.declaration.type ) && !this.declaration.id ) {
6835 this.declaration.activate();
6836 }
6837 };
6838
6839 return ExportDefaultDeclaration;
6840}(Node$1));
6841
6842var ExportNamedDeclaration = (function (Node) {
6843 function ExportNamedDeclaration () {
6844 Node.apply(this, arguments);
6845 }
6846
6847 if ( Node ) ExportNamedDeclaration.__proto__ = Node;
6848 ExportNamedDeclaration.prototype = Object.create( Node && Node.prototype );
6849 ExportNamedDeclaration.prototype.constructor = ExportNamedDeclaration;
6850
6851 ExportNamedDeclaration.prototype.bind = function bind () {
6852 if ( this.declaration ) { this.declaration.bind(); }
6853 };
6854
6855 ExportNamedDeclaration.prototype.initialiseNode = function initialiseNode () {
6856 this.isExportDeclaration = true;
6857 };
6858
6859 ExportNamedDeclaration.prototype.render = function render ( code, es ) {
6860 if ( this.declaration ) {
6861 code.remove( this.start, this.declaration.start );
6862 this.declaration.render( code, es );
6863 } else {
6864 var start = this.leadingCommentStart || this.start;
6865 var end = this.next || this.end;
6866
6867 if ( this.defaultExport ) {
6868 var name = this.defaultExport.getName( es );
6869 var originalName = this.defaultExport.original.getName( es );
6870
6871 if ( name !== originalName ) {
6872 code.overwrite( start, end, ("var " + name + " = " + originalName + ";") );
6873 return;
6874 }
6875 }
6876
6877 code.remove( start, end );
6878 }
6879 };
6880
6881 return ExportNamedDeclaration;
6882}(Node$1));
6883
6884var ExpressionStatement = (function (Statement$$1) {
6885 function ExpressionStatement () {
6886 Statement$$1.apply(this, arguments);
6887 }
6888
6889 if ( Statement$$1 ) ExpressionStatement.__proto__ = Statement$$1;
6890 ExpressionStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6891 ExpressionStatement.prototype.constructor = ExpressionStatement;
6892
6893 ExpressionStatement.prototype.render = function render ( code, es ) {
6894 Statement$$1.prototype.render.call( this, code, es );
6895 if ( this.shouldInclude ) { this.insertSemicolon( code ); }
6896 };
6897
6898 return ExpressionStatement;
6899}(Statement));
6900
6901var ForStatement = (function (Statement$$1) {
6902 function ForStatement () {
6903 Statement$$1.apply(this, arguments);
6904 }
6905
6906 if ( Statement$$1 ) ForStatement.__proto__ = Statement$$1;
6907 ForStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6908 ForStatement.prototype.constructor = ForStatement;
6909
6910 ForStatement.prototype.initialiseChildren = function initialiseChildren () {
6911 if ( this.init ) { this.init.initialise( this.scope ); }
6912 if ( this.test ) { this.test.initialise( this.scope ); }
6913 if ( this.update ) { this.update.initialise( this.scope ); }
6914
6915 if ( this.body.type === 'BlockStatement' ) {
6916 this.body.initialiseScope( this.scope );
6917 this.body.initialiseChildren();
6918 } else {
6919 this.body.initialise( this.scope );
6920 }
6921 };
6922
6923 ForStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6924 this.scope = new Scope( {
6925 parent: parentScope,
6926 isBlockScope: true,
6927 isLexicalBoundary: false
6928 } );
6929 };
6930
6931 return ForStatement;
6932}(Statement));
6933
6934function assignToForLoopLeft ( node, scope, value ) {
6935 if ( node.type === 'VariableDeclaration' ) {
6936 for ( var proxy of node.declarations[0].proxies.values() ) {
6937 proxy.possibleValues.add( value );
6938 }
6939 }
6940
6941 else {
6942 if ( node.type === 'MemberExpression' ) {
6943 // apparently this is legal JavaScript? Though I don't know what
6944 // kind of monster would write `for ( foo.bar of thing ) {...}`
6945
6946 // for now, do nothing, as I'm not sure anything needs to happen...
6947 }
6948
6949 else {
6950 for ( var name of extractNames( node ) ) {
6951 var declaration = scope.findDeclaration( name );
6952 if ( declaration.possibleValues ) {
6953 declaration.possibleValues.add( value );
6954 }
6955 }
6956 }
6957 }
6958}
6959
6960var ForInStatement = (function (Statement$$1) {
6961 function ForInStatement () {
6962 Statement$$1.apply(this, arguments);
6963 }
6964
6965 if ( Statement$$1 ) ForInStatement.__proto__ = Statement$$1;
6966 ForInStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6967 ForInStatement.prototype.constructor = ForInStatement;
6968
6969 ForInStatement.prototype.initialiseChildren = function initialiseChildren () {
6970 this.left.initialise( this.scope );
6971 this.right.initialise( this.scope.parent );
6972 this.body.initialiseAndReplaceScope ?
6973 this.body.initialiseAndReplaceScope( this.scope ) :
6974 this.body.initialise( this.scope );
6975 assignToForLoopLeft( this.left, this.scope, STRING );
6976 };
6977
6978 ForInStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6979 this.scope = new Scope({
6980 parent: parentScope,
6981 isBlockScope: true,
6982 isLexicalBoundary: false
6983 });
6984 };
6985
6986 return ForInStatement;
6987}(Statement));
6988
6989var ForOfStatement = (function (Statement$$1) {
6990 function ForOfStatement () {
6991 Statement$$1.apply(this, arguments);
6992 }
6993
6994 if ( Statement$$1 ) ForOfStatement.__proto__ = Statement$$1;
6995 ForOfStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6996 ForOfStatement.prototype.constructor = ForOfStatement;
6997
6998 ForOfStatement.prototype.initialiseChildren = function initialiseChildren () {
6999 this.left.initialise( this.scope );
7000 this.right.initialise( this.scope.parent );
7001 this.body.initialiseAndReplaceScope ?
7002 this.body.initialiseAndReplaceScope( this.scope ) :
7003 this.body.initialise( this.scope );
7004 assignToForLoopLeft( this.left, this.scope, UNKNOWN );
7005 };
7006
7007 ForOfStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
7008 this.scope = new Scope( {
7009 parent: parentScope,
7010 isBlockScope: true,
7011 isLexicalBoundary: false
7012 } );
7013 };
7014
7015 return ForOfStatement;
7016}(Statement));
7017
7018var FunctionDeclaration = (function (Function) {
7019 function FunctionDeclaration () {
7020 Function.apply(this, arguments);
7021 }
7022
7023 if ( Function ) FunctionDeclaration.__proto__ = Function;
7024 FunctionDeclaration.prototype = Object.create( Function && Function.prototype );
7025 FunctionDeclaration.prototype.constructor = FunctionDeclaration;
7026
7027 FunctionDeclaration.prototype.activate = function activate () {
7028 if ( this.activated ) { return; }
7029 this.activated = true;
7030
7031 this.params.forEach( function (param) { return param.run(); } ); // in case of assignment patterns
7032 this.body.run();
7033 };
7034
7035 FunctionDeclaration.prototype.addReference = function addReference () {};
7036
7037 FunctionDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7038 values.add( this );
7039 };
7040
7041 FunctionDeclaration.prototype.getName = function getName () {
7042 return this.name;
7043 };
7044
7045 FunctionDeclaration.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7046 if ( this.id ) {
7047 this.name = this.id.name; // may be overridden by bundle.deconflict
7048 parentScope.addDeclaration( this.name, this, false, false );
7049 this.id.initialise( parentScope );
7050 }
7051 Function.prototype.initialiseChildren.call( this, parentScope );
7052 };
7053
7054 FunctionDeclaration.prototype.render = function render ( code, es ) {
7055 if ( !this.module.bundle.treeshake || this.activated ) {
7056 Function.prototype.render.call( this, code, es );
7057 } else {
7058 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
7059 }
7060 };
7061
7062 FunctionDeclaration.prototype.run = function run () {
7063 if ( this.parent.type === 'ExportDefaultDeclaration' ) {
7064 Function.prototype.run.call(this);
7065 }
7066 };
7067
7068 return FunctionDeclaration;
7069}(Function$1));
7070
7071var FunctionExpression = (function (Function) {
7072 function FunctionExpression () {
7073 Function.apply(this, arguments);
7074 }
7075
7076 if ( Function ) FunctionExpression.__proto__ = Function;
7077 FunctionExpression.prototype = Object.create( Function && Function.prototype );
7078 FunctionExpression.prototype.constructor = FunctionExpression;
7079
7080 FunctionExpression.prototype.activate = function activate () {
7081 if ( this.activated ) { return; }
7082 this.activated = true;
7083
7084 this.params.forEach( function (param) { return param.run(); } ); // in case of assignment patterns
7085 this.body.run();
7086 };
7087
7088 FunctionExpression.prototype.addReference = function addReference () {};
7089
7090 FunctionExpression.prototype.getName = function getName () {
7091 return this.name;
7092 };
7093
7094 FunctionExpression.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7095 if ( this.id ) {
7096 this.name = this.id.name; // may be overridden by bundle.deconflict
7097 this.scope.addDeclaration( this.name, this, false, false );
7098 this.id.initialise( this.scope );
7099 }
7100 Function.prototype.initialiseChildren.call( this, parentScope );
7101 };
7102
7103 return FunctionExpression;
7104}(Function$1));
7105
7106function isAssignmentPatternLhs (node, parent) {
7107 // special case: `({ foo = 42 }) => {...}`
7108 // `foo` actually has two different parents, the Property of the
7109 // ObjectPattern, and the AssignmentPattern. In one case it's a
7110 // reference, in one case it's not, because it's shorthand for
7111 // `({ foo: foo = 42 }) => {...}`. But unlike a regular shorthand
7112 // property, the `foo` node appears at different levels of the tree
7113 return (
7114 parent.type === "Property" &&
7115 parent.shorthand &&
7116 parent.value.type === "AssignmentPattern" &&
7117 parent.value.left === node
7118 );
7119}
7120
7121var Identifier = (function (Node) {
7122 function Identifier () {
7123 Node.apply(this, arguments);
7124 }
7125
7126 if ( Node ) Identifier.__proto__ = Node;
7127 Identifier.prototype = Object.create( Node && Node.prototype );
7128 Identifier.prototype.constructor = Identifier;
7129
7130 Identifier.prototype.bind = function bind () {
7131 if (isReference(this, this.parent) || isAssignmentPatternLhs(this, this.parent)) {
7132 this.declaration = this.scope.findDeclaration(this.name);
7133 this.declaration.addReference(this); // TODO necessary?
7134 }
7135 };
7136
7137 Identifier.prototype.gatherPossibleValues = function gatherPossibleValues (values) {
7138 if (isReference(this, this.parent)) {
7139 values.add(this);
7140 }
7141 };
7142
7143 Identifier.prototype.render = function render (code, es) {
7144 if (this.declaration) {
7145 var name = this.declaration.getName(es);
7146 if (name !== this.name) {
7147 code.overwrite(this.start, this.end, name, { storeName: true, contentOnly: false });
7148
7149 // special case
7150 if (this.parent.type === "Property" && this.parent.shorthand) {
7151 code.appendLeft(this.start, ((this.name) + ": "));
7152 }
7153 }
7154 }
7155 };
7156
7157 Identifier.prototype.run = function run () {
7158 if (this.declaration) { this.declaration.activate(); }
7159 };
7160
7161 return Identifier;
7162}(Node$1));
7163
7164// Statement types which may contain if-statements as direct children.
7165var statementsWithIfStatements = new Set( [
7166 'DoWhileStatement',
7167 'ForInStatement',
7168 'ForOfStatement',
7169 'ForStatement',
7170 'IfStatement',
7171 'WhileStatement'
7172] );
7173
7174function handleVarDeclarations ( node, scope ) {
7175 var hoistedVars = [];
7176
7177 function visit ( node ) {
7178 if ( node.type === 'VariableDeclaration' && node.kind === 'var' ) {
7179 node.declarations.forEach( function (declarator) {
7180 declarator.init = null;
7181 declarator.initialise( scope );
7182
7183 extractNames( declarator.id ).forEach( function (name) {
7184 if ( !~hoistedVars.indexOf( name ) ) { hoistedVars.push( name ); }
7185 } );
7186 } );
7187 }
7188
7189 else if ( !/Function/.test( node.type ) ) {
7190 node.eachChild( visit );
7191 }
7192 }
7193
7194 visit( node );
7195
7196 return hoistedVars;
7197}
7198
7199// TODO DRY this out
7200var IfStatement = (function (Statement$$1) {
7201 function IfStatement () {
7202 Statement$$1.apply(this, arguments);
7203 }
7204
7205 if ( Statement$$1 ) IfStatement.__proto__ = Statement$$1;
7206 IfStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
7207 IfStatement.prototype.constructor = IfStatement;
7208
7209 IfStatement.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7210 if ( this.module.bundle.treeshake ) {
7211 this.testValue = this.test.getValue();
7212
7213 if ( this.testValue === UNKNOWN ) {
7214 Statement$$1.prototype.initialiseChildren.call( this, parentScope );
7215 } else if ( this.testValue ) {
7216 this.consequent.initialise( this.scope );
7217 if ( this.alternate ) {
7218 this.hoistedVars = handleVarDeclarations( this.alternate, this.scope );
7219 this.alternate = null;
7220 }
7221 } else {
7222 if ( this.alternate ) {
7223 this.alternate.initialise( this.scope );
7224 }
7225 this.hoistedVars = handleVarDeclarations( this.consequent, this.scope );
7226 this.consequent = null;
7227 }
7228 } else {
7229 Statement$$1.prototype.initialiseChildren.call( this, parentScope );
7230 }
7231 };
7232
7233 IfStatement.prototype.render = function render ( code, es ) {
7234 var this$1 = this;
7235
7236 if ( this.module.bundle.treeshake ) {
7237 if ( this.testValue === UNKNOWN ) {
7238 Statement$$1.prototype.render.call( this, code, es );
7239 }
7240
7241 else {
7242 code.overwrite( this.test.start, this.test.end, JSON.stringify( this.testValue ) );
7243
7244 // TODO if no block-scoped declarations, remove enclosing
7245 // curlies and dedent block (if there is a block)
7246
7247 if ( this.hoistedVars ) {
7248 var names = this.hoistedVars
7249 .map( function (name) {
7250 var declaration = this$1.scope.findDeclaration( name );
7251 return declaration.activated ? declaration.getName() : null;
7252 } )
7253 .filter( Boolean );
7254
7255 if ( names.length > 0 ) {
7256 code.appendLeft( this.start, ("var " + (names.join( ', ' )) + ";\n\n") );
7257 }
7258 }
7259
7260 if ( this.testValue ) {
7261 code.remove( this.start, this.consequent.start );
7262 code.remove( this.consequent.end, this.end );
7263 this.consequent.render( code, es );
7264 }
7265
7266 else {
7267 code.remove( this.start, this.alternate ? this.alternate.start : this.next || this.end );
7268
7269 if ( this.alternate ) {
7270 this.alternate.render( code, es );
7271 }
7272
7273 else if ( statementsWithIfStatements.has( this.parent.type ) ) {
7274 code.prependRight( this.start, '{}' );
7275 }
7276 }
7277 }
7278 }
7279
7280 else {
7281 Statement$$1.prototype.render.call( this, code, es );
7282 }
7283 };
7284
7285 return IfStatement;
7286}(Statement));
7287
7288var ImportDeclaration = (function (Node) {
7289 function ImportDeclaration () {
7290 Node.apply(this, arguments);
7291 }
7292
7293 if ( Node ) ImportDeclaration.__proto__ = Node;
7294 ImportDeclaration.prototype = Object.create( Node && Node.prototype );
7295 ImportDeclaration.prototype.constructor = ImportDeclaration;
7296
7297 ImportDeclaration.prototype.bind = function bind () {
7298 // noop
7299 // TODO do the inter-module binding setup here?
7300 };
7301
7302 ImportDeclaration.prototype.initialiseNode = function initialiseNode () {
7303 this.isImportDeclaration = true;
7304 };
7305
7306 ImportDeclaration.prototype.render = function render ( code ) {
7307 code.remove( this.start, this.next || this.end );
7308 };
7309
7310 return ImportDeclaration;
7311}(Node$1));
7312
7313var Literal = (function (Node) {
7314 function Literal () {
7315 Node.apply(this, arguments);
7316 }
7317
7318 if ( Node ) Literal.__proto__ = Node;
7319 Literal.prototype = Object.create( Node && Node.prototype );
7320 Literal.prototype.constructor = Literal;
7321
7322 Literal.prototype.getValue = function getValue () {
7323 return this.value;
7324 };
7325
7326 Literal.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7327 values.add( this );
7328 };
7329
7330 Literal.prototype.render = function render ( code ) {
7331 if ( typeof this.value === 'string' ) {
7332 code.indentExclusionRanges.push( [ this.start + 1, this.end - 1 ] );
7333 }
7334 };
7335
7336 return Literal;
7337}(Node$1));
7338
7339var operators$1 = {
7340 '&&': function ( left, right ) { return left && right; },
7341 '||': function ( left, right ) { return left || right; }
7342};
7343
7344var LogicalExpression = (function (Node) {
7345 function LogicalExpression () {
7346 Node.apply(this, arguments);
7347 }
7348
7349 if ( Node ) LogicalExpression.__proto__ = Node;
7350 LogicalExpression.prototype = Object.create( Node && Node.prototype );
7351 LogicalExpression.prototype.constructor = LogicalExpression;
7352
7353 LogicalExpression.prototype.getValue = function getValue () {
7354 var leftValue = this.left.getValue();
7355 if ( leftValue === UNKNOWN ) { return UNKNOWN; }
7356
7357 var rightValue = this.right.getValue();
7358 if ( rightValue === UNKNOWN ) { return UNKNOWN; }
7359
7360 return operators$1[ this.operator ]( leftValue, rightValue );
7361 };
7362
7363 return LogicalExpression;
7364}(Node$1));
7365
7366var validProp = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
7367
7368var Keypath = function Keypath ( node ) {
7369 var this$1 = this;
7370
7371 this.parts = [];
7372
7373 while ( node.type === 'MemberExpression' ) {
7374 var prop = node.property;
7375
7376 if ( node.computed ) {
7377 if ( prop.type !== 'Literal' || typeof prop.value !== 'string' || !validProp.test( prop.value ) ) {
7378 this$1.computed = true;
7379 return;
7380 }
7381 }
7382
7383 this$1.parts.unshift( prop );
7384 node = node.object;
7385 }
7386
7387 this.root = node;
7388};
7389
7390var MemberExpression = (function (Node) {
7391 function MemberExpression () {
7392 Node.apply(this, arguments);
7393 }
7394
7395 if ( Node ) MemberExpression.__proto__ = Node;
7396 MemberExpression.prototype = Object.create( Node && Node.prototype );
7397 MemberExpression.prototype.constructor = MemberExpression;
7398
7399 MemberExpression.prototype.bind = function bind () {
7400 var this$1 = this;
7401
7402 // if this resolves to a namespaced declaration, prepare
7403 // to replace it
7404 // TODO this code is a bit inefficient
7405 var keypath = new Keypath( this );
7406
7407 if ( !keypath.computed && keypath.root.type === 'Identifier' ) {
7408 var declaration = this.scope.findDeclaration( keypath.root.name );
7409
7410 while ( declaration.isNamespace && keypath.parts.length ) {
7411 var exporterId = declaration.module.id;
7412
7413 var part = keypath.parts[ 0 ];
7414 declaration = declaration.module.traceExport( part.name || part.value );
7415
7416 if ( !declaration ) {
7417 this$1.module.warn( {
7418 code: 'MISSING_EXPORT',
7419 missing: part.name || part.value,
7420 importer: relativeId( this$1.module.id ),
7421 exporter: relativeId( exporterId ),
7422 message: ("'" + (part.name || part.value) + "' is not exported by '" + (relativeId( exporterId )) + "'"),
7423 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
7424 }, part.start );
7425 this$1.replacement = 'undefined';
7426 return;
7427 }
7428
7429 keypath.parts.shift();
7430 }
7431
7432 if ( keypath.parts.length ) {
7433 Node.prototype.bind.call(this);
7434 return; // not a namespaced declaration
7435 }
7436
7437 this.declaration = declaration;
7438
7439 if ( declaration.isExternal ) {
7440 declaration.module.suggestName( keypath.root.name );
7441 }
7442 }
7443
7444 else {
7445 Node.prototype.bind.call(this);
7446 }
7447 };
7448
7449 MemberExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7450 values.add( UNKNOWN ); // TODO
7451 };
7452
7453 MemberExpression.prototype.render = function render ( code, es ) {
7454 if ( this.declaration ) {
7455 var name = this.declaration.getName( es );
7456 if ( name !== this.name ) { code.overwrite( this.start, this.end, name, { storeName: true, contentOnly: false } ); }
7457 }
7458
7459 else if ( this.replacement ) {
7460 code.overwrite( this.start, this.end, this.replacement, { storeName: true, contentOnly: false } );
7461 }
7462
7463 Node.prototype.render.call( this, code, es );
7464 };
7465
7466 MemberExpression.prototype.run = function run () {
7467 if ( this.declaration ) { this.declaration.activate(); }
7468 Node.prototype.run.call(this);
7469 };
7470
7471 return MemberExpression;
7472}(Node$1));
7473
7474var NewExpression = (function (Node) {
7475 function NewExpression () {
7476 Node.apply(this, arguments);
7477 }
7478
7479 if ( Node ) NewExpression.__proto__ = Node;
7480 NewExpression.prototype = Object.create( Node && Node.prototype );
7481 NewExpression.prototype.constructor = NewExpression;
7482
7483 NewExpression.prototype.hasEffects = function hasEffects () {
7484 return callHasEffects( this.scope, this.callee, true );
7485 };
7486
7487 return NewExpression;
7488}(Node$1));
7489
7490var ObjectExpression = (function (Node) {
7491 function ObjectExpression () {
7492 Node.apply(this, arguments);
7493 }
7494
7495 if ( Node ) ObjectExpression.__proto__ = Node;
7496 ObjectExpression.prototype = Object.create( Node && Node.prototype );
7497 ObjectExpression.prototype.constructor = ObjectExpression;
7498
7499 ObjectExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7500 values.add( OBJECT );
7501 };
7502
7503 return ObjectExpression;
7504}(Node$1));
7505
7506var SwitchStatement = (function (Statement$$1) {
7507 function SwitchStatement () {
7508 Statement$$1.apply(this, arguments);
7509 }
7510
7511 if ( Statement$$1 ) SwitchStatement.__proto__ = Statement$$1;
7512 SwitchStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
7513 SwitchStatement.prototype.constructor = SwitchStatement;
7514
7515 SwitchStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
7516 this.scope = new Scope( {
7517 parent: parentScope,
7518 isBlockScope: true,
7519 isLexicalBoundary: false
7520 } );
7521 };
7522
7523 return SwitchStatement;
7524}(Statement));
7525
7526var TaggedTemplateExpression = (function (Node) {
7527 function TaggedTemplateExpression () {
7528 Node.apply(this, arguments);
7529 }
7530
7531 if ( Node ) TaggedTemplateExpression.__proto__ = Node;
7532 TaggedTemplateExpression.prototype = Object.create( Node && Node.prototype );
7533 TaggedTemplateExpression.prototype.constructor = TaggedTemplateExpression;
7534
7535 TaggedTemplateExpression.prototype.bind = function bind () {
7536 if ( this.tag.type === 'Identifier' ) {
7537 var declaration = this.scope.findDeclaration( this.tag.name );
7538
7539 if ( declaration.isNamespace ) {
7540 this.module.error({
7541 code: 'CANNOT_CALL_NAMESPACE',
7542 message: ("Cannot call a namespace ('" + (this.tag.name) + "')")
7543 }, this.start );
7544 }
7545
7546 if ( this.tag.name === 'eval' && declaration.isGlobal ) {
7547 this.module.warn({
7548 code: 'EVAL',
7549 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
7550 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval'
7551 }, this.start );
7552 }
7553 }
7554
7555 Node.prototype.bind.call(this);
7556 };
7557
7558 TaggedTemplateExpression.prototype.hasEffects = function hasEffects () {
7559 return this.quasi.hasEffects() || callHasEffects( this.scope, this.tag, false );
7560 };
7561
7562 TaggedTemplateExpression.prototype.initialiseNode = function initialiseNode () {
7563 if ( isProgramLevel( this ) ) {
7564 this.module.bundle.dependentExpressions.push( this );
7565 }
7566 };
7567
7568 TaggedTemplateExpression.prototype.isUsedByBundle = function isUsedByBundle () {
7569 return this.hasEffects();
7570 };
7571
7572 return TaggedTemplateExpression;
7573}(Node$1));
7574
7575var TemplateLiteral = (function (Node) {
7576 function TemplateLiteral () {
7577 Node.apply(this, arguments);
7578 }
7579
7580 if ( Node ) TemplateLiteral.__proto__ = Node;
7581 TemplateLiteral.prototype = Object.create( Node && Node.prototype );
7582 TemplateLiteral.prototype.constructor = TemplateLiteral;
7583
7584 TemplateLiteral.prototype.render = function render ( code, es ) {
7585 code.indentExclusionRanges.push( [ this.start, this.end ] );
7586 Node.prototype.render.call( this, code, es );
7587 };
7588
7589 return TemplateLiteral;
7590}(Node$1));
7591
7592var ThisExpression = (function (Node) {
7593 function ThisExpression () {
7594 Node.apply(this, arguments);
7595 }
7596
7597 if ( Node ) ThisExpression.__proto__ = Node;
7598 ThisExpression.prototype = Object.create( Node && Node.prototype );
7599 ThisExpression.prototype.constructor = ThisExpression;
7600
7601 ThisExpression.prototype.initialiseNode = function initialiseNode () {
7602 var lexicalBoundary = this.scope.findLexicalBoundary();
7603
7604 if ( lexicalBoundary.isModuleScope ) {
7605 this.alias = this.module.context;
7606 if ( this.alias === 'undefined' ) {
7607 this.module.warn( {
7608 code: 'THIS_IS_UNDEFINED',
7609 message: "The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten",
7610 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined"
7611 }, this.start );
7612 }
7613 }
7614 };
7615
7616 ThisExpression.prototype.render = function render ( code ) {
7617 if ( this.alias ) {
7618 code.overwrite( this.start, this.end, this.alias, { storeName: true, contentOnly: false } );
7619 }
7620 };
7621
7622 return ThisExpression;
7623}(Node$1));
7624
7625var ThrowStatement = (function (Node) {
7626 function ThrowStatement () {
7627 Node.apply(this, arguments);
7628 }
7629
7630 if ( Node ) ThrowStatement.__proto__ = Node;
7631 ThrowStatement.prototype = Object.create( Node && Node.prototype );
7632 ThrowStatement.prototype.constructor = ThrowStatement;
7633
7634 ThrowStatement.prototype.hasEffects = function hasEffects () {
7635 return true;
7636 };
7637
7638 return ThrowStatement;
7639}(Node$1));
7640
7641var operators$2 = {
7642 '-': function (value) { return -value; },
7643 '+': function (value) { return +value; },
7644 '!': function (value) { return !value; },
7645 '~': function (value) { return ~value; },
7646 typeof: function (value) { return typeof value; },
7647 void: function () { return undefined; },
7648 delete: function () { return UNKNOWN; }
7649};
7650
7651var UnaryExpression = (function (Node) {
7652 function UnaryExpression () {
7653 Node.apply(this, arguments);
7654 }
7655
7656 if ( Node ) UnaryExpression.__proto__ = Node;
7657 UnaryExpression.prototype = Object.create( Node && Node.prototype );
7658 UnaryExpression.prototype.constructor = UnaryExpression;
7659
7660 UnaryExpression.prototype.bind = function bind () {
7661 if ( this.value === UNKNOWN ) { Node.prototype.bind.call(this); }
7662 };
7663
7664 UnaryExpression.prototype.getValue = function getValue () {
7665 var argumentValue = this.argument.getValue();
7666 if ( argumentValue === UNKNOWN ) { return UNKNOWN; }
7667
7668 return operators$2[ this.operator ]( argumentValue );
7669 };
7670
7671 UnaryExpression.prototype.hasEffects = function hasEffects () {
7672 return this.operator === 'delete' || this.argument.hasEffects();
7673 };
7674
7675 UnaryExpression.prototype.initialiseNode = function initialiseNode () {
7676 this.value = this.getValue();
7677 };
7678
7679 return UnaryExpression;
7680}(Node$1));
7681
7682var UpdateExpression = (function (Node) {
7683 function UpdateExpression () {
7684 Node.apply(this, arguments);
7685 }
7686
7687 if ( Node ) UpdateExpression.__proto__ = Node;
7688 UpdateExpression.prototype = Object.create( Node && Node.prototype );
7689 UpdateExpression.prototype.constructor = UpdateExpression;
7690
7691 UpdateExpression.prototype.bind = function bind () {
7692 var subject = this.argument;
7693
7694 this.subject = subject;
7695 disallowIllegalReassignment( this.scope, this.argument );
7696
7697 if ( subject.type === 'Identifier' ) {
7698 var declaration = this.scope.findDeclaration( subject.name );
7699 declaration.isReassigned = true;
7700
7701 if ( declaration.possibleValues ) {
7702 declaration.possibleValues.add( NUMBER );
7703 }
7704 }
7705
7706 Node.prototype.bind.call(this);
7707 };
7708
7709 UpdateExpression.prototype.hasEffects = function hasEffects () {
7710 return isUsedByBundle( this.scope, this.subject );
7711 };
7712
7713 UpdateExpression.prototype.initialiseNode = function initialiseNode () {
7714 this.module.bundle.dependentExpressions.push( this );
7715 };
7716
7717 UpdateExpression.prototype.isUsedByBundle = function isUsedByBundle$1 () {
7718 return isUsedByBundle( this.scope, this.subject );
7719 };
7720
7721 return UpdateExpression;
7722}(Node$1));
7723
7724var DeclaratorProxy = function DeclaratorProxy ( name, declarator, isTopLevel, init ) {
7725 this.name = name;
7726 this.declarator = declarator;
7727
7728 this.activated = false;
7729 this.isReassigned = false;
7730 this.exportName = null;
7731
7732 this.duplicates = [];
7733 this.possibleValues = new Set( init ? [ init ] : null );
7734};
7735
7736DeclaratorProxy.prototype.activate = function activate () {
7737 this.activated = true;
7738 this.declarator.activate();
7739 this.duplicates.forEach( function (dupe) { return dupe.activate(); } );
7740};
7741
7742DeclaratorProxy.prototype.addReference = function addReference () {
7743 /* noop? */
7744};
7745
7746DeclaratorProxy.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7747 this.possibleValues.forEach( function (value) { return values.add( value ); } );
7748};
7749
7750DeclaratorProxy.prototype.getName = function getName ( es ) {
7751 // TODO desctructuring...
7752 if ( es ) { return this.name; }
7753 if ( !this.isReassigned || !this.exportName ) { return this.name; }
7754
7755 return ("exports." + (this.exportName));
7756};
7757
7758DeclaratorProxy.prototype.toString = function toString () {
7759 return this.name;
7760};
7761
7762var VariableDeclarator = (function (Node) {
7763 function VariableDeclarator () {
7764 Node.apply(this, arguments);
7765 }
7766
7767 if ( Node ) VariableDeclarator.__proto__ = Node;
7768 VariableDeclarator.prototype = Object.create( Node && Node.prototype );
7769 VariableDeclarator.prototype.constructor = VariableDeclarator;
7770
7771 VariableDeclarator.prototype.activate = function activate () {
7772 if ( this.activated ) { return; }
7773 this.activated = true;
7774
7775 this.run();
7776
7777 // if declaration is inside a block, ensure that the block
7778 // is marked for inclusion
7779 if ( this.parent.kind === 'var' ) {
7780 var node = this.parent.parent;
7781 while ( /Statement/.test( node.type ) ) {
7782 node.shouldInclude = true;
7783 node = node.parent;
7784 }
7785 }
7786 };
7787
7788 VariableDeclarator.prototype.hasEffects = function hasEffects () {
7789 return this.init && this.init.hasEffects();
7790 };
7791
7792 VariableDeclarator.prototype.initialiseNode = function initialiseNode () {
7793 var this$1 = this;
7794
7795 this.proxies = new Map();
7796 var lexicalBoundary = this.scope.findLexicalBoundary();
7797 var init = this.init ? ( this.id.type === 'Identifier' ? this.init : UNKNOWN ) : // TODO maybe UNKNOWN is unnecessary
7798 null;
7799
7800 extractNames( this.id ).forEach( function (name) {
7801 var proxy = new DeclaratorProxy( name, this$1, lexicalBoundary.isModuleScope, init );
7802
7803 this$1.proxies.set( name, proxy );
7804 this$1.scope.addDeclaration( name, proxy, this$1.parent.kind === 'var' );
7805 } );
7806 };
7807
7808 VariableDeclarator.prototype.render = function render ( code, es ) {
7809 var this$1 = this;
7810
7811 extractNames( this.id ).forEach( function (name) {
7812 var declaration = this$1.proxies.get( name );
7813
7814 if ( !es && declaration.exportName && declaration.isReassigned ) {
7815 if ( this$1.init ) {
7816 code.overwrite( this$1.start, this$1.id.end, declaration.getName( es ) );
7817 } else if ( this$1.module.bundle.treeshake ) {
7818 code.remove( this$1.start, this$1.end );
7819 }
7820 }
7821 } );
7822
7823 Node.prototype.render.call( this, code, es );
7824 };
7825
7826 return VariableDeclarator;
7827}(Node$1));
7828
7829function getSeparator (code, start) {
7830 var c = start;
7831
7832 while (c > 0 && code[c - 1] !== "\n") {
7833 c -= 1;
7834 if (code[c] === ";" || code[c] === "{") { return "; "; }
7835 }
7836
7837 var lineStart = code.slice(c, start).match(/^\s*/)[0];
7838
7839 return (";\n" + lineStart);
7840}
7841
7842var forStatement = /^For(?:Of|In)?Statement/;
7843
7844var VariableDeclaration = (function (Node) {
7845 function VariableDeclaration () {
7846 Node.apply(this, arguments);
7847 }
7848
7849 if ( Node ) VariableDeclaration.__proto__ = Node;
7850 VariableDeclaration.prototype = Object.create( Node && Node.prototype );
7851 VariableDeclaration.prototype.constructor = VariableDeclaration;
7852
7853 VariableDeclaration.prototype.render = function render (code, es) {
7854 var this$1 = this;
7855
7856 var treeshake = this.module.bundle.treeshake;
7857
7858 var shouldSeparate = false;
7859 var separator;
7860
7861 if (this.scope.isModuleScope && !forStatement.test(this.parent.type)) {
7862 shouldSeparate = true;
7863 separator = getSeparator(this.module.code, this.start);
7864 }
7865
7866 var c = this.start;
7867 var empty = true;
7868
7869 var loop = function ( i ) {
7870 var declarator = this$1.declarations[i];
7871
7872 var prefix = empty ? "" : separator; // TODO indentation
7873
7874 if (declarator.id.type === "Identifier") {
7875 var proxy = declarator.proxies.get(declarator.id.name);
7876 var isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned;
7877
7878 if (isExportedAndReassigned) {
7879 if (declarator.init) {
7880 if (shouldSeparate) { code.overwrite(c, declarator.start, prefix); }
7881 c = declarator.end;
7882 empty = false;
7883 }
7884 } else if (!treeshake || proxy.activated) {
7885 if (shouldSeparate) { code.overwrite(c, declarator.start, ("" + prefix + (this$1.kind) + " ")); } // TODO indentation
7886 c = declarator.end;
7887 empty = false;
7888 }
7889 } else {
7890 var exportAssignments = [];
7891 var activated = false;
7892
7893 extractNames(declarator.id).forEach(function (name) {
7894 var proxy = declarator.proxies.get(name);
7895 var isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned;
7896
7897 if (isExportedAndReassigned) {
7898 // code.overwrite( c, declarator.start, prefix );
7899 // c = declarator.end;
7900 // empty = false;
7901 exportAssignments.push("TODO");
7902 } else if (declarator.activated) {
7903 activated = true;
7904 }
7905 });
7906
7907 if (!treeshake || activated) {
7908 if (shouldSeparate) { code.overwrite(c, declarator.start, ("" + prefix + (this$1.kind) + " ")); } // TODO indentation
7909 c = declarator.end;
7910 empty = false;
7911 }
7912
7913 if (exportAssignments.length) {
7914 throw new Error("TODO");
7915 }
7916 }
7917
7918 declarator.render(code, es);
7919 };
7920
7921 for (var i = 0; i < this.declarations.length; i += 1) loop( i );
7922
7923 if (treeshake && empty) {
7924 code.remove(this.leadingCommentStart || this.start, this.next || this.end);
7925 } else {
7926 // always include a semi-colon (https://github.com/rollup/rollup/pull/1013),
7927 // unless it's a var declaration in a loop head
7928 var needsSemicolon = !forStatement.test( this.parent.type ) || this === this.parent.body;
7929
7930 if (this.end > c) {
7931 code.overwrite(c, this.end, needsSemicolon ? ";" : "");
7932 } else if (needsSemicolon) {
7933 this.insertSemicolon(code);
7934 }
7935 }
7936 };
7937
7938 return VariableDeclaration;
7939}(Node$1));
7940
7941var nodes = {
7942 ArrayExpression: ArrayExpression,
7943 ArrowFunctionExpression: ArrowFunctionExpression,
7944 AssignmentExpression: AssignmentExpression,
7945 BinaryExpression: BinaryExpression,
7946 BlockStatement: BlockStatement,
7947 CallExpression: CallExpression,
7948 CatchClause: CatchClause,
7949 ClassDeclaration: ClassDeclaration,
7950 ClassExpression: ClassExpression$1,
7951 ConditionalExpression: ConditionalExpression,
7952 DoWhileStatement: Statement,
7953 EmptyStatement: EmptyStatement,
7954 ExportAllDeclaration: ExportAllDeclaration,
7955 ExportDefaultDeclaration: ExportDefaultDeclaration,
7956 ExportNamedDeclaration: ExportNamedDeclaration,
7957 ExpressionStatement: ExpressionStatement,
7958 ForStatement: ForStatement,
7959 ForInStatement: ForInStatement,
7960 ForOfStatement: ForOfStatement,
7961 FunctionDeclaration: FunctionDeclaration,
7962 FunctionExpression: FunctionExpression,
7963 Identifier: Identifier,
7964 IfStatement: IfStatement,
7965 ImportDeclaration: ImportDeclaration,
7966 Literal: Literal,
7967 LogicalExpression: LogicalExpression,
7968 MemberExpression: MemberExpression,
7969 NewExpression: NewExpression,
7970 ObjectExpression: ObjectExpression,
7971 ReturnStatement: Statement,
7972 SwitchStatement: SwitchStatement,
7973 TaggedTemplateExpression: TaggedTemplateExpression,
7974 TemplateLiteral: TemplateLiteral,
7975 ThisExpression: ThisExpression,
7976 ThrowStatement: ThrowStatement,
7977 TryStatement: Statement,
7978 UnaryExpression: UnaryExpression,
7979 UpdateExpression: UpdateExpression,
7980 VariableDeclarator: VariableDeclarator,
7981 VariableDeclaration: VariableDeclaration,
7982 WhileStatement: Statement
7983};
7984
7985var keys$1 = {
7986 Program: [ 'body' ],
7987 Literal: []
7988};
7989
7990var newline = /\n/;
7991
7992function enhance ( ast, module, comments ) {
7993 enhanceNode( ast, module, module, module.magicString );
7994
7995 var comment = comments.shift();
7996
7997 for ( var node of ast.body ) {
7998 if ( comment && ( comment.start < node.start ) ) {
7999 node.leadingCommentStart = comment.start;
8000 }
8001
8002 while ( comment && comment.end < node.end ) { comment = comments.shift(); }
8003
8004 // if the next comment is on the same line as the end of the node,
8005 // treat is as a trailing comment
8006 if ( comment && !newline.test( module.code.slice( node.end, comment.start ) ) ) {
8007 node.trailingCommentEnd = comment.end; // TODO is node.trailingCommentEnd used anywhere?
8008 comment = comments.shift();
8009 }
8010
8011 node.initialise( module.scope );
8012 }
8013}
8014
8015function enhanceNode ( raw, parent, module, code ) {
8016 if ( !raw ) { return; }
8017
8018 if ( 'length' in raw ) {
8019 for ( var i = 0; i < raw.length; i += 1 ) {
8020 enhanceNode( raw[i], parent, module, code );
8021 }
8022
8023 return;
8024 }
8025
8026 // with e.g. shorthand properties, key and value are
8027 // the same node. We don't want to enhance an object twice
8028 if ( raw.__enhanced ) { return; }
8029 raw.__enhanced = true;
8030
8031 if ( !keys$1[ raw.type ] ) {
8032 keys$1[ raw.type ] = Object.keys( raw ).filter( function (key) { return typeof raw[ key ] === 'object'; } );
8033 }
8034
8035 raw.parent = parent;
8036 raw.module = module;
8037 raw.keys = keys$1[ raw.type ];
8038
8039 code.addSourcemapLocation( raw.start );
8040 code.addSourcemapLocation( raw.end );
8041
8042 for ( var key of keys$1[ raw.type ] ) {
8043 enhanceNode( raw[ key ], raw, module, code );
8044 }
8045
8046 var type = nodes[ raw.type ] || Node$1;
8047 raw.__proto__ = type.prototype;
8048}
8049
8050function clone ( node ) {
8051 if ( !node ) { return node; }
8052 if ( typeof node !== 'object' ) { return node; }
8053
8054 if ( Array.isArray( node ) ) {
8055 var cloned$1 = new Array( node.length );
8056 for ( var i = 0; i < node.length; i += 1 ) { cloned$1[i] = clone( node[i] ); }
8057 return cloned$1;
8058 }
8059
8060 var cloned = {};
8061 for ( var key in node ) {
8062 cloned[ key ] = clone( node[ key ] );
8063 }
8064
8065 return cloned;
8066}
8067
8068var ModuleScope = (function (Scope$$1) {
8069 function ModuleScope ( module ) {
8070 Scope$$1.call(this, {
8071 isBlockScope: false,
8072 isLexicalBoundary: true,
8073 isModuleScope: true,
8074 parent: module.bundle.scope
8075 });
8076
8077 this.module = module;
8078 }
8079
8080 if ( Scope$$1 ) ModuleScope.__proto__ = Scope$$1;
8081 ModuleScope.prototype = Object.create( Scope$$1 && Scope$$1.prototype );
8082 ModuleScope.prototype.constructor = ModuleScope;
8083
8084 ModuleScope.prototype.deshadow = function deshadow ( names ) {
8085 var this$1 = this;
8086
8087 names = new Set( names );
8088
8089 forOwn( this.module.imports, function (specifier) {
8090 if ( specifier.module.isExternal ) { return; }
8091
8092 var addDeclaration = function (declaration) {
8093 if ( declaration.isNamespace && !declaration.isExternal ) {
8094 declaration.module.getExports().forEach( function (name) {
8095 addDeclaration( declaration.module.traceExport(name) );
8096 });
8097 }
8098
8099 names.add( declaration.name );
8100 };
8101
8102 specifier.module.getExports().forEach( function (name) {
8103 addDeclaration( specifier.module.traceExport(name) );
8104 });
8105
8106 if ( specifier.name !== '*' ) {
8107 var declaration = specifier.module.traceExport( specifier.name );
8108 if ( !declaration ) {
8109 this$1.module.warn({
8110 code: 'NON_EXISTENT_EXPORT',
8111 name: specifier.name,
8112 source: specifier.module.id,
8113 message: ("Non-existent export '" + (specifier.name) + "' is imported from " + (relativeId( specifier.module.id )))
8114 }, specifier.specifier.start );
8115 return;
8116 }
8117
8118 var name = declaration.getName( true );
8119 if ( name !== specifier.name ) {
8120 names.add( declaration.getName( true ) );
8121 }
8122
8123 if ( specifier.name !== 'default' && specifier.specifier.imported.name !== specifier.specifier.local.name ) {
8124 names.add( specifier.specifier.imported.name );
8125 }
8126 }
8127 });
8128
8129 Scope$$1.prototype.deshadow.call( this, names );
8130 };
8131
8132 ModuleScope.prototype.findDeclaration = function findDeclaration ( name ) {
8133 if ( this.declarations[ name ] ) {
8134 return this.declarations[ name ];
8135 }
8136
8137 return this.module.trace( name ) || this.parent.findDeclaration( name );
8138 };
8139
8140 ModuleScope.prototype.findLexicalBoundary = function findLexicalBoundary () {
8141 return this;
8142 };
8143
8144 return ModuleScope;
8145}(Scope));
8146
8147function tryParse ( module, acornOptions ) {
8148 try {
8149 return parse( module.code, assign( {
8150 ecmaVersion: 8,
8151 sourceType: 'module',
8152 onComment: function ( block, text, start, end ) { return module.comments.push( { block: block, text: text, start: start, end: end } ); },
8153 preserveParens: false
8154 }, acornOptions ) );
8155 } catch ( err ) {
8156 module.error( {
8157 code: 'PARSE_ERROR',
8158 message: err.message.replace( / \(\d+:\d+\)$/, '' )
8159 }, err.pos );
8160 }
8161}
8162
8163var Module = function Module ( ref ) {
8164 var this$1 = this;
8165 var id = ref.id;
8166 var code = ref.code;
8167 var originalCode = ref.originalCode;
8168 var originalSourceMap = ref.originalSourceMap;
8169 var ast = ref.ast;
8170 var sourceMapChain = ref.sourceMapChain;
8171 var resolvedIds = ref.resolvedIds;
8172 var resolvedExternalIds = ref.resolvedExternalIds;
8173 var bundle = ref.bundle;
8174
8175 this.code = code;
8176 this.id = id;
8177 this.bundle = bundle;
8178 this.originalCode = originalCode;
8179 this.originalSourceMap = originalSourceMap;
8180 this.sourceMapChain = sourceMapChain;
8181
8182 this.comments = [];
8183
8184 timeStart( 'ast' );
8185
8186 if ( ast ) {
8187 // prevent mutating the provided AST, as it may be reused on
8188 // subsequent incremental rebuilds
8189 this.ast = clone( ast );
8190 this.astClone = ast;
8191 } else {
8192 this.ast = tryParse( this, bundle.acornOptions ); // TODO what happens to comments if AST is provided?
8193 this.astClone = clone( this.ast );
8194 }
8195
8196 timeEnd( 'ast' );
8197
8198 this.excludeFromSourcemap = /\0/.test( id );
8199 this.context = bundle.getModuleContext( id );
8200
8201 // all dependencies
8202 this.sources = [];
8203 this.dependencies = [];
8204 this.resolvedIds = resolvedIds || blank();
8205 this.resolvedExternalIds = resolvedExternalIds || blank();
8206
8207 // imports and exports, indexed by local name
8208 this.imports = blank();
8209 this.exports = blank();
8210 this.exportsAll = blank();
8211 this.reexports = blank();
8212
8213 this.exportAllSources = [];
8214 this.exportAllModules = null;
8215
8216 // By default, `id` is the filename. Custom resolvers and loaders
8217 // can change that, but it makes sense to use it for the source filename
8218 this.magicString = new MagicString$1( code, {
8219 filename: this.excludeFromSourcemap ? null : id, // don't include plugin helpers in sourcemap
8220 indentExclusionRanges: []
8221 } );
8222
8223 // remove existing sourceMappingURL comments
8224 this.comments = this.comments.filter( function (comment) {
8225 //only one line comment can contain source maps
8226 var isSourceMapComment = !comment.block && SOURCEMAPPING_URL_RE.test( comment.text );
8227 if ( isSourceMapComment ) {
8228 this$1.magicString.remove( comment.start, comment.end );
8229 }
8230 return !isSourceMapComment;
8231 } );
8232
8233 this.declarations = blank();
8234 this.type = 'Module'; // TODO only necessary so that Scope knows this should be treated as a function scope... messy
8235 this.scope = new ModuleScope( this );
8236
8237 timeStart( 'analyse' );
8238
8239 this.analyse();
8240
8241 timeEnd( 'analyse' );
8242
8243 this.strongDependencies = [];
8244};
8245
8246Module.prototype.addExport = function addExport ( node ) {
8247 var this$1 = this;
8248
8249 var source = node.source && node.source.value;
8250
8251 // export { name } from './other.js'
8252 if ( source ) {
8253 if ( !~this.sources.indexOf( source ) ) { this.sources.push( source ); }
8254
8255 if ( node.type === 'ExportAllDeclaration' ) {
8256 // Store `export * from '...'` statements in an array of delegates.
8257 // When an unknown import is encountered, we see if one of them can satisfy it.
8258 this.exportAllSources.push( source );
8259 }
8260
8261 else {
8262 node.specifiers.forEach( function (specifier) {
8263 var name = specifier.exported.name;
8264
8265 if ( this$1.exports[ name ] || this$1.reexports[ name ] ) {
8266 this$1.error( {
8267 code: 'DUPLICATE_EXPORT',
8268 message: ("A module cannot have multiple exports with the same name ('" + name + "')")
8269 }, specifier.start );
8270 }
8271
8272 this$1.reexports[ name ] = {
8273 start: specifier.start,
8274 source: source,
8275 localName: specifier.local.name,
8276 module: null // filled in later
8277 };
8278 } );
8279 }
8280 }
8281
8282 // export default function foo () {}
8283 // export default foo;
8284 // export default 42;
8285 else if ( node.type === 'ExportDefaultDeclaration' ) {
8286 var identifier = ( node.declaration.id && node.declaration.id.name ) || node.declaration.name;
8287
8288 if ( this.exports.default ) {
8289 this.error( {
8290 code: 'DUPLICATE_EXPORT',
8291 message: "A module can only have one default export"
8292 }, node.start );
8293 }
8294
8295 this.exports.default = {
8296 localName: 'default',
8297 identifier: identifier
8298 };
8299
8300 // create a synthetic declaration
8301 //this.declarations.default = new SyntheticDefaultDeclaration( node, identifier || this.basename() );
8302 }
8303
8304 // export var { foo, bar } = ...
8305 // export var foo = 42;
8306 // export var a = 1, b = 2, c = 3;
8307 // export function foo () {}
8308 else if ( node.declaration ) {
8309 var declaration = node.declaration;
8310
8311 if ( declaration.type === 'VariableDeclaration' ) {
8312 declaration.declarations.forEach( function (decl) {
8313 extractNames( decl.id ).forEach( function (localName) {
8314 this$1.exports[ localName ] = { localName: localName };
8315 } );
8316 } );
8317 } else {
8318 // export function foo () {}
8319 var localName = declaration.id.name;
8320 this.exports[ localName ] = { localName: localName };
8321 }
8322 }
8323
8324 // export { foo, bar, baz }
8325 else {
8326 node.specifiers.forEach( function (specifier) {
8327 var localName = specifier.local.name;
8328 var exportedName = specifier.exported.name;
8329
8330 if ( this$1.exports[ exportedName ] || this$1.reexports[ exportedName ] ) {
8331 this$1.error({
8332 code: 'DUPLICATE_EXPORT',
8333 message: ("A module cannot have multiple exports with the same name ('" + exportedName + "')")
8334 }, specifier.start );
8335 }
8336
8337 this$1.exports[ exportedName ] = { localName: localName };
8338 });
8339 }
8340};
8341
8342Module.prototype.addImport = function addImport ( node ) {
8343 var this$1 = this;
8344
8345 var source = node.source.value;
8346
8347 if ( !~this.sources.indexOf( source ) ) { this.sources.push( source ); }
8348
8349 node.specifiers.forEach( function (specifier) {
8350 var localName = specifier.local.name;
8351
8352 if ( this$1.imports[ localName ] ) {
8353 this$1.error( {
8354 code: 'DUPLICATE_IMPORT',
8355 message: ("Duplicated import '" + localName + "'")
8356 }, specifier.start );
8357 }
8358
8359 var isDefault = specifier.type === 'ImportDefaultSpecifier';
8360 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
8361
8362 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
8363 this$1.imports[ localName ] = { source: source, specifier: specifier, name: name, module: null };
8364 } );
8365};
8366
8367Module.prototype.analyse = function analyse () {
8368 var this$1 = this;
8369
8370 enhance( this.ast, this, this.comments );
8371
8372 // discover this module's imports and exports
8373 var lastNode;
8374
8375 for ( var node of this$1.ast.body ) {
8376 if ( node.isImportDeclaration ) {
8377 this$1.addImport( node );
8378 } else if ( node.isExportDeclaration ) {
8379 this$1.addExport( node );
8380 }
8381
8382 if ( lastNode ) { lastNode.next = node.leadingCommentStart || node.start; }
8383 lastNode = node;
8384 }
8385};
8386
8387Module.prototype.basename = function basename$1 () {
8388 var base = path.basename( this.id );
8389 var ext = path.extname( this.id );
8390
8391 return makeLegal( ext ? base.slice( 0, -ext.length ) : base );
8392};
8393
8394Module.prototype.bindImportSpecifiers = function bindImportSpecifiers () {
8395 var this$1 = this;
8396
8397 [ this.imports, this.reexports ].forEach( function (specifiers) {
8398 keys( specifiers ).forEach( function (name) {
8399 var specifier = specifiers[ name ];
8400
8401 var id = this$1.resolvedIds[ specifier.source ] || this$1.resolvedExternalIds[ specifier.source ];
8402 specifier.module = this$1.bundle.moduleById.get( id );
8403 } );
8404 } );
8405
8406 this.exportAllModules = this.exportAllSources.map( function (source) {
8407 var id = this$1.resolvedIds[ source ] || this$1.resolvedExternalIds[ source ];
8408 return this$1.bundle.moduleById.get( id );
8409 } );
8410
8411 this.sources.forEach( function (source) {
8412 var id = this$1.resolvedIds[ source ];
8413
8414 if ( id ) {
8415 var module = this$1.bundle.moduleById.get( id );
8416 this$1.dependencies.push( module );
8417 }
8418 } );
8419};
8420
8421Module.prototype.bindReferences = function bindReferences () {
8422 var this$1 = this;
8423
8424 for ( var node of this$1.ast.body ) {
8425 node.bind();
8426 }
8427
8428 // if ( this.declarations.default ) {
8429 // if ( this.exports.default.identifier ) {
8430 // const declaration = this.trace( this.exports.default.identifier );
8431 // if ( declaration ) this.declarations.default.bind( declaration );
8432 // }
8433 // }
8434};
8435
8436Module.prototype.error = function error$1 ( props, pos ) {
8437 if ( pos !== undefined ) {
8438 props.pos = pos;
8439
8440 var ref = locate( this.code, pos, { offsetLine: 1 } );
8441 var line = ref.line;
8442 var column = ref.column; // TODO trace sourcemaps
8443
8444 props.loc = { file: this.id, line: line, column: column };
8445 props.frame = getCodeFrame( this.code, line, column );
8446 }
8447
8448 error( props );
8449};
8450
8451Module.prototype.findParent = function findParent () {
8452 // TODO what does it mean if we're here?
8453 return null;
8454};
8455
8456Module.prototype.getExports = function getExports () {
8457 return keys( this.exports );
8458};
8459
8460Module.prototype.getReexports = function getReexports () {
8461 var reexports = blank();
8462
8463 keys( this.reexports ).forEach( function (name) {
8464 reexports[ name ] = true;
8465 } );
8466
8467 this.exportAllModules.forEach( function (module) {
8468 if ( module.isExternal ) {
8469 reexports[ ("*" + (module.id)) ] = true;
8470 return;
8471 }
8472
8473 module.getExports().concat( module.getReexports() ).forEach( function (name) {
8474 if ( name !== 'default' ) { reexports[ name ] = true; }
8475 } );
8476 } );
8477
8478 return keys( reexports );
8479};
8480
8481Module.prototype.namespace = function namespace () {
8482 if ( !this.declarations[ '*' ] ) {
8483 this.declarations[ '*' ] = new SyntheticNamespaceDeclaration( this );
8484 }
8485
8486 return this.declarations[ '*' ];
8487};
8488
8489Module.prototype.render = function render ( es, legacy ) {
8490 var this$1 = this;
8491
8492 var magicString = this.magicString.clone();
8493
8494 for ( var node of this$1.ast.body ) {
8495 node.render( magicString, es );
8496 }
8497
8498 if ( this.namespace().needsNamespaceBlock ) {
8499 magicString.append( '\n\n' + this.namespace().renderBlock( es, legacy, '\t' ) ); // TODO use correct indentation
8500 }
8501
8502 return magicString.trim();
8503};
8504
8505Module.prototype.run = function run () {
8506 var this$1 = this;
8507
8508 for ( var node of this$1.ast.body ) {
8509 if ( node.hasEffects() ) {
8510 node.run();
8511 }
8512 }
8513};
8514
8515Module.prototype.toJSON = function toJSON () {
8516 return {
8517 id: this.id,
8518 dependencies: this.dependencies.map( function (module) { return module.id; } ),
8519 code: this.code,
8520 originalCode: this.originalCode,
8521 originalSourceMap: this.originalSourceMap,
8522 ast: this.astClone,
8523 sourceMapChain: this.sourceMapChain,
8524 resolvedIds: this.resolvedIds,
8525 resolvedExternalIds: this.resolvedExternalIds
8526 };
8527};
8528
8529Module.prototype.trace = function trace ( name ) {
8530 // TODO this is slightly circular
8531 if ( name in this.scope.declarations ) {
8532 return this.scope.declarations[ name ];
8533 }
8534
8535 if ( name in this.imports ) {
8536 var importDeclaration = this.imports[ name ];
8537 var otherModule = importDeclaration.module;
8538
8539 if ( importDeclaration.name === '*' && !otherModule.isExternal ) {
8540 return otherModule.namespace();
8541 }
8542
8543 var declaration = otherModule.traceExport( importDeclaration.name );
8544
8545 if ( !declaration ) {
8546 this.error( {
8547 code: 'MISSING_EXPORT',
8548 message: ("'" + (importDeclaration.name) + "' is not exported by " + (relativeId( otherModule.id ))),
8549 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
8550 }, importDeclaration.specifier.start );
8551 }
8552
8553 return declaration;
8554 }
8555
8556 return null;
8557};
8558
8559Module.prototype.traceExport = function traceExport ( name ) {
8560 var this$1 = this;
8561
8562 // export * from 'external'
8563 if ( name[ 0 ] === '*' ) {
8564 var module = this.bundle.moduleById.get( name.slice( 1 ) );
8565 return module.traceExport( '*' );
8566 }
8567
8568 // export { foo } from './other.js'
8569 var reexportDeclaration = this.reexports[ name ];
8570 if ( reexportDeclaration ) {
8571 var declaration = reexportDeclaration.module.traceExport( reexportDeclaration.localName );
8572
8573 if ( !declaration ) {
8574 this.error( {
8575 code: 'MISSING_EXPORT',
8576 message: ("'" + (reexportDeclaration.localName) + "' is not exported by " + (relativeId( reexportDeclaration.module.id ))),
8577 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
8578 }, reexportDeclaration.start );
8579 }
8580
8581 return declaration;
8582 }
8583
8584 var exportDeclaration = this.exports[ name ];
8585 if ( exportDeclaration ) {
8586 var name$1 = exportDeclaration.localName;
8587 var declaration$1 = this.trace( name$1 );
8588
8589 return declaration$1 || this.bundle.scope.findDeclaration( name$1 );
8590 }
8591
8592 if ( name === 'default' ) { return; }
8593
8594 for ( var i = 0; i < this.exportAllModules.length; i += 1 ) {
8595 var module$1$$1 = this$1.exportAllModules[ i ];
8596 var declaration$2 = module$1$$1.traceExport( name );
8597
8598 if ( declaration$2 ) { return declaration$2; }
8599 }
8600};
8601
8602Module.prototype.warn = function warn ( warning, pos ) {
8603 if ( pos !== undefined ) {
8604 warning.pos = pos;
8605
8606 var ref = locate( this.code, pos, { offsetLine: 1 } );
8607 var line = ref.line;
8608 var column = ref.column; // TODO trace sourcemaps
8609
8610 warning.loc = { file: this.id, line: line, column: column };
8611 warning.frame = getCodeFrame( this.code, line, column );
8612 }
8613
8614 warning.id = this.id;
8615 this.bundle.warn( warning );
8616};
8617
8618var ExternalModule = function ExternalModule ( id, relativePath ) {
8619 this.id = id;
8620 this.path = relativePath;
8621
8622 this.name = makeLegal( relativePath );
8623
8624 this.nameSuggestions = blank();
8625 this.mostCommonSuggestion = 0;
8626
8627 this.isExternal = true;
8628 this.used = false;
8629 this.declarations = blank();
8630
8631 this.exportsNames = false;
8632};
8633
8634ExternalModule.prototype.suggestName = function suggestName ( name ) {
8635 if ( !this.nameSuggestions[ name ] ) { this.nameSuggestions[ name ] = 0; }
8636 this.nameSuggestions[ name ] += 1;
8637
8638 if ( this.nameSuggestions[ name ] > this.mostCommonSuggestion ) {
8639 this.mostCommonSuggestion = this.nameSuggestions[ name ];
8640 this.name = name;
8641 }
8642};
8643
8644ExternalModule.prototype.traceExport = function traceExport ( name ) {
8645 if ( name !== 'default' && name !== '*' ) { this.exportsNames = true; }
8646 if ( name === '*' ) { this.exportsNamespace = true; }
8647
8648 return this.declarations[ name ] || (
8649 this.declarations[ name ] = new ExternalDeclaration( this, name )
8650 );
8651};
8652
8653function getName ( x ) {
8654 return x.name;
8655}
8656
8657function quotePath ( x ) {
8658 return ("'" + (x.path) + "'");
8659}
8660
8661function req ( x ) {
8662 return ("require('" + (x.path) + "')");
8663}
8664
8665function getInteropBlock ( bundle, options ) {
8666 return bundle.externalModules
8667 .map( function (module) {
8668 if ( !module.declarations.default || options.interop === false ) { return null; }
8669
8670 if ( module.exportsNamespace ) {
8671 return ((bundle.varOrConst) + " " + (module.name) + "__default = " + (module.name) + "['default'];");
8672 }
8673
8674 if ( module.exportsNames ) {
8675 return ((bundle.varOrConst) + " " + (module.name) + "__default = 'default' in " + (module.name) + " ? " + (module.name) + "['default'] : " + (module.name) + ";");
8676 }
8677
8678 return ((module.name) + " = " + (module.name) + " && " + (module.name) + ".hasOwnProperty('default') ? " + (module.name) + "['default'] : " + (module.name) + ";");
8679 })
8680 .filter( Boolean )
8681 .join( '\n' );
8682}
8683
8684function getExportBlock ( bundle, exportMode, mechanism ) {
8685 if ( mechanism === void 0 ) mechanism = 'return';
8686
8687 var entryModule = bundle.entryModule;
8688
8689 if ( exportMode === 'default' ) {
8690 return (mechanism + " " + (entryModule.traceExport( 'default' ).getName( false )) + ";");
8691 }
8692
8693 var exports = entryModule.getExports().concat( entryModule.getReexports() )
8694 .map( function (name) {
8695 if ( name[0] === '*' ) {
8696 // export all from external
8697 var id = name.slice( 1 );
8698 var module = bundle.moduleById.get( id );
8699
8700 return ("Object.keys(" + (module.name) + ").forEach(function (key) { exports[key] = " + (module.name) + "[key]; });");
8701 }
8702
8703 var prop = name === 'default' ? "['default']" : ("." + name);
8704 var declaration = entryModule.traceExport( name );
8705
8706 var lhs = "exports" + prop;
8707 var rhs = declaration ?
8708 declaration.getName( false ) :
8709 name; // exporting a global
8710
8711 // prevent `exports.count = exports.count`
8712 if ( lhs === rhs ) { return null; }
8713
8714 return (lhs + " = " + rhs + ";");
8715 });
8716
8717 return exports
8718 .filter( Boolean )
8719 .join( '\n' );
8720}
8721
8722var esModuleExport = "Object.defineProperty(exports, '__esModule', { value: true });";
8723
8724var builtins$1 = {
8725 process: true,
8726 events: true,
8727 stream: true,
8728 util: true,
8729 path: true,
8730 buffer: true,
8731 querystring: true,
8732 url: true,
8733 string_decoder: true,
8734 punycode: true,
8735 http: true,
8736 https: true,
8737 os: true,
8738 assert: true,
8739 constants: true,
8740 timers: true,
8741 console: true,
8742 vm: true,
8743 zlib: true,
8744 tty: true,
8745 domain: true
8746};
8747
8748// Creating a browser bundle that depends on Node.js built-in modules ('util'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins
8749
8750function warnOnBuiltins ( bundle ) {
8751 var externalBuiltins = bundle.externalModules
8752 .filter( function (mod) { return mod.id in builtins$1; } )
8753 .map( function (mod) { return mod.id; } );
8754
8755 if ( !externalBuiltins.length ) { return; }
8756
8757 var detail = externalBuiltins.length === 1 ?
8758 ("module ('" + (externalBuiltins[0]) + "')") :
8759 ("modules (" + (externalBuiltins.slice( 0, -1 ).map( function (name) { return ("'" + name + "'"); } ).join( ', ' )) + " and '" + (externalBuiltins.slice( -1 )) + "')");
8760
8761 bundle.warn({
8762 code: 'MISSING_NODE_BUILTINS',
8763 modules: externalBuiltins,
8764 message: ("Creating a browser bundle that depends on Node.js built-in " + detail + ". You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins")
8765 });
8766}
8767
8768function amd ( bundle, magicString, ref, options ) {
8769 var exportMode = ref.exportMode;
8770 var indentString = ref.indentString;
8771 var intro = ref.intro;
8772 var outro = ref.outro;
8773
8774 warnOnBuiltins( bundle );
8775 var deps = bundle.externalModules.map( quotePath );
8776 var args = bundle.externalModules.map( getName );
8777
8778 if ( exportMode === 'named' ) {
8779 args.unshift( "exports" );
8780 deps.unshift( "'exports'" );
8781 }
8782
8783 var amdOptions = options.amd || {};
8784
8785 var params =
8786 ( amdOptions.id ? ("'" + (amdOptions.id) + "', ") : "" ) +
8787 ( deps.length ? ("[" + (deps.join( ', ' )) + "], ") : "" );
8788
8789 var useStrict = options.useStrict !== false ? " 'use strict';" : "";
8790 var define = amdOptions.define || 'define';
8791 var wrapperStart = define + "(" + params + "function (" + (args.join( ', ' )) + ") {" + useStrict + "\n\n";
8792
8793 // var foo__default = 'default' in foo ? foo['default'] : foo;
8794 var interopBlock = getInteropBlock( bundle, options );
8795 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
8796
8797 if ( intro ) { magicString.prepend( intro ); }
8798
8799 var exportBlock = getExportBlock( bundle, exportMode );
8800 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
8801 if ( exportMode === 'named' && options.legacy !== true ) { magicString.append( ("\n\n" + esModuleExport) ); }
8802 if ( outro ) { magicString.append( outro ); }
8803
8804 return magicString
8805 .indent( indentString )
8806 .append( '\n\n});' )
8807 .prepend( wrapperStart );
8808}
8809
8810function cjs ( bundle, magicString, ref, options ) {
8811 var exportMode = ref.exportMode;
8812 var intro = ref.intro;
8813 var outro = ref.outro;
8814
8815 intro = ( options.useStrict === false ? intro : ("'use strict';\n\n" + intro) ) +
8816 ( exportMode === 'named' && options.legacy !== true ? (esModuleExport + "\n\n") : '' );
8817
8818 var needsInterop = false;
8819
8820 var varOrConst = bundle.varOrConst;
8821 var interop = options.interop !== false;
8822
8823 // TODO handle empty imports, once they're supported
8824 var importBlock = bundle.externalModules
8825 .map( function (module) {
8826 if ( interop && module.declarations.default ) {
8827 if ( module.exportsNamespace ) {
8828 return varOrConst + " " + (module.name) + " = require('" + (module.path) + "');" +
8829 "\n" + varOrConst + " " + (module.name) + "__default = " + (module.name) + "['default'];";
8830 }
8831
8832 needsInterop = true;
8833
8834 if ( module.exportsNames ) {
8835 return varOrConst + " " + (module.name) + " = require('" + (module.path) + "');" +
8836 "\n" + varOrConst + " " + (module.name) + "__default = _interopDefault(" + (module.name) + ");";
8837 }
8838
8839 return (varOrConst + " " + (module.name) + " = _interopDefault(require('" + (module.path) + "'));");
8840 } else {
8841 var activated = Object.keys( module.declarations )
8842 .filter( function (name) { return module.declarations[ name ].activated; } );
8843
8844 var needsVar = activated.length || module.reexported;
8845
8846 return needsVar ?
8847 (varOrConst + " " + (module.name) + " = require('" + (module.path) + "');") :
8848 ("require('" + (module.path) + "');");
8849 }
8850 })
8851 .join( '\n' );
8852
8853 if ( needsInterop ) {
8854 intro += "function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n";
8855 }
8856
8857 if ( importBlock ) {
8858 intro += importBlock + '\n\n';
8859 }
8860
8861 magicString.prepend( intro );
8862
8863 var exportBlock = getExportBlock( bundle, exportMode, 'module.exports =' );
8864 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
8865 if ( outro ) { magicString.append( outro ); }
8866
8867 return magicString;
8868}
8869
8870function notDefault ( name ) {
8871 return name !== 'default';
8872}
8873
8874function es ( bundle, magicString, ref ) {
8875 var intro = ref.intro;
8876 var outro = ref.outro;
8877
8878 var importBlock = bundle.externalModules
8879 .map( function (module) {
8880 var specifiers = [];
8881 var specifiersList = [specifiers];
8882 var importedNames = keys( module.declarations )
8883 .filter( function (name) { return name !== '*' && name !== 'default'; } )
8884 .filter( function (name) { return module.declarations[ name ].activated; } )
8885 .map( function (name) {
8886 if ( name[0] === '*' ) {
8887 return ("* as " + (module.name));
8888 }
8889
8890 var declaration = module.declarations[ name ];
8891
8892 if ( declaration.name === declaration.safeName ) { return declaration.name; }
8893 return ((declaration.name) + " as " + (declaration.safeName));
8894 })
8895 .filter( Boolean );
8896
8897 if ( module.declarations.default ) {
8898 if ( module.exportsNamespace ) {
8899 specifiersList.push([ ((module.name) + "__default") ]);
8900 } else {
8901 specifiers.push( module.name );
8902 }
8903 }
8904
8905 var namespaceSpecifier = module.declarations['*'] && module.declarations['*'].activated ? ("* as " + (module.name)) : null; // TODO prevent unnecessary namespace import, e.g form/external-imports
8906 var namedSpecifier = importedNames.length ? ("{ " + (importedNames.sort().join( ', ' )) + " }") : null;
8907
8908 if ( namespaceSpecifier && namedSpecifier ) {
8909 // Namespace and named specifiers cannot be combined.
8910 specifiersList.push( [namespaceSpecifier] );
8911 specifiers.push( namedSpecifier );
8912 } else if ( namedSpecifier ) {
8913 specifiers.push( namedSpecifier );
8914 } else if ( namespaceSpecifier ) {
8915 specifiers.push( namespaceSpecifier );
8916 }
8917
8918 return specifiersList
8919 .map( function (specifiers) {
8920 if ( specifiers.length ) {
8921 return ("import " + (specifiers.join( ', ' )) + " from '" + (module.path) + "';");
8922 }
8923
8924 return module.reexported ?
8925 null :
8926 ("import '" + (module.path) + "';");
8927 })
8928 .filter( Boolean )
8929 .join( '\n' );
8930 })
8931 .join( '\n' );
8932
8933 if ( importBlock ) { intro += importBlock + '\n\n'; }
8934 if ( intro ) { magicString.prepend( intro ); }
8935
8936 var module = bundle.entryModule;
8937
8938 var exportInternalSpecifiers = [];
8939 var exportExternalSpecifiers = new Map();
8940 var exportAllDeclarations = [];
8941
8942 module.getExports()
8943 .filter( notDefault )
8944 .forEach( function (name) {
8945 var declaration = module.traceExport( name );
8946 var rendered = declaration.getName( true );
8947 exportInternalSpecifiers.push( rendered === name ? name : (rendered + " as " + name) );
8948 });
8949
8950 module.getReexports()
8951 .filter( notDefault )
8952 .forEach( function (name) {
8953 var declaration = module.traceExport( name );
8954
8955 if ( declaration.isExternal ) {
8956 if ( name[0] === '*' ) {
8957 // export * from 'external'
8958 exportAllDeclarations.push( ("export * from '" + (name.slice( 1 )) + "';") );
8959 } else {
8960 if ( !exportExternalSpecifiers.has( declaration.module.id ) ) { exportExternalSpecifiers.set( declaration.module.id, [] ); }
8961 exportExternalSpecifiers.get( declaration.module.id ).push( name );
8962 }
8963
8964 return;
8965 }
8966
8967 var rendered = declaration.getName( true );
8968 exportInternalSpecifiers.push( rendered === name ? name : (rendered + " as " + name) );
8969 });
8970
8971 var exportBlock = [];
8972 if ( exportInternalSpecifiers.length ) { exportBlock.push( ("export { " + (exportInternalSpecifiers.join(', ')) + " };") ); }
8973 if ( module.exports.default || module.reexports.default ) { exportBlock.push( ("export default " + (module.traceExport( 'default' ).getName( true )) + ";") ); }
8974 if ( exportAllDeclarations.length ) { exportBlock.push( exportAllDeclarations.join( '\n' ) ); }
8975 if ( exportExternalSpecifiers.size ) {
8976 exportExternalSpecifiers.forEach( function ( specifiers, id ) {
8977 exportBlock.push( ("export { " + (specifiers.join( ', ' )) + " } from '" + id + "';") );
8978 });
8979 }
8980
8981 if ( exportBlock.length ) { magicString.append( '\n\n' + exportBlock.join( '\n' ).trim() ); }
8982
8983 if ( outro ) { magicString.append( outro ); }
8984
8985 return magicString.trim();
8986}
8987
8988function getGlobalNameMaker ( globals, bundle, fallback ) {
8989 if ( fallback === void 0 ) fallback = null;
8990
8991 var fn = typeof globals === 'function' ? globals : function (id) { return globals[ id ]; };
8992
8993 return function ( module ) {
8994 var name = fn( module.id );
8995 if ( name ) { return name; }
8996
8997 if ( Object.keys( module.declarations ).length > 0 ) {
8998 bundle.warn({
8999 code: 'MISSING_GLOBAL_NAME',
9000 source: module.id,
9001 guess: module.name,
9002 message: ("No name was provided for external module '" + (module.id) + "' in options.globals – guessing '" + (module.name) + "'")
9003 });
9004
9005 return module.name;
9006 }
9007
9008 return fallback;
9009 };
9010}
9011
9012// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
9013// if the property name isn't trivial
9014var shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
9015
9016function property ( prop ) {
9017 return shouldUseDot.test( prop ) ? ("." + prop) : ("['" + prop + "']");
9018}
9019
9020function keypath ( keypath ) {
9021 return keypath.split( '.' ).map( property ).join( '' );
9022}
9023
9024function trimEmptyImports ( modules ) {
9025 var i = modules.length;
9026
9027 while ( i-- ) {
9028 var module = modules[i];
9029 if ( Object.keys( module.declarations ).length > 0 ) {
9030 return modules.slice( 0, i + 1 );
9031 }
9032 }
9033
9034 return [];
9035}
9036
9037function setupNamespace ( keypath$$1 ) {
9038 var parts = keypath$$1.split( '.' );
9039
9040 parts.pop();
9041
9042 var acc = 'this';
9043
9044 return parts
9045 .map( function (part) { return ( acc += property( part ), (acc + " = " + acc + " || {};") ); } )
9046 .join( '\n' ) + '\n';
9047}
9048
9049var thisProp = function (name) { return ("this" + (keypath( name ))); };
9050
9051function iife ( bundle, magicString, ref, options ) {
9052 var exportMode = ref.exportMode;
9053 var indentString = ref.indentString;
9054 var intro = ref.intro;
9055 var outro = ref.outro;
9056
9057 var globalNameMaker = getGlobalNameMaker( options.globals || blank(), bundle, 'null' );
9058
9059 var extend = options.extend;
9060 var name = options.moduleName;
9061 var isNamespaced = name && name.indexOf( '.' ) !== -1;
9062 var possibleVariableAssignment = !extend && !isNamespaced;
9063
9064 if ( name && possibleVariableAssignment && !isLegal(name) ) {
9065 error({
9066 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
9067 message: ("Given moduleName (" + name + ") is not legal JS identifier. If you need this you can try --extend option")
9068 });
9069 }
9070
9071 warnOnBuiltins( bundle );
9072
9073 var external = trimEmptyImports( bundle.externalModules );
9074 var dependencies = external.map( globalNameMaker );
9075 var args = external.map( getName );
9076
9077 if ( exportMode !== 'none' && !name ) {
9078 error({
9079 code: 'INVALID_OPTION',
9080 message: "You must supply options.moduleName for IIFE bundles"
9081 });
9082 }
9083
9084 if ( extend ) {
9085 dependencies.unshift( ("(" + (thisProp(name)) + " = " + (thisProp(name)) + " || {})") );
9086 args.unshift( 'exports' );
9087 } else if ( exportMode === 'named' ) {
9088 dependencies.unshift( '{}' );
9089 args.unshift( 'exports' );
9090 }
9091
9092 var useStrict = options.useStrict !== false ? (indentString + "'use strict';\n\n") : "";
9093
9094 var wrapperIntro = "(function (" + args + ") {\n" + useStrict;
9095
9096 if ( exportMode !== 'none' && !extend) {
9097 wrapperIntro = ( isNamespaced ? thisProp(name) : ((bundle.varOrConst) + " " + name) ) + " = " + wrapperIntro;
9098 }
9099
9100 if ( isNamespaced ) {
9101 wrapperIntro = setupNamespace( name ) + wrapperIntro;
9102 }
9103
9104 var wrapperOutro = "\n\n}(" + dependencies + "));";
9105
9106 if (!extend && exportMode === 'named') {
9107 wrapperOutro = "\n\n" + indentString + "return exports;" + wrapperOutro;
9108 }
9109
9110 // var foo__default = 'default' in foo ? foo['default'] : foo;
9111 var interopBlock = getInteropBlock( bundle, options );
9112 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
9113
9114 if ( intro ) { magicString.prepend( intro ); }
9115
9116 var exportBlock = getExportBlock( bundle, exportMode );
9117 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
9118 if ( outro ) { magicString.append( outro ); }
9119
9120 return magicString
9121 .indent( indentString )
9122 .prepend( wrapperIntro )
9123 .append( wrapperOutro );
9124}
9125
9126function globalProp ( name ) {
9127 if ( !name ) { return 'null'; }
9128 return ("global" + (keypath( name )));
9129}
9130
9131function setupNamespace$1 ( name ) {
9132 var parts = name.split( '.' );
9133 var last = property( parts.pop() );
9134
9135 var acc = 'global';
9136 return parts
9137 .map( function (part) { return ( acc += property( part ), (acc + " = " + acc + " || {}") ); } )
9138 .concat( ("" + acc + last) )
9139 .join( ', ' );
9140}
9141
9142function safeAccess ( name ) {
9143 var parts = name.split( '.' );
9144
9145 var acc = 'global';
9146 return parts
9147 .map( function (part) { return ( acc += property( part ), acc ); } )
9148 .join( " && " );
9149}
9150
9151var wrapperOutro = '\n\n})));';
9152
9153function umd ( bundle, magicString, ref, options ) {
9154 var exportMode = ref.exportMode;
9155 var indentString = ref.indentString;
9156 var intro = ref.intro;
9157 var outro = ref.outro;
9158
9159 if ( exportMode !== 'none' && !options.moduleName ) {
9160 error({
9161 code: 'INVALID_OPTION',
9162 message: 'You must supply options.moduleName for UMD bundles'
9163 });
9164 }
9165
9166 warnOnBuiltins( bundle );
9167
9168 var globalNameMaker = getGlobalNameMaker( options.globals || blank(), bundle );
9169
9170 var amdDeps = bundle.externalModules.map( quotePath );
9171 var cjsDeps = bundle.externalModules.map( req );
9172
9173 var trimmed = trimEmptyImports( bundle.externalModules );
9174 var globalDeps = trimmed.map( function (module) { return globalProp( globalNameMaker( module ) ); } );
9175 var args = trimmed.map( getName );
9176
9177 if ( exportMode === 'named' ) {
9178 amdDeps.unshift( "'exports'" );
9179 cjsDeps.unshift( "exports" );
9180 globalDeps.unshift( ("(" + (setupNamespace$1(options.moduleName)) + " = " + (options.extend ? ((globalProp(options.moduleName)) + " || ") : '') + "{})") );
9181
9182 args.unshift( 'exports' );
9183 }
9184
9185 var amdOptions = options.amd || {};
9186
9187 var amdParams =
9188 ( amdOptions.id ? ("'" + (amdOptions.id) + "', ") : "" ) +
9189 ( amdDeps.length ? ("[" + (amdDeps.join( ', ' )) + "], ") : "" );
9190
9191 var define = amdOptions.define || 'define';
9192
9193 var cjsExport = exportMode === 'default' ? "module.exports = " : "";
9194 var defaultExport = exportMode === 'default' ? ((setupNamespace$1(options.moduleName)) + " = ") : '';
9195
9196 var useStrict = options.useStrict !== false ? " 'use strict';" : "";
9197
9198 var globalExport;
9199
9200 if (options.noConflict === true) {
9201 var factory;
9202
9203 if ( exportMode === 'default' ) {
9204 factory = "var exports = factory(" + globalDeps + ");";
9205 } else if ( exportMode === 'named' ) {
9206 var module = globalDeps.shift();
9207 factory = "var exports = " + module + ";\n\t\t\t\tfactory(" + (['exports'].concat(globalDeps)) + ");";
9208 }
9209 globalExport = "(function() {\n\t\t\t\tvar current = " + (safeAccess(options.moduleName)) + ";\n\t\t\t\t" + factory + "\n\t\t\t\t" + (globalProp(options.moduleName)) + " = exports;\n\t\t\t\texports.noConflict = function() { " + (globalProp(options.moduleName)) + " = current; return exports; };\n\t\t\t})()";
9210 } else {
9211 globalExport = "(" + defaultExport + "factory(" + globalDeps + "))";
9212 }
9213
9214 var wrapperIntro =
9215 ("(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" + globalExport + ";\n\t\t}(this, (function (" + args + ") {" + useStrict + "\n\n\t\t").replace( /^\t\t/gm, '' ).replace( /^\t/gm, indentString || '\t' );
9216
9217 // var foo__default = 'default' in foo ? foo['default'] : foo;
9218 var interopBlock = getInteropBlock( bundle, options );
9219 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
9220
9221 if ( intro ) { magicString.prepend( intro ); }
9222
9223 var exportBlock = getExportBlock( bundle, exportMode );
9224 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
9225 if ( exportMode === 'named' && options.legacy !== true ) { magicString.append( ("\n\n" + esModuleExport) ); }
9226 if ( outro ) { magicString.append( outro ); }
9227
9228 return magicString
9229 .trim()
9230 .indent( indentString )
9231 .append( wrapperOutro )
9232 .prepend( wrapperIntro );
9233}
9234
9235var finalisers = { amd: amd, cjs: cjs, es: es, iife: iife, umd: umd };
9236
9237function ensureArray ( thing ) {
9238 if ( Array.isArray( thing ) ) { return thing; }
9239 if ( thing == undefined ) { return []; }
9240 return [ thing ];
9241}
9242
9243function load ( id ) {
9244 return fs.readFileSync( id, 'utf-8' );
9245}
9246
9247function findFile ( file ) {
9248 try {
9249 var stats = fs.lstatSync( file );
9250 if ( stats.isSymbolicLink() ) { return findFile( fs.realpathSync( file ) ); }
9251 if ( stats.isFile() ) {
9252 // check case
9253 var name = path.basename( file );
9254 var files = fs.readdirSync( path.dirname( file ) );
9255
9256 if ( ~files.indexOf( name ) ) { return file; }
9257 }
9258 } catch ( err ) {
9259 // suppress
9260 }
9261}
9262
9263function addJsExtensionIfNecessary ( file ) {
9264 return findFile( file ) || findFile( file + '.js' );
9265}
9266
9267function resolveId ( importee, importer ) {
9268 if ( typeof process === 'undefined' ) {
9269 error({
9270 code: 'MISSING_PROCESS',
9271 message: "It looks like you're using Rollup in a non-Node.js environment. This means you must supply a plugin with custom resolveId and load functions",
9272 url: 'https://github.com/rollup/rollup/wiki/Plugins'
9273 });
9274 }
9275
9276 // external modules (non-entry modules that start with neither '.' or '/')
9277 // are skipped at this stage.
9278 if ( importer !== undefined && !isAbsolute( importee ) && importee[0] !== '.' ) { return null; }
9279
9280 // `resolve` processes paths from right to left, prepending them until an
9281 // absolute path is created. Absolute importees therefore shortcircuit the
9282 // resolve call and require no special handing on our part.
9283 // See https://nodejs.org/api/path.html#path_path_resolve_paths
9284 return addJsExtensionIfNecessary(
9285 path.resolve( importer ? path.dirname( importer ) : path.resolve(), importee ) );
9286}
9287
9288
9289function makeOnwarn () {
9290 var warned = blank();
9291
9292 return function (warning) {
9293 var str = warning.toString();
9294 if ( str in warned ) { return; }
9295 console.error( str ); //eslint-disable-line no-console
9296 warned[ str ] = true;
9297 };
9298}
9299
9300function badExports ( option, keys$$1 ) {
9301 error({
9302 code: 'INVALID_EXPORT_OPTION',
9303 message: ("'" + option + "' was specified for options.exports, but entry module has following exports: " + (keys$$1.join(', ')))
9304 });
9305}
9306
9307function getExportMode ( bundle, ref ) {
9308 var exportMode = ref.exports;
9309 var moduleName = ref.moduleName;
9310 var format = ref.format;
9311
9312 var exportKeys = keys( bundle.entryModule.exports )
9313 .concat( keys( bundle.entryModule.reexports ) )
9314 .concat( bundle.entryModule.exportAllSources ); // not keys, but makes our job easier this way
9315
9316 if ( exportMode === 'default' ) {
9317 if ( exportKeys.length !== 1 || exportKeys[0] !== 'default' ) {
9318 badExports( 'default', exportKeys );
9319 }
9320 } else if ( exportMode === 'none' && exportKeys.length ) {
9321 badExports( 'none', exportKeys );
9322 }
9323
9324 if ( !exportMode || exportMode === 'auto' ) {
9325 if ( exportKeys.length === 0 ) {
9326 exportMode = 'none';
9327 } else if ( exportKeys.length === 1 && exportKeys[0] === 'default' ) {
9328 exportMode = 'default';
9329 } else {
9330 if ( bundle.entryModule.exports.default && format !== 'es') {
9331 bundle.warn({
9332 code: 'MIXED_EXPORTS',
9333 message: ("Using named and default exports together. Consumers of your bundle will have to use " + (moduleName || 'bundle') + "['default'] to access the default export, which may not be what you want. Use `exports: 'named'` to disable this warning"),
9334 url: "https://github.com/rollup/rollup/wiki/JavaScript-API#exports"
9335 });
9336 }
9337 exportMode = 'named';
9338 }
9339 }
9340
9341 if ( !/(?:default|named|none)/.test( exportMode ) ) {
9342 error({
9343 code: 'INVALID_EXPORT_OPTION',
9344 message: "options.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')"
9345 });
9346 }
9347
9348 return exportMode;
9349}
9350
9351function getIndentString ( magicString, options ) {
9352 if ( options.indent === true ) {
9353 return magicString.getIndentString();
9354 }
9355
9356 return options.indent || '';
9357}
9358
9359function transform ( bundle, source, id, plugins ) {
9360 var sourceMapChain = [];
9361
9362 var originalSourceMap = typeof source.map === 'string' ? JSON.parse( source.map ) : source.map;
9363
9364 if ( originalSourceMap && typeof originalSourceMap.mappings === 'string' ) {
9365 originalSourceMap.mappings = decode$$1( originalSourceMap.mappings );
9366 }
9367
9368 var originalCode = source.code;
9369 var ast = source.ast;
9370
9371 var promise = Promise.resolve( source.code );
9372
9373 plugins.forEach( function (plugin) {
9374 if ( !plugin.transform ) { return; }
9375
9376 promise = promise.then( function (previous) {
9377 function augment ( object, pos, code ) {
9378 if ( typeof object === 'string' ) {
9379 object = { message: object };
9380 }
9381
9382 if ( object.code ) { object.pluginCode = object.code; }
9383 object.code = code;
9384
9385 if ( pos !== undefined ) {
9386 if ( pos.line !== undefined && pos.column !== undefined ) {
9387 var line = pos.line;
9388 var column = pos.column;
9389 object.loc = { file: id, line: line, column: column };
9390 object.frame = getCodeFrame( previous, line, column );
9391 }
9392 else {
9393 object.pos = pos;
9394 var ref = locate( previous, pos, { offsetLine: 1 });
9395 var line$1 = ref.line;
9396 var column$1 = ref.column;
9397 object.loc = { file: id, line: line$1, column: column$1 };
9398 object.frame = getCodeFrame( previous, line$1, column$1 );
9399 }
9400 }
9401
9402 object.plugin = plugin.name;
9403 object.id = id;
9404
9405 return object;
9406 }
9407
9408 var throwing;
9409
9410 var context = {
9411 warn: function ( warning, pos ) {
9412 warning = augment( warning, pos, 'PLUGIN_WARNING' );
9413 bundle.warn( warning );
9414 },
9415
9416 error: function error$1 ( err, pos ) {
9417 err = augment( err, pos, 'PLUGIN_ERROR' );
9418 throwing = true;
9419 error( err );
9420 }
9421 };
9422
9423 var transformed;
9424
9425 try {
9426 transformed = plugin.transform.call( context, previous, id );
9427 } catch ( err ) {
9428 if ( !throwing ) { context.error( err ); }
9429 error( err );
9430 }
9431
9432 return Promise.resolve( transformed )
9433 .then( function (result) {
9434 if ( result == null ) { return previous; }
9435
9436 if ( typeof result === 'string' ) {
9437 result = {
9438 code: result,
9439 ast: null,
9440 map: null
9441 };
9442 }
9443
9444 // `result.map` can only be a string if `result` isn't
9445 else if ( typeof result.map === 'string' ) {
9446 result.map = JSON.parse( result.map );
9447 }
9448
9449 if ( result.map && typeof result.map.mappings === 'string' ) {
9450 result.map.mappings = decode$$1( result.map.mappings );
9451 }
9452
9453 sourceMapChain.push( result.map || { missing: true, plugin: plugin.name }); // lil' bit hacky but it works
9454 ast = result.ast;
9455
9456 return result.code;
9457 })
9458 .catch( function (err) {
9459 err = augment( err, undefined, 'PLUGIN_ERROR' );
9460 error( err );
9461 });
9462 });
9463 });
9464
9465 return promise.then( function (code) { return ({ code: code, originalCode: originalCode, originalSourceMap: originalSourceMap, ast: ast, sourceMapChain: sourceMapChain }); } );
9466}
9467
9468function transformBundle ( code, plugins, sourceMapChain, options ) {
9469 return plugins.reduce( function ( promise, plugin ) {
9470 if ( !plugin.transformBundle ) { return promise; }
9471
9472 return promise.then( function (code) {
9473 return Promise.resolve().then( function () {
9474 return plugin.transformBundle( code, { format : options.format } );
9475 }).then( function (result) {
9476 if ( result == null ) { return code; }
9477
9478 if ( typeof result === 'string' ) {
9479 result = {
9480 code: result,
9481 map: null
9482 };
9483 }
9484
9485 var map = typeof result.map === 'string' ? JSON.parse( result.map ) : result.map;
9486 if ( map && typeof map.mappings === 'string' ) {
9487 map.mappings = decode$$1( map.mappings );
9488 }
9489
9490 sourceMapChain.push( map );
9491
9492 return result.code;
9493 }).catch( function (err) {
9494 error({
9495 code: 'BAD_BUNDLE_TRANSFORMER',
9496 message: ("Error transforming bundle" + (plugin.name ? (" with '" + (plugin.name) + "' plugin") : '') + ": " + (err.message)),
9497 plugin: plugin.name
9498 });
9499 });
9500 });
9501
9502 }, Promise.resolve( code ) );
9503}
9504
9505var Source = function Source ( filename, content ) {
9506 this.isOriginal = true;
9507 this.filename = filename;
9508 this.content = content;
9509};
9510
9511Source.prototype.traceSegment = function traceSegment ( line, column, name ) {
9512 return { line: line, column: column, name: name, source: this };
9513};
9514
9515var Link = function Link ( map, sources ) {
9516 this.sources = sources;
9517 this.names = map.names;
9518 this.mappings = map.mappings;
9519};
9520
9521Link.prototype.traceMappings = function traceMappings () {
9522 var this$1 = this;
9523
9524 var sources = [];
9525 var sourcesContent = [];
9526 var names = [];
9527
9528 var mappings = this.mappings.map( function (line) {
9529 var tracedLine = [];
9530
9531 line.forEach( function (segment) {
9532 var source = this$1.sources[ segment[1] ];
9533
9534 if ( !source ) { return; }
9535
9536 var traced = source.traceSegment( segment[2], segment[3], this$1.names[ segment[4] ] );
9537
9538 if ( traced ) {
9539 var sourceIndex = null;
9540 var nameIndex = null;
9541 segment = [
9542 segment[0],
9543 null,
9544 traced.line,
9545 traced.column
9546 ];
9547
9548 // newer sources are more likely to be used, so search backwards.
9549 sourceIndex = sources.lastIndexOf( traced.source.filename );
9550 if ( sourceIndex === -1 ) {
9551 sourceIndex = sources.length;
9552 sources.push( traced.source.filename );
9553 sourcesContent[ sourceIndex ] = traced.source.content;
9554 } else if ( sourcesContent[ sourceIndex ] == null ) {
9555 sourcesContent[ sourceIndex ] = traced.source.content;
9556 } else if ( traced.source.content != null && sourcesContent[ sourceIndex ] !== traced.source.content ) {
9557 error({
9558 message: ("Multiple conflicting contents for sourcemap source " + (source.filename))
9559 });
9560 }
9561
9562 segment[1] = sourceIndex;
9563
9564 if ( traced.name ) {
9565 nameIndex = names.indexOf( traced.name );
9566 if ( nameIndex === -1 ) {
9567 nameIndex = names.length;
9568 names.push( traced.name );
9569 }
9570
9571 segment[4] = nameIndex;
9572 }
9573
9574 tracedLine.push( segment );
9575 }
9576 });
9577
9578 return tracedLine;
9579 });
9580
9581 return { sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings };
9582};
9583
9584Link.prototype.traceSegment = function traceSegment ( line, column, name ) {
9585 var this$1 = this;
9586
9587 var segments = this.mappings[ line ];
9588
9589 if ( !segments ) { return null; }
9590
9591 for ( var i = 0; i < segments.length; i += 1 ) {
9592 var segment = segments[i];
9593
9594 if ( segment[0] > column ) { return null; }
9595
9596 if ( segment[0] === column ) {
9597 var source = this$1.sources[ segment[1] ];
9598 if ( !source ) { return null; }
9599
9600 return source.traceSegment( segment[2], segment[3], this$1.names[ segment[4] ] || name );
9601 }
9602 }
9603
9604 return null;
9605};
9606
9607function collapseSourcemaps ( bundle, file, map, modules, bundleSourcemapChain ) {
9608 var moduleSources = modules.filter( function (module) { return !module.excludeFromSourcemap; } ).map( function (module) {
9609 var sourceMapChain = module.sourceMapChain;
9610
9611 var source;
9612 if ( module.originalSourceMap == null ) {
9613 source = new Source( module.id, module.originalCode );
9614 } else {
9615 var sources = module.originalSourceMap.sources;
9616 var sourcesContent = module.originalSourceMap.sourcesContent || [];
9617
9618 if ( sources == null || ( sources.length <= 1 && sources[0] == null ) ) {
9619 source = new Source( module.id, sourcesContent[0] );
9620 sourceMapChain = [ module.originalSourceMap ].concat( sourceMapChain );
9621 } else {
9622 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
9623 var directory = path.dirname( module.id ) || '.';
9624 var sourceRoot = module.originalSourceMap.sourceRoot || '.';
9625
9626 var baseSources = sources.map( function (source, i) {
9627 return new Source( path.resolve( directory, sourceRoot, source ), sourcesContent[i] );
9628 });
9629
9630 source = new Link( module.originalSourceMap, baseSources );
9631 }
9632 }
9633
9634 sourceMapChain.forEach( function (map) {
9635 if ( map.missing ) {
9636 bundle.warn({
9637 code: 'SOURCEMAP_BROKEN',
9638 plugin: map.plugin,
9639 message: ("Sourcemap is likely to be incorrect: a plugin" + (map.plugin ? (" ('" + (map.plugin) + "')") : "") + " was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help"),
9640 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#sourcemap-is-likely-to-be-incorrect"
9641 });
9642
9643 map = {
9644 names: [],
9645 mappings: ''
9646 };
9647 }
9648
9649 source = new Link( map, [ source ]);
9650 });
9651
9652 return source;
9653 });
9654
9655 var source = new Link( map, moduleSources );
9656
9657 bundleSourcemapChain.forEach( function (map) {
9658 source = new Link( map, [ source ] );
9659 });
9660
9661 var ref = source.traceMappings();
9662 var sources = ref.sources;
9663 var sourcesContent = ref.sourcesContent;
9664 var names = ref.names;
9665 var mappings = ref.mappings;
9666
9667 if ( file ) {
9668 var directory = path.dirname( file );
9669 sources = sources.map( function (source) { return path.relative( directory, source ); } );
9670
9671 map.file = path.basename( file );
9672 }
9673
9674 // we re-use the `map` object because it has convenient toString/toURL methods
9675 map.sources = sources;
9676 map.sourcesContent = sourcesContent;
9677 map.names = names;
9678 map.mappings = encode$$1( mappings );
9679
9680 return map;
9681}
9682
9683function callIfFunction ( thing ) {
9684 return typeof thing === 'function' ? thing() : thing;
9685}
9686
9687var SyntheticGlobalDeclaration = function SyntheticGlobalDeclaration ( name ) {
9688 this.name = name;
9689 this.isExternal = true;
9690 this.isGlobal = true;
9691 this.isReassigned = false;
9692
9693 this.activated = true;
9694};
9695
9696SyntheticGlobalDeclaration.prototype.activate = function activate () {
9697 /* noop */
9698};
9699
9700SyntheticGlobalDeclaration.prototype.addReference = function addReference ( reference ) {
9701 reference.declaration = this;
9702 if ( reference.isReassignment ) { this.isReassigned = true; }
9703};
9704
9705SyntheticGlobalDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
9706 values.add( UNKNOWN );
9707};
9708
9709SyntheticGlobalDeclaration.prototype.getName = function getName () {
9710 return this.name;
9711};
9712
9713var BundleScope = (function (Scope$$1) {
9714 function BundleScope () {
9715 Scope$$1.apply(this, arguments);
9716 }
9717
9718 if ( Scope$$1 ) BundleScope.__proto__ = Scope$$1;
9719 BundleScope.prototype = Object.create( Scope$$1 && Scope$$1.prototype );
9720 BundleScope.prototype.constructor = BundleScope;
9721
9722 BundleScope.prototype.findDeclaration = function findDeclaration ( name ) {
9723 if ( !this.declarations[ name ] ) {
9724 this.declarations[ name ] = new SyntheticGlobalDeclaration( name );
9725 }
9726
9727 return this.declarations[ name ];
9728 };
9729
9730 return BundleScope;
9731}(Scope));
9732
9733var Bundle = function Bundle ( options ) {
9734 var this$1 = this;
9735
9736 this.cachedModules = new Map();
9737 if ( options.cache ) {
9738 options.cache.modules.forEach( function (module) {
9739 this$1.cachedModules.set( module.id, module );
9740 } );
9741 }
9742
9743 this.plugins = ensureArray( options.plugins );
9744
9745 options = this.plugins.reduce( function ( acc, plugin ) {
9746 if ( plugin.options ) { return plugin.options( acc ) || acc; }
9747 return acc;
9748 }, options );
9749
9750 if ( !options.entry ) {
9751 throw new Error( 'You must supply options.entry to rollup' );
9752 }
9753
9754 this.entry = options.entry;
9755 this.entryId = null;
9756 this.entryModule = null;
9757
9758 this.treeshake = options.treeshake !== false;
9759
9760 if ( options.pureExternalModules === true ) {
9761 this.isPureExternalModule = function () { return true; };
9762 } else if ( typeof options.pureExternalModules === 'function' ) {
9763 this.isPureExternalModule = options.pureExternalModules;
9764 } else if ( Array.isArray( options.pureExternalModules ) ) {
9765 var pureExternalModules = new Set( options.pureExternalModules );
9766 this.isPureExternalModule = function (id) { return pureExternalModules.has( id ); };
9767 } else {
9768 this.isPureExternalModule = function () { return false; };
9769 }
9770
9771 this.resolveId = first(
9772 [ function (id) { return this$1.isExternal( id ) ? false : null; } ]
9773 .concat( this.plugins.map( function (plugin) { return plugin.resolveId; } ).filter( Boolean ) )
9774 .concat( resolveId )
9775 );
9776
9777 var loaders = this.plugins
9778 .map( function (plugin) { return plugin.load; } )
9779 .filter( Boolean );
9780 this.hasLoaders = loaders.length !== 0;
9781 this.load = first( loaders.concat( load ) );
9782
9783 var optionsPaths = options.paths;
9784 this.getPath = typeof optionsPaths === 'function' ?
9785 ( function (id) { return optionsPaths( id ) || this$1.getPathRelativeToEntryDirname( id ); } ) :
9786 optionsPaths ?
9787 ( function (id) { return optionsPaths.hasOwnProperty( id ) ? optionsPaths[ id ] : this$1.getPathRelativeToEntryDirname( id ); } ) :
9788 function (id) { return this$1.getPathRelativeToEntryDirname( id ); };
9789
9790 this.scope = new BundleScope();
9791 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
9792 [ 'module', 'exports', '_interopDefault' ].forEach( function (name) {
9793 this$1.scope.findDeclaration( name ); // creates global declaration as side-effect
9794 } );
9795
9796 this.moduleById = new Map();
9797 this.modules = [];
9798 this.externalModules = [];
9799
9800 this.context = String( options.context );
9801
9802 var optionsModuleContext = options.moduleContext;
9803 if ( typeof optionsModuleContext === 'function' ) {
9804 this.getModuleContext = function (id) { return optionsModuleContext( id ) || this$1.context; };
9805 } else if ( typeof optionsModuleContext === 'object' ) {
9806 var moduleContext = new Map();
9807 Object.keys( optionsModuleContext ).forEach( function (key) {
9808 moduleContext.set( path.resolve( key ), optionsModuleContext[ key ] );
9809 } );
9810 this.getModuleContext = function (id) { return moduleContext.get( id ) || this$1.context; };
9811 } else {
9812 this.getModuleContext = function () { return this$1.context; };
9813 }
9814
9815 if ( typeof options.external === 'function' ) {
9816 this.isExternal = options.external;
9817 } else {
9818 var ids = ensureArray( options.external );
9819 this.isExternal = function (id) { return ids.indexOf( id ) !== -1; };
9820 }
9821
9822 this.onwarn = options.onwarn || makeOnwarn();
9823
9824 this.varOrConst = options.preferConst ? 'const' : 'var';
9825 this.legacy = options.legacy;
9826 this.acornOptions = options.acorn || {};
9827
9828 this.dependentExpressions = [];
9829};
9830
9831Bundle.prototype.build = function build () {
9832 var this$1 = this;
9833
9834 // Phase 1 – discovery. We load the entry module and find which
9835 // modules it imports, and import those, until we have all
9836 // of the entry module's dependencies
9837 return this.resolveId( this.entry, undefined )
9838 .then( function (id) {
9839 if ( id === false ) {
9840 error( {
9841 code: 'UNRESOLVED_ENTRY',
9842 message: "Entry module cannot be external"
9843 } );
9844 }
9845
9846 if ( id == null ) {
9847 error( {
9848 code: 'UNRESOLVED_ENTRY',
9849 message: ("Could not resolve entry (" + (this$1.entry) + ")")
9850 } );
9851 }
9852
9853 this$1.entryId = id;
9854 return this$1.fetchModule( id, undefined );
9855 } )
9856 .then( function (entryModule) {
9857 this$1.entryModule = entryModule;
9858
9859 // Phase 2 – binding. We link references to their declarations
9860 // to generate a complete picture of the bundle
9861
9862 timeStart( 'phase 2' );
9863
9864 this$1.modules.forEach( function (module) { return module.bindImportSpecifiers(); } );
9865 this$1.modules.forEach( function (module) { return module.bindReferences(); } );
9866
9867 timeEnd( 'phase 2' );
9868
9869 // Phase 3 – marking. We 'run' each statement to see which ones
9870 // need to be included in the generated bundle
9871
9872 timeStart( 'phase 3' );
9873
9874 // mark all export statements
9875 entryModule.getExports().forEach( function (name) {
9876 var declaration = entryModule.traceExport( name );
9877
9878 declaration.exportName = name;
9879 declaration.activate();
9880
9881 if ( declaration.isNamespace ) {
9882 declaration.needsNamespaceBlock = true;
9883 }
9884 });
9885
9886 entryModule.getReexports().forEach( function (name) {
9887 var declaration = entryModule.traceExport( name );
9888
9889 if ( declaration.isExternal ) {
9890 declaration.reexported = declaration.module.reexported = true;
9891 } else {
9892 declaration.exportName = name;
9893 declaration.activate();
9894 }
9895 });
9896
9897 // mark statements that should appear in the bundle
9898 if ( this$1.treeshake ) {
9899 this$1.modules.forEach( function (module) {
9900 module.run();
9901 } );
9902
9903 var settled = false;
9904 while ( !settled ) {
9905 settled = true;
9906
9907 var i = this$1.dependentExpressions.length;
9908 while ( i-- ) {
9909 var expression = this$1.dependentExpressions[ i ];
9910
9911 var statement = expression;
9912 while ( statement.parent && !/Function/.test( statement.parent.type ) ) { statement = statement.parent; }
9913
9914 if ( !statement || statement.ran ) {
9915 this$1.dependentExpressions.splice( i, 1 );
9916 } else if ( expression.isUsedByBundle() ) {
9917 settled = false;
9918 statement.run();
9919 this$1.dependentExpressions.splice( i, 1 );
9920 }
9921 }
9922 }
9923 }
9924
9925 timeEnd( 'phase 3' );
9926
9927 // Phase 4 – final preparation. We order the modules with an
9928 // enhanced topological sort that accounts for cycles, then
9929 // ensure that names are deconflicted throughout the bundle
9930
9931 timeStart( 'phase 4' );
9932
9933 // while we're here, check for unused external imports
9934 this$1.externalModules.forEach( function (module) {
9935 var unused = Object.keys( module.declarations )
9936 .filter( function (name) { return name !== '*'; } )
9937 .filter( function (name) { return !module.declarations[ name ].activated && !module.declarations[ name ].reexported; } );
9938
9939 if ( unused.length === 0 ) { return; }
9940
9941 var names = unused.length === 1 ?
9942 ("'" + (unused[0]) + "' is") :
9943 ((unused.slice( 0, -1 ).map( function (name) { return ("'" + name + "'"); } ).join( ', ' )) + " and '" + (unused.slice( -1 )) + "' are");
9944
9945 this$1.warn( {
9946 code: 'UNUSED_EXTERNAL_IMPORT',
9947 source: module.id,
9948 names: unused,
9949 message: (names + " imported from external module '" + (module.id) + "' but never used")
9950 } );
9951 } );
9952
9953 // prune unused external imports
9954 this$1.externalModules = this$1.externalModules.filter( function (module) {
9955 return module.used || !this$1.isPureExternalModule( module.id );
9956 } );
9957
9958 this$1.orderedModules = this$1.sort();
9959 this$1.deconflict();
9960
9961 timeEnd( 'phase 4' );
9962 } );
9963};
9964
9965Bundle.prototype.deconflict = function deconflict () {
9966 var used = blank();
9967
9968 // ensure no conflicts with globals
9969 keys( this.scope.declarations ).forEach( function (name) { return used[ name ] = 1; } );
9970
9971 function getSafeName ( name ) {
9972 while ( used[ name ] ) {
9973 name += "$" + (used[ name ]++);
9974 }
9975
9976 used[ name ] = 1;
9977 return name;
9978 }
9979
9980 var toDeshadow = new Set();
9981
9982 this.externalModules.forEach( function (module) {
9983 var safeName = getSafeName( module.name );
9984 toDeshadow.add( safeName );
9985 module.name = safeName;
9986
9987 // ensure we don't shadow named external imports, if
9988 // we're creating an ES6 bundle
9989 forOwn( module.declarations, function ( declaration, name ) {
9990 var safeName = getSafeName( name );
9991 toDeshadow.add( safeName );
9992 declaration.setSafeName( safeName );
9993 } );
9994 } );
9995
9996 this.modules.forEach( function (module) {
9997 forOwn( module.scope.declarations, function ( declaration ) {
9998 if ( declaration.isDefault && declaration.declaration.id ) {
9999 return;
10000 }
10001
10002 declaration.name = getSafeName( declaration.name );
10003 } );
10004
10005 // deconflict reified namespaces
10006 var namespace = module.namespace();
10007 if ( namespace.needsNamespaceBlock ) {
10008 namespace.name = getSafeName( namespace.name );
10009 }
10010 } );
10011
10012 this.scope.deshadow( toDeshadow );
10013};
10014
10015Bundle.prototype.fetchModule = function fetchModule ( id, importer ) {
10016 var this$1 = this;
10017
10018 // short-circuit cycles
10019 if ( this.moduleById.has( id ) ) { return null; }
10020 this.moduleById.set( id, null );
10021
10022 return this.load( id )
10023 .catch( function (err) {
10024 var msg = "Could not load " + id;
10025 if ( importer ) { msg += " (imported by " + importer + ")"; }
10026
10027 msg += ": " + (err.message);
10028 throw new Error( msg );
10029 } )
10030 .then( function (source) {
10031 if ( typeof source === 'string' ) { return source; }
10032 if ( source && typeof source === 'object' && source.code ) { return source; }
10033
10034 // TODO report which plugin failed
10035 error( {
10036 code: 'BAD_LOADER',
10037 message: ("Error loading " + (relativeId( id )) + ": plugin load hook should return a string, a { code, map } object, or nothing/null")
10038 } );
10039 } )
10040 .then( function (source) {
10041 if ( typeof source === 'string' ) {
10042 source = {
10043 code: source,
10044 ast: null
10045 };
10046 }
10047
10048 if ( this$1.cachedModules.has( id ) && this$1.cachedModules.get( id ).originalCode === source.code ) {
10049 return this$1.cachedModules.get( id );
10050 }
10051
10052 return transform( this$1, source, id, this$1.plugins );
10053 } )
10054 .then( function (source) {
10055 var code = source.code;
10056 var originalCode = source.originalCode;
10057 var originalSourceMap = source.originalSourceMap;
10058 var ast = source.ast;
10059 var sourceMapChain = source.sourceMapChain;
10060 var resolvedIds = source.resolvedIds;
10061
10062 var module = new Module( {
10063 id: id,
10064 code: code,
10065 originalCode: originalCode,
10066 originalSourceMap: originalSourceMap,
10067 ast: ast,
10068 sourceMapChain: sourceMapChain,
10069 resolvedIds: resolvedIds,
10070 bundle: this$1
10071 } );
10072
10073 this$1.modules.push( module );
10074 this$1.moduleById.set( id, module );
10075
10076 return this$1.fetchAllDependencies( module ).then( function () {
10077 keys( module.exports ).forEach( function (name) {
10078 if ( name !== 'default' ) {
10079 module.exportsAll[ name ] = module.id;
10080 }
10081 } );
10082 module.exportAllSources.forEach( function (source) {
10083 var id = module.resolvedIds[ source ] || module.resolvedExternalIds[ source ];
10084 var exportAllModule = this$1.moduleById.get( id );
10085 if ( exportAllModule.isExternal ) { return; }
10086
10087 keys( exportAllModule.exportsAll ).forEach( function (name) {
10088 if ( name in module.exportsAll ) {
10089 this$1.warn( {
10090 code: 'NAMESPACE_CONFLICT',
10091 reexporter: module.id,
10092 name: name,
10093 sources: [ module.exportsAll[ name ], exportAllModule.exportsAll[ name ] ],
10094 message: ("Conflicting namespaces: " + (relativeId( module.id )) + " re-exports '" + name + "' from both " + (relativeId( module.exportsAll[ name ] )) + " and " + (relativeId( exportAllModule.exportsAll[ name ] )) + " (will be ignored)")
10095 } );
10096 } else {
10097 module.exportsAll[ name ] = exportAllModule.exportsAll[ name ];
10098 }
10099 } );
10100 } );
10101 return module;
10102 } );
10103 } );
10104};
10105
10106Bundle.prototype.fetchAllDependencies = function fetchAllDependencies ( module ) {
10107 var this$1 = this;
10108
10109 return mapSequence( module.sources, function (source) {
10110 var resolvedId = module.resolvedIds[ source ];
10111 return ( resolvedId ? Promise.resolve( resolvedId ) : this$1.resolveId( source, module.id ) )
10112 .then( function (resolvedId) {
10113 var externalId = resolvedId || (
10114 isRelative( source ) ? path.resolve( module.id, '..', source ) : source
10115 );
10116
10117 var isExternal = this$1.isExternal( externalId );
10118
10119 if ( !resolvedId && !isExternal ) {
10120 if ( isRelative( source ) ) {
10121 error( {
10122 code: 'UNRESOLVED_IMPORT',
10123 message: ("Could not resolve '" + source + "' from " + (relativeId( module.id )))
10124 } );
10125 }
10126
10127 this$1.warn( {
10128 code: 'UNRESOLVED_IMPORT',
10129 source: source,
10130 importer: relativeId( module.id ),
10131 message: ("'" + source + "' is imported by " + (relativeId( module.id )) + ", but could not be resolved – treating it as an external dependency"),
10132 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency'
10133 } );
10134 isExternal = true;
10135 }
10136
10137 if ( isExternal ) {
10138 module.resolvedExternalIds[ source ] = externalId;
10139
10140 if ( !this$1.moduleById.has( externalId ) ) {
10141 var module$1$$1 = new ExternalModule( externalId, this$1.getPath( externalId ) );
10142 this$1.externalModules.push( module$1$$1 );
10143 this$1.moduleById.set( externalId, module$1$$1 );
10144 }
10145
10146 var externalModule = this$1.moduleById.get( externalId );
10147
10148 // add external declarations so we can detect which are never used
10149 Object.keys( module.imports ).forEach( function (name) {
10150 var importDeclaration = module.imports[ name ];
10151 if ( importDeclaration.source !== source ) { return; }
10152
10153 externalModule.traceExport( importDeclaration.name );
10154 } );
10155 } else {
10156 if ( resolvedId === module.id ) {
10157 // need to find the actual import declaration, so we can provide
10158 // a useful error message. Bit hoop-jumpy but what can you do
10159 var declaration = module.ast.body.find( function (node) {
10160 return node.isImportDeclaration && node.source.value === source;
10161 } );
10162
10163 module.error( {
10164 code: 'CANNOT_IMPORT_SELF',
10165 message: "A module cannot import itself"
10166 }, declaration.start );
10167 }
10168
10169 module.resolvedIds[ source ] = resolvedId;
10170 return this$1.fetchModule( resolvedId, module.id );
10171 }
10172 } );
10173 } );
10174};
10175
10176Bundle.prototype.getPathRelativeToEntryDirname = function getPathRelativeToEntryDirname ( resolvedId ) {
10177 if ( isRelative( resolvedId ) || isAbsolute( resolvedId ) ) {
10178 var entryDirname = path.dirname( this.entryId );
10179 var relativeToEntry = normalize( path.relative( entryDirname, resolvedId ) );
10180
10181 return isRelative( relativeToEntry ) ? relativeToEntry : ("./" + relativeToEntry);
10182 }
10183
10184 return resolvedId;
10185};
10186
10187Bundle.prototype.render = function render ( options ) {
10188 var this$1 = this;
10189 if ( options === void 0 ) options = {};
10190
10191 return Promise.resolve().then( function () {
10192 // Determine export mode - 'default', 'named', 'none'
10193 var exportMode = getExportMode( this$1, options );
10194
10195 var magicString = new Bundle$2( { separator: '\n\n' } );
10196 var usedModules = [];
10197
10198 timeStart( 'render modules' );
10199
10200 this$1.orderedModules.forEach( function (module) {
10201 var source = module.render( options.format === 'es', this$1.legacy );
10202
10203 if ( source.toString().length ) {
10204 magicString.addSource( source );
10205 usedModules.push( module );
10206 }
10207 } );
10208
10209 if ( !magicString.toString().trim() && this$1.entryModule.getExports().length === 0 && this$1.entryModule.getReexports().length === 0 ) {
10210 this$1.warn( {
10211 code: 'EMPTY_BUNDLE',
10212 message: 'Generated an empty bundle'
10213 } );
10214 }
10215
10216 timeEnd( 'render modules' );
10217
10218 var intro = [ options.intro ]
10219 .concat(
10220 this$1.plugins.map( function (plugin) { return plugin.intro && plugin.intro(); } )
10221 )
10222 .filter( Boolean )
10223 .join( '\n\n' );
10224
10225 if ( intro ) { intro += '\n\n'; }
10226
10227 var outro = [ options.outro ]
10228 .concat(
10229 this$1.plugins.map( function (plugin) { return plugin.outro && plugin.outro(); } )
10230 )
10231 .filter( Boolean )
10232 .join( '\n\n' );
10233
10234 if ( outro ) { outro = "\n\n" + outro; }
10235
10236 var indentString = getIndentString( magicString, options );
10237
10238 var finalise = finalisers[ options.format ];
10239 if ( !finalise ) {
10240 error({
10241 code: 'INVALID_OPTION',
10242 message: ("Invalid format: " + (options.format) + " - valid options are " + (keys( finalisers ).join( ', ' )))
10243 });
10244 }
10245
10246 timeStart( 'render format' );
10247
10248 magicString = finalise( this$1, magicString.trim(), { exportMode: exportMode, indentString: indentString, intro: intro, outro: outro }, options );
10249
10250 timeEnd( 'render format' );
10251
10252 var banner = [ options.banner ]
10253 .concat( this$1.plugins.map( function (plugin) { return plugin.banner; } ) )
10254 .map( callIfFunction )
10255 .filter( Boolean )
10256 .join( '\n' );
10257
10258 var footer = [ options.footer ]
10259 .concat( this$1.plugins.map( function (plugin) { return plugin.footer; } ) )
10260 .map( callIfFunction )
10261 .filter( Boolean )
10262 .join( '\n' );
10263
10264 if ( banner ) { magicString.prepend( banner + '\n' ); }
10265 if ( footer ) { magicString.append( '\n' + footer ); }
10266
10267 var prevCode = magicString.toString();
10268 var map = null;
10269 var bundleSourcemapChain = [];
10270
10271 return transformBundle( prevCode, this$1.plugins, bundleSourcemapChain, options ).then( function (code) {
10272 if ( options.sourceMap ) {
10273 timeStart( 'sourceMap' );
10274
10275 var file = options.sourceMapFile || options.dest;
10276 if ( file ) { file = path.resolve( typeof process !== 'undefined' ? process.cwd() : '', file ); }
10277
10278 if ( this$1.hasLoaders || find( this$1.plugins, function (plugin) { return plugin.transform || plugin.transformBundle; } ) ) {
10279 map = magicString.generateMap( {} );
10280 if ( typeof map.mappings === 'string' ) {
10281 map.mappings = decode$$1( map.mappings );
10282 }
10283 map = collapseSourcemaps( this$1, file, map, usedModules, bundleSourcemapChain );
10284 } else {
10285 map = magicString.generateMap( { file: file, includeContent: true } );
10286 }
10287
10288 map.sources = map.sources.map( normalize );
10289
10290 timeEnd( 'sourceMap' );
10291 }
10292
10293 if ( code[ code.length - 1 ] !== '\n' ) { code += '\n'; }
10294 return { code: code, map: map };
10295 } );
10296 } );
10297};
10298
10299Bundle.prototype.sort = function sort () {
10300 var this$1 = this;
10301
10302 var hasCycles;
10303 var seen = {};
10304 var ordered = [];
10305
10306 var stronglyDependsOn = blank();
10307 var dependsOn = blank();
10308
10309 this.modules.forEach( function (module) {
10310 stronglyDependsOn[ module.id ] = blank();
10311 dependsOn[ module.id ] = blank();
10312 } );
10313
10314 this.modules.forEach( function (module) {
10315 function processStrongDependency ( dependency ) {
10316 if ( dependency === module || stronglyDependsOn[ module.id ][ dependency.id ] ) { return; }
10317
10318 stronglyDependsOn[ module.id ][ dependency.id ] = true;
10319 dependency.strongDependencies.forEach( processStrongDependency );
10320 }
10321
10322 function processDependency ( dependency ) {
10323 if ( dependency === module || dependsOn[ module.id ][ dependency.id ] ) { return; }
10324
10325 dependsOn[ module.id ][ dependency.id ] = true;
10326 dependency.dependencies.forEach( processDependency );
10327 }
10328
10329 module.strongDependencies.forEach( processStrongDependency );
10330 module.dependencies.forEach( processDependency );
10331 } );
10332
10333 var visit = function (module) {
10334 if ( seen[ module.id ] ) {
10335 hasCycles = true;
10336 return;
10337 }
10338
10339 seen[ module.id ] = true;
10340
10341 module.dependencies.forEach( visit );
10342 ordered.push( module );
10343 };
10344
10345 visit( this.entryModule );
10346
10347 if ( hasCycles ) {
10348 ordered.forEach( function ( a, i ) {
10349 var loop = function ( ) {
10350 var b = ordered[ i ];
10351
10352 // TODO reinstate this! it no longer works
10353 if ( stronglyDependsOn[ a.id ][ b.id ] ) {
10354 // somewhere, there is a module that imports b before a. Because
10355 // b imports a, a is placed before b. We need to find the module
10356 // in question, so we can provide a useful error message
10357 var parent = '[[unknown]]';
10358 var visited = {};
10359
10360 var findParent = function (module) {
10361 if ( dependsOn[ module.id ][ a.id ] && dependsOn[ module.id ][ b.id ] ) {
10362 parent = module.id;
10363 return true;
10364 }
10365 visited[ module.id ] = true;
10366 for ( var i = 0; i < module.dependencies.length; i += 1 ) {
10367 var dependency = module.dependencies[ i ];
10368 if ( !visited[ dependency.id ] && findParent( dependency ) ) { return true; }
10369 }
10370 };
10371
10372 findParent( this$1.entryModule );
10373
10374 this$1.onwarn(
10375 ("Module " + (a.id) + " may be unable to evaluate without " + (b.id) + ", but is included first due to a cyclical dependency. Consider swapping the import statements in " + parent + " to ensure correct ordering")
10376 );
10377 }
10378 };
10379
10380 for ( i += 1; i < ordered.length; i += 1 ) loop( );
10381 } );
10382 }
10383
10384 return ordered;
10385};
10386
10387Bundle.prototype.warn = function warn ( warning ) {
10388 warning.toString = function () {
10389 var str = '';
10390
10391 if ( warning.plugin ) { str += "(" + (warning.plugin) + " plugin) "; }
10392 if ( warning.loc ) { str += (relativeId( warning.loc.file )) + " (" + (warning.loc.line) + ":" + (warning.loc.column) + ") "; }
10393 str += warning.message;
10394
10395 return str;
10396 };
10397
10398 this.onwarn( warning );
10399};
10400
10401var ALLOWED_KEYS = [
10402 'acorn',
10403 'amd',
10404 'banner',
10405 'cache',
10406 'context',
10407 'dest',
10408 'entry',
10409 'exports',
10410 'extend',
10411 'external',
10412 'footer',
10413 'format',
10414 'globals',
10415 'indent',
10416 'interop',
10417 'intro',
10418 'legacy',
10419 'moduleContext',
10420 'moduleName',
10421 'noConflict',
10422 'onwarn',
10423 'outro',
10424 'paths',
10425 'plugins',
10426 'preferConst',
10427 'pureExternalModules',
10428 'sourceMap',
10429 'sourceMapFile',
10430 'targets',
10431 'treeshake',
10432 'useStrict',
10433 'watch'
10434];
10435
10436function checkAmd ( options ) {
10437 if ( options.moduleId ) {
10438 if ( options.amd ) { throw new Error( 'Cannot have both options.amd and options.moduleId' ); }
10439
10440 options.amd = { id: options.moduleId };
10441 delete options.moduleId;
10442
10443 var msg = "options.moduleId is deprecated in favour of options.amd = { id: moduleId }";
10444 if ( options.onwarn ) {
10445 options.onwarn( msg );
10446 } else {
10447 console.warn( msg ); // eslint-disable-line no-console
10448 }
10449 }
10450}
10451
10452function checkOptions ( options ) {
10453 if ( !options ) {
10454 throw new Error( 'You must supply an options object to rollup' );
10455 }
10456
10457 if ( options.transform || options.load || options.resolveId || options.resolveExternal ) {
10458 throw new Error( 'The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://github.com/rollup/rollup/wiki/Plugins for details' );
10459 }
10460
10461 checkAmd (options);
10462
10463 var err = validateKeys( keys(options), ALLOWED_KEYS );
10464 if ( err ) { throw err; }
10465}
10466
10467var throwAsyncGenerateError = {
10468 get: function get () {
10469 throw new Error( "bundle.generate(...) now returns a Promise instead of a { code, map } object" );
10470 }
10471};
10472
10473function rollup ( options ) {
10474 try {
10475 checkOptions( options );
10476 var bundle = new Bundle( options );
10477
10478 timeStart( '--BUILD--' );
10479
10480 return bundle.build().then( function () {
10481 timeEnd( '--BUILD--' );
10482
10483 function generate ( options ) {
10484 if ( options === void 0 ) options = {};
10485
10486 if ( options.format === 'es6' ) {
10487 throw new Error( 'The `es6` output format is deprecated – use `es` instead' );
10488 }
10489
10490 if ( !options.format ) {
10491 error({
10492 code: 'MISSING_FORMAT',
10493 message: "You must supply an output format",
10494 url: "https://github.com/rollup/rollup/wiki/JavaScript-API#format"
10495 });
10496 }
10497
10498 checkAmd( options );
10499
10500 timeStart( '--GENERATE--' );
10501
10502 var promise = Promise.resolve()
10503 .then( function () { return bundle.render( options ); } )
10504 .then( function (rendered) {
10505 timeEnd( '--GENERATE--' );
10506
10507 bundle.plugins.forEach( function (plugin) {
10508 if ( plugin.ongenerate ) {
10509 plugin.ongenerate( assign({
10510 bundle: result
10511 }, options ), rendered);
10512 }
10513 });
10514
10515 flushTime();
10516
10517 return rendered;
10518 });
10519
10520 Object.defineProperty( promise, 'code', throwAsyncGenerateError );
10521 Object.defineProperty( promise, 'map', throwAsyncGenerateError );
10522
10523 return promise;
10524 }
10525
10526 var result = {
10527 imports: bundle.externalModules.map( function (module) { return module.id; } ),
10528 exports: keys( bundle.entryModule.exports ),
10529 modules: bundle.orderedModules.map( function (module) { return module.toJSON(); } ),
10530
10531 generate: generate,
10532 write: function (options) {
10533 if ( !options || !options.dest ) {
10534 error({
10535 code: 'MISSING_OPTION',
10536 message: 'You must supply options.dest to bundle.write'
10537 });
10538 }
10539
10540 var dest = options.dest;
10541 return generate( options ).then( function (output) {
10542 var code = output.code;
10543 var map = output.map;
10544
10545 var promises = [];
10546
10547 if ( options.sourceMap ) {
10548 var url;
10549
10550 if ( options.sourceMap === 'inline' ) {
10551 url = map.toUrl();
10552 } else {
10553 url = (path.basename( dest )) + ".map";
10554 promises.push( writeFile$1( dest + '.map', map.toString() ) );
10555 }
10556
10557 code += "//# " + SOURCEMAPPING_URL + "=" + url + "\n";
10558 }
10559
10560 promises.push( writeFile$1( dest, code ) );
10561 return Promise.all( promises ).then( function () {
10562 return mapSequence( bundle.plugins.filter( function (plugin) { return plugin.onwrite; } ), function (plugin) {
10563 return Promise.resolve( plugin.onwrite( assign({
10564 bundle: result
10565 }, options ), output));
10566 });
10567 });
10568 });
10569 }
10570 };
10571
10572 return result;
10573 });
10574 } catch ( err ) {
10575 return Promise.reject( err );
10576 }
10577}
10578
10579function createCommonjsModule(fn, module) {
10580 return module = { exports: {} }, fn(module, module.exports), module.exports;
10581}
10582
10583/*!
10584 * filename-regex <https://github.com/regexps/filename-regex>
10585 *
10586 * Copyright (c) 2014-2015, Jon Schlinkert
10587 * Licensed under the MIT license.
10588 */
10589
10590var index$2 = function filenameRegex() {
10591 return /([^\\\/]+)$/;
10592};
10593
10594/*!
10595 * arr-flatten <https://github.com/jonschlinkert/arr-flatten>
10596 *
10597 * Copyright (c) 2014-2017, Jon Schlinkert.
10598 * Released under the MIT License.
10599 */
10600
10601var index$6 = function (arr) {
10602 return flat(arr, []);
10603};
10604
10605function flat(arr, res) {
10606 var i = 0, cur;
10607 var len = arr.length;
10608 for (; i < len; i++) {
10609 cur = arr[i];
10610 Array.isArray(cur) ? flat(cur, res) : res.push(cur);
10611 }
10612 return res;
10613}
10614
10615var slice = [].slice;
10616
10617/**
10618 * Return the difference between the first array and
10619 * additional arrays.
10620 *
10621 * ```js
10622 * var diff = require('{%= name %}');
10623 *
10624 * var a = ['a', 'b', 'c', 'd'];
10625 * var b = ['b', 'c'];
10626 *
10627 * console.log(diff(a, b))
10628 * //=> ['a', 'd']
10629 * ```
10630 *
10631 * @param {Array} `a`
10632 * @param {Array} `b`
10633 * @return {Array}
10634 * @api public
10635 */
10636
10637function diff(arr, arrays) {
10638 var argsLen = arguments.length;
10639 var len = arr.length, i = -1;
10640 var res = [], arrays;
10641
10642 if (argsLen === 1) {
10643 return arr;
10644 }
10645
10646 if (argsLen > 2) {
10647 arrays = index$6(slice.call(arguments, 1));
10648 }
10649
10650 while (++i < len) {
10651 if (!~arrays.indexOf(arr[i])) {
10652 res.push(arr[i]);
10653 }
10654 }
10655 return res;
10656}
10657
10658/**
10659 * Expose `diff`
10660 */
10661
10662var index$4 = diff;
10663
10664/*!
10665 * array-unique <https://github.com/jonschlinkert/array-unique>
10666 *
10667 * Copyright (c) 2014-2015, Jon Schlinkert.
10668 * Licensed under the MIT License.
10669 */
10670
10671var index$8 = function unique(arr) {
10672 if (!Array.isArray(arr)) {
10673 throw new TypeError('array-unique expects an array.');
10674 }
10675
10676 var len = arr.length;
10677 var i = -1;
10678
10679 while (i++ < len) {
10680 var j = i + 1;
10681
10682 for (; j < arr.length; ++j) {
10683 if (arr[i] === arr[j]) {
10684 arr.splice(j--, 1);
10685 }
10686 }
10687 }
10688 return arr;
10689};
10690
10691var toString$1$1 = {}.toString;
10692
10693var index$18 = Array.isArray || function (arr) {
10694 return toString$1$1.call(arr) == '[object Array]';
10695};
10696
10697var index$16 = function isObject(val) {
10698 return val != null && typeof val === 'object' && index$18(val) === false;
10699};
10700
10701/*!
10702 * Determine if an object is a Buffer
10703 *
10704 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10705 * @license MIT
10706 */
10707
10708// The _isBuffer check is for Safari 5-7 support, because it's missing
10709// Object.prototype.constructor. Remove this eventually
10710var index$24 = function (obj) {
10711 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10712};
10713
10714function isBuffer (obj) {
10715 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10716}
10717
10718// For Node v0.10 support. Remove this eventually.
10719function isSlowBuffer (obj) {
10720 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
10721}
10722
10723var toString$2 = Object.prototype.toString;
10724
10725/**
10726 * Get the native `typeof` a value.
10727 *
10728 * @param {*} `val`
10729 * @return {*} Native javascript type
10730 */
10731
10732var index$22 = function kindOf(val) {
10733 // primitivies
10734 if (typeof val === 'undefined') {
10735 return 'undefined';
10736 }
10737 if (val === null) {
10738 return 'null';
10739 }
10740 if (val === true || val === false || val instanceof Boolean) {
10741 return 'boolean';
10742 }
10743 if (typeof val === 'string' || val instanceof String) {
10744 return 'string';
10745 }
10746 if (typeof val === 'number' || val instanceof Number) {
10747 return 'number';
10748 }
10749
10750 // functions
10751 if (typeof val === 'function' || val instanceof Function) {
10752 return 'function';
10753 }
10754
10755 // array
10756 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
10757 return 'array';
10758 }
10759
10760 // check for instances of RegExp and Date before calling `toString`
10761 if (val instanceof RegExp) {
10762 return 'regexp';
10763 }
10764 if (val instanceof Date) {
10765 return 'date';
10766 }
10767
10768 // other objects
10769 var type = toString$2.call(val);
10770
10771 if (type === '[object RegExp]') {
10772 return 'regexp';
10773 }
10774 if (type === '[object Date]') {
10775 return 'date';
10776 }
10777 if (type === '[object Arguments]') {
10778 return 'arguments';
10779 }
10780 if (type === '[object Error]') {
10781 return 'error';
10782 }
10783
10784 // buffer
10785 if (index$24(val)) {
10786 return 'buffer';
10787 }
10788
10789 // es6: Map, WeakMap, Set, WeakSet
10790 if (type === '[object Set]') {
10791 return 'set';
10792 }
10793 if (type === '[object WeakSet]') {
10794 return 'weakset';
10795 }
10796 if (type === '[object Map]') {
10797 return 'map';
10798 }
10799 if (type === '[object WeakMap]') {
10800 return 'weakmap';
10801 }
10802 if (type === '[object Symbol]') {
10803 return 'symbol';
10804 }
10805
10806 // typed arrays
10807 if (type === '[object Int8Array]') {
10808 return 'int8array';
10809 }
10810 if (type === '[object Uint8Array]') {
10811 return 'uint8array';
10812 }
10813 if (type === '[object Uint8ClampedArray]') {
10814 return 'uint8clampedarray';
10815 }
10816 if (type === '[object Int16Array]') {
10817 return 'int16array';
10818 }
10819 if (type === '[object Uint16Array]') {
10820 return 'uint16array';
10821 }
10822 if (type === '[object Int32Array]') {
10823 return 'int32array';
10824 }
10825 if (type === '[object Uint32Array]') {
10826 return 'uint32array';
10827 }
10828 if (type === '[object Float32Array]') {
10829 return 'float32array';
10830 }
10831 if (type === '[object Float64Array]') {
10832 return 'float64array';
10833 }
10834
10835 // must be a plain object
10836 return 'object';
10837};
10838
10839var index$20 = function isNumber(num) {
10840 var type = index$22(num);
10841 if (type !== 'number' && type !== 'string') {
10842 return false;
10843 }
10844 var n = +num;
10845 return (n - n + 1) >= 0 && num !== '';
10846};
10847
10848var toString$3 = Object.prototype.toString;
10849
10850/**
10851 * Get the native `typeof` a value.
10852 *
10853 * @param {*} `val`
10854 * @return {*} Native javascript type
10855 */
10856
10857var index$30 = function kindOf(val) {
10858 // primitivies
10859 if (typeof val === 'undefined') {
10860 return 'undefined';
10861 }
10862 if (val === null) {
10863 return 'null';
10864 }
10865 if (val === true || val === false || val instanceof Boolean) {
10866 return 'boolean';
10867 }
10868 if (typeof val === 'string' || val instanceof String) {
10869 return 'string';
10870 }
10871 if (typeof val === 'number' || val instanceof Number) {
10872 return 'number';
10873 }
10874
10875 // functions
10876 if (typeof val === 'function' || val instanceof Function) {
10877 return 'function';
10878 }
10879
10880 // array
10881 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
10882 return 'array';
10883 }
10884
10885 // check for instances of RegExp and Date before calling `toString`
10886 if (val instanceof RegExp) {
10887 return 'regexp';
10888 }
10889 if (val instanceof Date) {
10890 return 'date';
10891 }
10892
10893 // other objects
10894 var type = toString$3.call(val);
10895
10896 if (type === '[object RegExp]') {
10897 return 'regexp';
10898 }
10899 if (type === '[object Date]') {
10900 return 'date';
10901 }
10902 if (type === '[object Arguments]') {
10903 return 'arguments';
10904 }
10905 if (type === '[object Error]') {
10906 return 'error';
10907 }
10908
10909 // buffer
10910 if (index$24(val)) {
10911 return 'buffer';
10912 }
10913
10914 // es6: Map, WeakMap, Set, WeakSet
10915 if (type === '[object Set]') {
10916 return 'set';
10917 }
10918 if (type === '[object WeakSet]') {
10919 return 'weakset';
10920 }
10921 if (type === '[object Map]') {
10922 return 'map';
10923 }
10924 if (type === '[object WeakMap]') {
10925 return 'weakmap';
10926 }
10927 if (type === '[object Symbol]') {
10928 return 'symbol';
10929 }
10930
10931 // typed arrays
10932 if (type === '[object Int8Array]') {
10933 return 'int8array';
10934 }
10935 if (type === '[object Uint8Array]') {
10936 return 'uint8array';
10937 }
10938 if (type === '[object Uint8ClampedArray]') {
10939 return 'uint8clampedarray';
10940 }
10941 if (type === '[object Int16Array]') {
10942 return 'int16array';
10943 }
10944 if (type === '[object Uint16Array]') {
10945 return 'uint16array';
10946 }
10947 if (type === '[object Int32Array]') {
10948 return 'int32array';
10949 }
10950 if (type === '[object Uint32Array]') {
10951 return 'uint32array';
10952 }
10953 if (type === '[object Float32Array]') {
10954 return 'float32array';
10955 }
10956 if (type === '[object Float64Array]') {
10957 return 'float64array';
10958 }
10959
10960 // must be a plain object
10961 return 'object';
10962};
10963
10964var index$28 = function isNumber(num) {
10965 var type = index$30(num);
10966
10967 if (type === 'string') {
10968 if (!num.trim()) return false;
10969 } else if (type !== 'number') {
10970 return false;
10971 }
10972
10973 return (num - num + 1) >= 0;
10974};
10975
10976var toString$4 = Object.prototype.toString;
10977
10978/**
10979 * Get the native `typeof` a value.
10980 *
10981 * @param {*} `val`
10982 * @return {*} Native javascript type
10983 */
10984
10985var index$32 = function kindOf(val) {
10986 // primitivies
10987 if (typeof val === 'undefined') {
10988 return 'undefined';
10989 }
10990 if (val === null) {
10991 return 'null';
10992 }
10993 if (val === true || val === false || val instanceof Boolean) {
10994 return 'boolean';
10995 }
10996 if (typeof val === 'string' || val instanceof String) {
10997 return 'string';
10998 }
10999 if (typeof val === 'number' || val instanceof Number) {
11000 return 'number';
11001 }
11002
11003 // functions
11004 if (typeof val === 'function' || val instanceof Function) {
11005 return 'function';
11006 }
11007
11008 // array
11009 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
11010 return 'array';
11011 }
11012
11013 // check for instances of RegExp and Date before calling `toString`
11014 if (val instanceof RegExp) {
11015 return 'regexp';
11016 }
11017 if (val instanceof Date) {
11018 return 'date';
11019 }
11020
11021 // other objects
11022 var type = toString$4.call(val);
11023
11024 if (type === '[object RegExp]') {
11025 return 'regexp';
11026 }
11027 if (type === '[object Date]') {
11028 return 'date';
11029 }
11030 if (type === '[object Arguments]') {
11031 return 'arguments';
11032 }
11033 if (type === '[object Error]') {
11034 return 'error';
11035 }
11036 if (type === '[object Promise]') {
11037 return 'promise';
11038 }
11039
11040 // buffer
11041 if (index$24(val)) {
11042 return 'buffer';
11043 }
11044
11045 // es6: Map, WeakMap, Set, WeakSet
11046 if (type === '[object Set]') {
11047 return 'set';
11048 }
11049 if (type === '[object WeakSet]') {
11050 return 'weakset';
11051 }
11052 if (type === '[object Map]') {
11053 return 'map';
11054 }
11055 if (type === '[object WeakMap]') {
11056 return 'weakmap';
11057 }
11058 if (type === '[object Symbol]') {
11059 return 'symbol';
11060 }
11061
11062 // typed arrays
11063 if (type === '[object Int8Array]') {
11064 return 'int8array';
11065 }
11066 if (type === '[object Uint8Array]') {
11067 return 'uint8array';
11068 }
11069 if (type === '[object Uint8ClampedArray]') {
11070 return 'uint8clampedarray';
11071 }
11072 if (type === '[object Int16Array]') {
11073 return 'int16array';
11074 }
11075 if (type === '[object Uint16Array]') {
11076 return 'uint16array';
11077 }
11078 if (type === '[object Int32Array]') {
11079 return 'int32array';
11080 }
11081 if (type === '[object Uint32Array]') {
11082 return 'uint32array';
11083 }
11084 if (type === '[object Float32Array]') {
11085 return 'float32array';
11086 }
11087 if (type === '[object Float64Array]') {
11088 return 'float64array';
11089 }
11090
11091 // must be a plain object
11092 return 'object';
11093};
11094
11095/**
11096 * Expose `randomatic`
11097 */
11098
11099var index$26 = randomatic;
11100
11101/**
11102 * Available mask characters
11103 */
11104
11105var type = {
11106 lower: 'abcdefghijklmnopqrstuvwxyz',
11107 upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
11108 number: '0123456789',
11109 special: '~!@#$%^&()_+-={}[];\',.'
11110};
11111
11112type.all = type.lower + type.upper + type.number + type.special;
11113
11114/**
11115 * Generate random character sequences of a specified `length`,
11116 * based on the given `pattern`.
11117 *
11118 * @param {String} `pattern` The pattern to use for generating the random string.
11119 * @param {String} `length` The length of the string to generate.
11120 * @param {String} `options`
11121 * @return {String}
11122 * @api public
11123 */
11124
11125function randomatic(pattern, length, options) {
11126 if (typeof pattern === 'undefined') {
11127 throw new Error('randomatic expects a string or number.');
11128 }
11129
11130 var custom = false;
11131 if (arguments.length === 1) {
11132 if (typeof pattern === 'string') {
11133 length = pattern.length;
11134
11135 } else if (index$28(pattern)) {
11136 options = {}; length = pattern; pattern = '*';
11137 }
11138 }
11139
11140 if (index$32(length) === 'object' && length.hasOwnProperty('chars')) {
11141 options = length;
11142 pattern = options.chars;
11143 length = pattern.length;
11144 custom = true;
11145 }
11146
11147 var opts = options || {};
11148 var mask = '';
11149 var res = '';
11150
11151 // Characters to be used
11152 if (pattern.indexOf('?') !== -1) mask += opts.chars;
11153 if (pattern.indexOf('a') !== -1) mask += type.lower;
11154 if (pattern.indexOf('A') !== -1) mask += type.upper;
11155 if (pattern.indexOf('0') !== -1) mask += type.number;
11156 if (pattern.indexOf('!') !== -1) mask += type.special;
11157 if (pattern.indexOf('*') !== -1) mask += type.all;
11158 if (custom) mask += pattern;
11159
11160 while (length--) {
11161 res += mask.charAt(parseInt(Math.random() * mask.length, 10));
11162 }
11163 return res;
11164}
11165
11166/*!
11167 * repeat-string <https://github.com/jonschlinkert/repeat-string>
11168 *
11169 * Copyright (c) 2014-2015, Jon Schlinkert.
11170 * Licensed under the MIT License.
11171 */
11172
11173/**
11174 * Results cache
11175 */
11176
11177var res = '';
11178var cache;
11179
11180/**
11181 * Expose `repeat`
11182 */
11183
11184var index$34 = repeat;
11185
11186/**
11187 * Repeat the given `string` the specified `number`
11188 * of times.
11189 *
11190 * **Example:**
11191 *
11192 * ```js
11193 * var repeat = require('repeat-string');
11194 * repeat('A', 5);
11195 * //=> AAAAA
11196 * ```
11197 *
11198 * @param {String} `string` The string to repeat
11199 * @param {Number} `number` The number of times to repeat the string
11200 * @return {String} Repeated string
11201 * @api public
11202 */
11203
11204function repeat(str, num) {
11205 if (typeof str !== 'string') {
11206 throw new TypeError('expected a string');
11207 }
11208
11209 // cover common, quick use cases
11210 if (num === 1) return str;
11211 if (num === 2) return str + str;
11212
11213 var max = str.length * num;
11214 if (cache !== str || typeof cache === 'undefined') {
11215 cache = str;
11216 res = '';
11217 } else if (res.length >= max) {
11218 return res.substr(0, max);
11219 }
11220
11221 while (max > res.length && num > 1) {
11222 if (num & 1) {
11223 res += str;
11224 }
11225
11226 num >>= 1;
11227 str += str;
11228 }
11229
11230 res += str;
11231 res = res.substr(0, max);
11232 return res;
11233}
11234
11235/*!
11236 * repeat-element <https://github.com/jonschlinkert/repeat-element>
11237 *
11238 * Copyright (c) 2015 Jon Schlinkert.
11239 * Licensed under the MIT license.
11240 */
11241
11242var index$36 = function repeat(ele, num) {
11243 var arr = new Array(num);
11244
11245 for (var i = 0; i < num; i++) {
11246 arr[i] = ele;
11247 }
11248
11249 return arr;
11250};
11251
11252/**
11253 * Expose `fillRange`
11254 */
11255
11256var index$14 = fillRange;
11257
11258/**
11259 * Return a range of numbers or letters.
11260 *
11261 * @param {String} `a` Start of the range
11262 * @param {String} `b` End of the range
11263 * @param {String} `step` Increment or decrement to use.
11264 * @param {Function} `fn` Custom function to modify each element in the range.
11265 * @return {Array}
11266 */
11267
11268function fillRange(a, b, step, options, fn) {
11269 if (a == null || b == null) {
11270 throw new Error('fill-range expects the first and second args to be strings.');
11271 }
11272
11273 if (typeof step === 'function') {
11274 fn = step; options = {}; step = null;
11275 }
11276
11277 if (typeof options === 'function') {
11278 fn = options; options = {};
11279 }
11280
11281 if (index$16(step)) {
11282 options = step; step = '';
11283 }
11284
11285 var expand, regex = false, sep$$1 = '';
11286 var opts = options || {};
11287
11288 if (typeof opts.silent === 'undefined') {
11289 opts.silent = true;
11290 }
11291
11292 step = step || opts.step;
11293
11294 // store a ref to unmodified arg
11295 var origA = a, origB = b;
11296
11297 b = (b.toString() === '-0') ? 0 : b;
11298
11299 if (opts.optimize || opts.makeRe) {
11300 step = step ? (step += '~') : step;
11301 expand = true;
11302 regex = true;
11303 sep$$1 = '~';
11304 }
11305
11306 // handle special step characters
11307 if (typeof step === 'string') {
11308 var match = stepRe().exec(step);
11309
11310 if (match) {
11311 var i = match.index;
11312 var m = match[0];
11313
11314 // repeat string
11315 if (m === '+') {
11316 return index$36(a, b);
11317
11318 // randomize a, `b` times
11319 } else if (m === '?') {
11320 return [index$26(a, b)];
11321
11322 // expand right, no regex reduction
11323 } else if (m === '>') {
11324 step = step.substr(0, i) + step.substr(i + 1);
11325 expand = true;
11326
11327 // expand to an array, or if valid create a reduced
11328 // string for a regex logic `or`
11329 } else if (m === '|') {
11330 step = step.substr(0, i) + step.substr(i + 1);
11331 expand = true;
11332 regex = true;
11333 sep$$1 = m;
11334
11335 // expand to an array, or if valid create a reduced
11336 // string for a regex range
11337 } else if (m === '~') {
11338 step = step.substr(0, i) + step.substr(i + 1);
11339 expand = true;
11340 regex = true;
11341 sep$$1 = m;
11342 }
11343 } else if (!index$20(step)) {
11344 if (!opts.silent) {
11345 throw new TypeError('fill-range: invalid step.');
11346 }
11347 return null;
11348 }
11349 }
11350
11351 if (/[.&*()[\]^%$#@!]/.test(a) || /[.&*()[\]^%$#@!]/.test(b)) {
11352 if (!opts.silent) {
11353 throw new RangeError('fill-range: invalid range arguments.');
11354 }
11355 return null;
11356 }
11357
11358 // has neither a letter nor number, or has both letters and numbers
11359 // this needs to be after the step logic
11360 if (!noAlphaNum(a) || !noAlphaNum(b) || hasBoth(a) || hasBoth(b)) {
11361 if (!opts.silent) {
11362 throw new RangeError('fill-range: invalid range arguments.');
11363 }
11364 return null;
11365 }
11366
11367 // validate arguments
11368 var isNumA = index$20(zeros(a));
11369 var isNumB = index$20(zeros(b));
11370
11371 if ((!isNumA && isNumB) || (isNumA && !isNumB)) {
11372 if (!opts.silent) {
11373 throw new TypeError('fill-range: first range argument is incompatible with second.');
11374 }
11375 return null;
11376 }
11377
11378 // by this point both are the same, so we
11379 // can use A to check going forward.
11380 var isNum = isNumA;
11381 var num = formatStep(step);
11382
11383 // is the range alphabetical? or numeric?
11384 if (isNum) {
11385 // if numeric, coerce to an integer
11386 a = +a; b = +b;
11387 } else {
11388 // otherwise, get the charCode to expand alpha ranges
11389 a = a.charCodeAt(0);
11390 b = b.charCodeAt(0);
11391 }
11392
11393 // is the pattern descending?
11394 var isDescending = a > b;
11395
11396 // don't create a character class if the args are < 0
11397 if (a < 0 || b < 0) {
11398 expand = false;
11399 regex = false;
11400 }
11401
11402 // detect padding
11403 var padding = isPadded(origA, origB);
11404 var res, pad, arr = [];
11405 var ii = 0;
11406
11407 // character classes, ranges and logical `or`
11408 if (regex) {
11409 if (shouldExpand(a, b, num, isNum, padding, opts)) {
11410 // make sure the correct separator is used
11411 if (sep$$1 === '|' || sep$$1 === '~') {
11412 sep$$1 = detectSeparator(a, b, num, isNum, isDescending);
11413 }
11414 return wrap$1([origA, origB], sep$$1, opts);
11415 }
11416 }
11417
11418 while (isDescending ? (a >= b) : (a <= b)) {
11419 if (padding && isNum) {
11420 pad = padding(a);
11421 }
11422
11423 // custom function
11424 if (typeof fn === 'function') {
11425 res = fn(a, isNum, pad, ii++);
11426
11427 // letters
11428 } else if (!isNum) {
11429 if (regex && isInvalidChar(a)) {
11430 res = null;
11431 } else {
11432 res = String.fromCharCode(a);
11433 }
11434
11435 // numbers
11436 } else {
11437 res = formatPadding(a, pad);
11438 }
11439
11440 // add result to the array, filtering any nulled values
11441 if (res !== null) arr.push(res);
11442
11443 // increment or decrement
11444 if (isDescending) {
11445 a -= num;
11446 } else {
11447 a += num;
11448 }
11449 }
11450
11451 // now that the array is expanded, we need to handle regex
11452 // character classes, ranges or logical `or` that wasn't
11453 // already handled before the loop
11454 if ((regex || expand) && !opts.noexpand) {
11455 // make sure the correct separator is used
11456 if (sep$$1 === '|' || sep$$1 === '~') {
11457 sep$$1 = detectSeparator(a, b, num, isNum, isDescending);
11458 }
11459 if (arr.length === 1 || a < 0 || b < 0) { return arr; }
11460 return wrap$1(arr, sep$$1, opts);
11461 }
11462
11463 return arr;
11464}
11465
11466/**
11467 * Wrap the string with the correct regex
11468 * syntax.
11469 */
11470
11471function wrap$1(arr, sep$$1, opts) {
11472 if (sep$$1 === '~') { sep$$1 = '-'; }
11473 var str = arr.join(sep$$1);
11474 var pre = opts && opts.regexPrefix;
11475
11476 // regex logical `or`
11477 if (sep$$1 === '|') {
11478 str = pre ? pre + str : str;
11479 str = '(' + str + ')';
11480 }
11481
11482 // regex character class
11483 if (sep$$1 === '-') {
11484 str = (pre && pre === '^')
11485 ? pre + str
11486 : str;
11487 str = '[' + str + ']';
11488 }
11489 return [str];
11490}
11491
11492/**
11493 * Check for invalid characters
11494 */
11495
11496function isCharClass(a, b, step, isNum, isDescending) {
11497 if (isDescending) { return false; }
11498 if (isNum) { return a <= 9 && b <= 9; }
11499 if (a < b) { return step === 1; }
11500 return false;
11501}
11502
11503/**
11504 * Detect the correct separator to use
11505 */
11506
11507function shouldExpand(a, b, num, isNum, padding, opts) {
11508 if (isNum && (a > 9 || b > 9)) { return false; }
11509 return !padding && num === 1 && a < b;
11510}
11511
11512/**
11513 * Detect the correct separator to use
11514 */
11515
11516function detectSeparator(a, b, step, isNum, isDescending) {
11517 var isChar = isCharClass(a, b, step, isNum, isDescending);
11518 if (!isChar) {
11519 return '|';
11520 }
11521 return '~';
11522}
11523
11524/**
11525 * Correctly format the step based on type
11526 */
11527
11528function formatStep(step) {
11529 return Math.abs(step >> 0) || 1;
11530}
11531
11532/**
11533 * Format padding, taking leading `-` into account
11534 */
11535
11536function formatPadding(ch, pad) {
11537 var res = pad ? pad + ch : ch;
11538 if (pad && ch.toString().charAt(0) === '-') {
11539 res = '-' + pad + ch.toString().substr(1);
11540 }
11541 return res.toString();
11542}
11543
11544/**
11545 * Check for invalid characters
11546 */
11547
11548function isInvalidChar(str) {
11549 var ch = toStr(str);
11550 return ch === '\\'
11551 || ch === '['
11552 || ch === ']'
11553 || ch === '^'
11554 || ch === '('
11555 || ch === ')'
11556 || ch === '`';
11557}
11558
11559/**
11560 * Convert to a string from a charCode
11561 */
11562
11563function toStr(ch) {
11564 return String.fromCharCode(ch);
11565}
11566
11567
11568/**
11569 * Step regex
11570 */
11571
11572function stepRe() {
11573 return /\?|>|\||\+|\~/g;
11574}
11575
11576/**
11577 * Return true if `val` has either a letter
11578 * or a number
11579 */
11580
11581function noAlphaNum(val) {
11582 return /[a-z0-9]/i.test(val);
11583}
11584
11585/**
11586 * Return true if `val` has both a letter and
11587 * a number (invalid)
11588 */
11589
11590function hasBoth(val) {
11591 return /[a-z][0-9]|[0-9][a-z]/i.test(val);
11592}
11593
11594/**
11595 * Normalize zeros for checks
11596 */
11597
11598function zeros(val) {
11599 if (/^-*0+$/.test(val.toString())) {
11600 return '0';
11601 }
11602 return val;
11603}
11604
11605/**
11606 * Return true if `val` has leading zeros,
11607 * or a similar valid pattern.
11608 */
11609
11610function hasZeros(val) {
11611 return /[^.]\.|^-*0+[0-9]/.test(val);
11612}
11613
11614/**
11615 * If the string is padded, returns a curried function with
11616 * the a cached padding string, or `false` if no padding.
11617 *
11618 * @param {*} `origA` String or number.
11619 * @return {String|Boolean}
11620 */
11621
11622function isPadded(origA, origB) {
11623 if (hasZeros(origA) || hasZeros(origB)) {
11624 var alen = length(origA);
11625 var blen = length(origB);
11626
11627 var len = alen >= blen
11628 ? alen
11629 : blen;
11630
11631 return function (a) {
11632 return index$34('0', len - length(a));
11633 };
11634 }
11635 return false;
11636}
11637
11638/**
11639 * Get the string length of `val`
11640 */
11641
11642function length(val) {
11643 return val.toString().length;
11644}
11645
11646var index$12 = function expandRange(str, options, fn) {
11647 if (typeof str !== 'string') {
11648 throw new TypeError('expand-range expects a string.');
11649 }
11650
11651 if (typeof options === 'function') {
11652 fn = options;
11653 options = {};
11654 }
11655
11656 if (typeof options === 'boolean') {
11657 options = {};
11658 options.makeRe = true;
11659 }
11660
11661 // create arguments to pass to fill-range
11662 var opts = options || {};
11663 var args = str.split('..');
11664 var len = args.length;
11665 if (len > 3) { return str; }
11666
11667 // if only one argument, it can't expand so return it
11668 if (len === 1) { return args; }
11669
11670 // if `true`, tell fill-range to regexify the string
11671 if (typeof fn === 'boolean' && fn === true) {
11672 opts.makeRe = true;
11673 }
11674
11675 args.push(opts);
11676 return index$14.apply(null, args.concat(fn));
11677};
11678
11679/*!
11680 * preserve <https://github.com/jonschlinkert/preserve>
11681 *
11682 * Copyright (c) 2014-2015, Jon Schlinkert.
11683 * Licensed under the MIT license.
11684 */
11685
11686/**
11687 * Replace tokens in `str` with a temporary, heuristic placeholder.
11688 *
11689 * ```js
11690 * tokens.before('{a\\,b}');
11691 * //=> '{__ID1__}'
11692 * ```
11693 *
11694 * @param {String} `str`
11695 * @return {String} String with placeholders.
11696 * @api public
11697 */
11698
11699var before = function before(str, re) {
11700 return str.replace(re, function (match) {
11701 var id = randomize$1();
11702 cache$1[id] = match;
11703 return '__ID' + id + '__';
11704 });
11705};
11706
11707/**
11708 * Replace placeholders in `str` with original tokens.
11709 *
11710 * ```js
11711 * tokens.after('{__ID1__}');
11712 * //=> '{a\\,b}'
11713 * ```
11714 *
11715 * @param {String} `str` String with placeholders
11716 * @return {String} `str` String with original tokens.
11717 * @api public
11718 */
11719
11720var after = function after(str) {
11721 return str.replace(/__ID(.{5})__/g, function (_, id) {
11722 return cache$1[id];
11723 });
11724};
11725
11726function randomize$1() {
11727 return Math.random().toString().slice(2, 7);
11728}
11729
11730var cache$1 = {};
11731
11732var index$38 = {
11733 before: before,
11734 after: after
11735};
11736
11737/**
11738 * Module dependencies
11739 */
11740
11741
11742
11743
11744
11745/**
11746 * Expose `braces`
11747 */
11748
11749var index$10 = function(str, options) {
11750 if (typeof str !== 'string') {
11751 throw new Error('braces expects a string');
11752 }
11753 return braces(str, options);
11754};
11755
11756/**
11757 * Expand `{foo,bar}` or `{1..5}` braces in the
11758 * given `string`.
11759 *
11760 * @param {String} `str`
11761 * @param {Array} `arr`
11762 * @param {Object} `options`
11763 * @return {Array}
11764 */
11765
11766function braces(str, arr, options) {
11767 if (str === '') {
11768 return [];
11769 }
11770
11771 if (!Array.isArray(arr)) {
11772 options = arr;
11773 arr = [];
11774 }
11775
11776 var opts = options || {};
11777 arr = arr || [];
11778
11779 if (typeof opts.nodupes === 'undefined') {
11780 opts.nodupes = true;
11781 }
11782
11783 var fn = opts.fn;
11784 var es6;
11785
11786 if (typeof opts === 'function') {
11787 fn = opts;
11788 opts = {};
11789 }
11790
11791 if (!(patternRe instanceof RegExp)) {
11792 patternRe = patternRegex();
11793 }
11794
11795 var matches = str.match(patternRe) || [];
11796 var m = matches[0];
11797
11798 switch(m) {
11799 case '\\,':
11800 return escapeCommas(str, arr, opts);
11801 case '\\.':
11802 return escapeDots(str, arr, opts);
11803 case '\/.':
11804 return escapePaths(str, arr, opts);
11805 case ' ':
11806 return splitWhitespace(str);
11807 case '{,}':
11808 return exponential(str, opts, braces);
11809 case '{}':
11810 return emptyBraces(str, arr, opts);
11811 case '\\{':
11812 case '\\}':
11813 return escapeBraces(str, arr, opts);
11814 case '${':
11815 if (!/\{[^{]+\{/.test(str)) {
11816 return arr.concat(str);
11817 } else {
11818 es6 = true;
11819 str = index$38.before(str, es6Regex());
11820 }
11821 }
11822
11823 if (!(braceRe instanceof RegExp)) {
11824 braceRe = braceRegex();
11825 }
11826
11827 var match = braceRe.exec(str);
11828 if (match == null) {
11829 return [str];
11830 }
11831
11832 var outter = match[1];
11833 var inner = match[2];
11834 if (inner === '') { return [str]; }
11835
11836 var segs, segsLength;
11837
11838 if (inner.indexOf('..') !== -1) {
11839 segs = index$12(inner, opts, fn) || inner.split(',');
11840 segsLength = segs.length;
11841
11842 } else if (inner[0] === '"' || inner[0] === '\'') {
11843 return arr.concat(str.split(/['"]/).join(''));
11844
11845 } else {
11846 segs = inner.split(',');
11847 if (opts.makeRe) {
11848 return braces(str.replace(outter, wrap(segs, '|')), opts);
11849 }
11850
11851 segsLength = segs.length;
11852 if (segsLength === 1 && opts.bash) {
11853 segs[0] = wrap(segs[0], '\\');
11854 }
11855 }
11856
11857 var len = segs.length;
11858 var i = 0, val;
11859
11860 while (len--) {
11861 var path$$1 = segs[i++];
11862
11863 if (/(\.[^.\/])/.test(path$$1)) {
11864 if (segsLength > 1) {
11865 return segs;
11866 } else {
11867 return [str];
11868 }
11869 }
11870
11871 val = splice(str, outter, path$$1);
11872
11873 if (/\{[^{}]+?\}/.test(val)) {
11874 arr = braces(val, arr, opts);
11875 } else if (val !== '') {
11876 if (opts.nodupes && arr.indexOf(val) !== -1) { continue; }
11877 arr.push(es6 ? index$38.after(val) : val);
11878 }
11879 }
11880
11881 if (opts.strict) { return filter$1(arr, filterEmpty); }
11882 return arr;
11883}
11884
11885/**
11886 * Expand exponential ranges
11887 *
11888 * `a{,}{,}` => ['a', 'a', 'a', 'a']
11889 */
11890
11891function exponential(str, options, fn) {
11892 if (typeof options === 'function') {
11893 fn = options;
11894 options = null;
11895 }
11896
11897 var opts = options || {};
11898 var esc = '__ESC_EXP__';
11899 var exp = 0;
11900 var res;
11901
11902 var parts = str.split('{,}');
11903 if (opts.nodupes) {
11904 return fn(parts.join(''), opts);
11905 }
11906
11907 exp = parts.length - 1;
11908 res = fn(parts.join(esc), opts);
11909 var len = res.length;
11910 var arr = [];
11911 var i = 0;
11912
11913 while (len--) {
11914 var ele = res[i++];
11915 var idx = ele.indexOf(esc);
11916
11917 if (idx === -1) {
11918 arr.push(ele);
11919
11920 } else {
11921 ele = ele.split('__ESC_EXP__').join('');
11922 if (!!ele && opts.nodupes !== false) {
11923 arr.push(ele);
11924
11925 } else {
11926 var num = Math.pow(2, exp);
11927 arr.push.apply(arr, index$36(ele, num));
11928 }
11929 }
11930 }
11931 return arr;
11932}
11933
11934/**
11935 * Wrap a value with parens, brackets or braces,
11936 * based on the given character/separator.
11937 *
11938 * @param {String|Array} `val`
11939 * @param {String} `ch`
11940 * @return {String}
11941 */
11942
11943function wrap(val, ch) {
11944 if (ch === '|') {
11945 return '(' + val.join(ch) + ')';
11946 }
11947 if (ch === ',') {
11948 return '{' + val.join(ch) + '}';
11949 }
11950 if (ch === '-') {
11951 return '[' + val.join(ch) + ']';
11952 }
11953 if (ch === '\\') {
11954 return '\\{' + val + '\\}';
11955 }
11956}
11957
11958/**
11959 * Handle empty braces: `{}`
11960 */
11961
11962function emptyBraces(str, arr, opts) {
11963 return braces(str.split('{}').join('\\{\\}'), arr, opts);
11964}
11965
11966/**
11967 * Filter out empty-ish values
11968 */
11969
11970function filterEmpty(ele) {
11971 return !!ele && ele !== '\\';
11972}
11973
11974/**
11975 * Handle patterns with whitespace
11976 */
11977
11978function splitWhitespace(str) {
11979 var segs = str.split(' ');
11980 var len = segs.length;
11981 var res = [];
11982 var i = 0;
11983
11984 while (len--) {
11985 res.push.apply(res, braces(segs[i++]));
11986 }
11987 return res;
11988}
11989
11990/**
11991 * Handle escaped braces: `\\{foo,bar}`
11992 */
11993
11994function escapeBraces(str, arr, opts) {
11995 if (!/\{[^{]+\{/.test(str)) {
11996 return arr.concat(str.split('\\').join(''));
11997 } else {
11998 str = str.split('\\{').join('__LT_BRACE__');
11999 str = str.split('\\}').join('__RT_BRACE__');
12000 return map$1(braces(str, arr, opts), function(ele) {
12001 ele = ele.split('__LT_BRACE__').join('{');
12002 return ele.split('__RT_BRACE__').join('}');
12003 });
12004 }
12005}
12006
12007/**
12008 * Handle escaped dots: `{1\\.2}`
12009 */
12010
12011function escapeDots(str, arr, opts) {
12012 if (!/[^\\]\..+\\\./.test(str)) {
12013 return arr.concat(str.split('\\').join(''));
12014 } else {
12015 str = str.split('\\.').join('__ESC_DOT__');
12016 return map$1(braces(str, arr, opts), function(ele) {
12017 return ele.split('__ESC_DOT__').join('.');
12018 });
12019 }
12020}
12021
12022/**
12023 * Handle escaped dots: `{1\\.2}`
12024 */
12025
12026function escapePaths(str, arr, opts) {
12027 str = str.split('\/.').join('__ESC_PATH__');
12028 return map$1(braces(str, arr, opts), function(ele) {
12029 return ele.split('__ESC_PATH__').join('\/.');
12030 });
12031}
12032
12033/**
12034 * Handle escaped commas: `{a\\,b}`
12035 */
12036
12037function escapeCommas(str, arr, opts) {
12038 if (!/\w,/.test(str)) {
12039 return arr.concat(str.split('\\').join(''));
12040 } else {
12041 str = str.split('\\,').join('__ESC_COMMA__');
12042 return map$1(braces(str, arr, opts), function(ele) {
12043 return ele.split('__ESC_COMMA__').join(',');
12044 });
12045 }
12046}
12047
12048/**
12049 * Regex for common patterns
12050 */
12051
12052function patternRegex() {
12053 return /\${|( (?=[{,}])|(?=[{,}]) )|{}|{,}|\\,(?=.*[{}])|\/\.(?=.*[{}])|\\\.(?={)|\\{|\\}/;
12054}
12055
12056/**
12057 * Braces regex.
12058 */
12059
12060function braceRegex() {
12061 return /.*(\\?\{([^}]+)\})/;
12062}
12063
12064/**
12065 * es6 delimiter regex.
12066 */
12067
12068function es6Regex() {
12069 return /\$\{([^}]+)\}/;
12070}
12071
12072var braceRe;
12073var patternRe;
12074
12075/**
12076 * Faster alternative to `String.replace()` when the
12077 * index of the token to be replaces can't be supplied
12078 */
12079
12080function splice(str, token, replacement) {
12081 var i = str.indexOf(token);
12082 return str.substr(0, i) + replacement
12083 + str.substr(i + token.length);
12084}
12085
12086/**
12087 * Fast array map
12088 */
12089
12090function map$1(arr, fn) {
12091 if (arr == null) {
12092 return [];
12093 }
12094
12095 var len = arr.length;
12096 var res = new Array(len);
12097 var i = -1;
12098
12099 while (++i < len) {
12100 res[i] = fn(arr[i], i, arr);
12101 }
12102
12103 return res;
12104}
12105
12106/**
12107 * Fast array filter
12108 */
12109
12110function filter$1(arr, cb) {
12111 if (arr == null) return [];
12112 if (typeof cb !== 'function') {
12113 throw new TypeError('braces: filter expects a callback function.');
12114 }
12115
12116 var len = arr.length;
12117 var res = arr.slice();
12118 var i = 0;
12119
12120 while (len--) {
12121 if (!cb(arr[len], i++)) {
12122 res.splice(len, 1);
12123 }
12124 }
12125 return res;
12126}
12127
12128/*!
12129 * is-posix-bracket <https://github.com/jonschlinkert/is-posix-bracket>
12130 *
12131 * Copyright (c) 2015-2016, Jon Schlinkert.
12132 * Licensed under the MIT License.
12133 */
12134
12135var index$42 = function isPosixBracket(str) {
12136 return typeof str === 'string' && /\[([:.=+])(?:[^\[\]]|)+\1\]/.test(str);
12137};
12138
12139/**
12140 * POSIX character classes
12141 */
12142
12143var POSIX = {
12144 alnum: 'a-zA-Z0-9',
12145 alpha: 'a-zA-Z',
12146 blank: ' \\t',
12147 cntrl: '\\x00-\\x1F\\x7F',
12148 digit: '0-9',
12149 graph: '\\x21-\\x7E',
12150 lower: 'a-z',
12151 print: '\\x20-\\x7E',
12152 punct: '-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
12153 space: ' \\t\\r\\n\\v\\f',
12154 upper: 'A-Z',
12155 word: 'A-Za-z0-9_',
12156 xdigit: 'A-Fa-f0-9',
12157};
12158
12159/**
12160 * Expose `brackets`
12161 */
12162
12163var index$40 = brackets;
12164
12165function brackets(str) {
12166 if (!index$42(str)) {
12167 return str;
12168 }
12169
12170 var negated = false;
12171 if (str.indexOf('[^') !== -1) {
12172 negated = true;
12173 str = str.split('[^').join('[');
12174 }
12175 if (str.indexOf('[!') !== -1) {
12176 negated = true;
12177 str = str.split('[!').join('[');
12178 }
12179
12180 var a = str.split('[');
12181 var b = str.split(']');
12182 var imbalanced = a.length !== b.length;
12183
12184 var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/);
12185 var len = parts.length, i = 0;
12186 var end = '', beg = '';
12187 var res = [];
12188
12189 // start at the end (innermost) first
12190 while (len--) {
12191 var inner = parts[i++];
12192 if (inner === '^[!' || inner === '[!') {
12193 inner = '';
12194 negated = true;
12195 }
12196
12197 var prefix = negated ? '^' : '';
12198 var ch = POSIX[inner];
12199
12200 if (ch) {
12201 res.push('[' + prefix + ch + ']');
12202 } else if (inner) {
12203 if (/^\[?\w-\w\]?$/.test(inner)) {
12204 if (i === parts.length) {
12205 res.push('[' + prefix + inner);
12206 } else if (i === 1) {
12207 res.push(prefix + inner + ']');
12208 } else {
12209 res.push(prefix + inner);
12210 }
12211 } else {
12212 if (i === 1) {
12213 beg += inner;
12214 } else if (i === parts.length) {
12215 end += inner;
12216 } else {
12217 res.push('[' + prefix + inner + ']');
12218 }
12219 }
12220 }
12221 }
12222
12223 var result = res.join('|');
12224 var rlen = res.length || 1;
12225 if (rlen > 1) {
12226 result = '(?:' + result + ')';
12227 rlen = 1;
12228 }
12229 if (beg) {
12230 rlen++;
12231 if (beg.charAt(0) === '[') {
12232 if (imbalanced) {
12233 beg = '\\[' + beg.slice(1);
12234 } else {
12235 beg += ']';
12236 }
12237 }
12238 result = beg + result;
12239 }
12240 if (end) {
12241 rlen++;
12242 if (end.slice(-1) === ']') {
12243 if (imbalanced) {
12244 end = end.slice(0, end.length - 1) + '\\]';
12245 } else {
12246 end = '[' + end;
12247 }
12248 }
12249 result += end;
12250 }
12251
12252 if (rlen > 1) {
12253 result = result.split('][').join(']|[');
12254 if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) {
12255 result = '(?:' + result + ')';
12256 }
12257 }
12258
12259 result = result.replace(/\[+=|=\]+/g, '\\b');
12260 return result;
12261}
12262
12263brackets.makeRe = function(pattern) {
12264 try {
12265 return new RegExp(brackets(pattern));
12266 } catch (err) {}
12267};
12268
12269brackets.isMatch = function(str, pattern) {
12270 try {
12271 return brackets.makeRe(pattern).test(str);
12272 } catch (err) {
12273 return false;
12274 }
12275};
12276
12277brackets.match = function(arr, pattern) {
12278 var len = arr.length, i = 0;
12279 var res = arr.slice();
12280
12281 var re = brackets.makeRe(pattern);
12282 while (i < len) {
12283 var ele = arr[i++];
12284 if (!re.test(ele)) {
12285 continue;
12286 }
12287 res.splice(i, 1);
12288 }
12289 return res;
12290};
12291
12292/*!
12293 * is-extglob <https://github.com/jonschlinkert/is-extglob>
12294 *
12295 * Copyright (c) 2014-2015, Jon Schlinkert.
12296 * Licensed under the MIT License.
12297 */
12298
12299var index$46 = function isExtglob(str) {
12300 return typeof str === 'string'
12301 && /[@?!+*]\(/.test(str);
12302};
12303
12304/**
12305 * Module dependencies
12306 */
12307
12308
12309var re;
12310var cache$2 = {};
12311
12312/**
12313 * Expose `extglob`
12314 */
12315
12316var index$44 = extglob;
12317
12318/**
12319 * Convert the given extglob `string` to a regex-compatible
12320 * string.
12321 *
12322 * ```js
12323 * var extglob = require('extglob');
12324 * extglob('!(a?(b))');
12325 * //=> '(?!a(?:b)?)[^/]*?'
12326 * ```
12327 *
12328 * @param {String} `str` The string to convert.
12329 * @param {Object} `options`
12330 * @option {Boolean} [options] `esc` If `false` special characters will not be escaped. Defaults to `true`.
12331 * @option {Boolean} [options] `regex` If `true` a regular expression is returned instead of a string.
12332 * @return {String}
12333 * @api public
12334 */
12335
12336
12337function extglob(str, opts) {
12338 opts = opts || {};
12339 var o = {}, i = 0;
12340
12341 // fix common character reversals
12342 // '*!(.js)' => '*.!(js)'
12343 str = str.replace(/!\(([^\w*()])/g, '$1!(');
12344
12345 // support file extension negation
12346 str = str.replace(/([*\/])\.!\([*]\)/g, function (m, ch) {
12347 if (ch === '/') {
12348 return escape('\\/[^.]+');
12349 }
12350 return escape('[^.]+');
12351 });
12352
12353 // create a unique key for caching by
12354 // combining the string and options
12355 var key = str
12356 + String(!!opts.regex)
12357 + String(!!opts.contains)
12358 + String(!!opts.escape);
12359
12360 if (cache$2.hasOwnProperty(key)) {
12361 return cache$2[key];
12362 }
12363
12364 if (!(re instanceof RegExp)) {
12365 re = regex();
12366 }
12367
12368 opts.negate = false;
12369 var m;
12370
12371 while (m = re.exec(str)) {
12372 var prefix = m[1];
12373 var inner = m[3];
12374 if (prefix === '!') {
12375 opts.negate = true;
12376 }
12377
12378 var id = '__EXTGLOB_' + (i++) + '__';
12379 // use the prefix of the _last_ (outtermost) pattern
12380 o[id] = wrap$2(inner, prefix, opts.escape);
12381 str = str.split(m[0]).join(id);
12382 }
12383
12384 var keys = Object.keys(o);
12385 var len = keys.length;
12386
12387 // we have to loop again to allow us to convert
12388 // patterns in reverse order (starting with the
12389 // innermost/last pattern first)
12390 while (len--) {
12391 var prop = keys[len];
12392 str = str.split(prop).join(o[prop]);
12393 }
12394
12395 var result = opts.regex
12396 ? toRegex$1(str, opts.contains, opts.negate)
12397 : str;
12398
12399 result = result.split('.').join('\\.');
12400
12401 // cache the result and return it
12402 return (cache$2[key] = result);
12403}
12404
12405/**
12406 * Convert `string` to a regex string.
12407 *
12408 * @param {String} `str`
12409 * @param {String} `prefix` Character that determines how to wrap the string.
12410 * @param {Boolean} `esc` If `false` special characters will not be escaped. Defaults to `true`.
12411 * @return {String}
12412 */
12413
12414function wrap$2(inner, prefix, esc) {
12415 if (esc) inner = escape(inner);
12416
12417 switch (prefix) {
12418 case '!':
12419 return '(?!' + inner + ')[^/]' + (esc ? '%%%~' : '*?');
12420 case '@':
12421 return '(?:' + inner + ')';
12422 case '+':
12423 return '(?:' + inner + ')+';
12424 case '*':
12425 return '(?:' + inner + ')' + (esc ? '%%' : '*')
12426 case '?':
12427 return '(?:' + inner + '|)';
12428 default:
12429 return inner;
12430 }
12431}
12432
12433function escape(str) {
12434 str = str.split('*').join('[^/]%%%~');
12435 str = str.split('.').join('\\.');
12436 return str;
12437}
12438
12439/**
12440 * extglob regex.
12441 */
12442
12443function regex() {
12444 return /(\\?[@?!+*$]\\?)(\(([^()]*?)\))/;
12445}
12446
12447/**
12448 * Negation regex
12449 */
12450
12451function negate(str) {
12452 return '(?!^' + str + ').*$';
12453}
12454
12455/**
12456 * Create the regex to do the matching. If
12457 * the leading character in the `pattern` is `!`
12458 * a negation regex is returned.
12459 *
12460 * @param {String} `pattern`
12461 * @param {Boolean} `contains` Allow loose matching.
12462 * @param {Boolean} `isNegated` True if the pattern is a negation pattern.
12463 */
12464
12465function toRegex$1(pattern, contains, isNegated) {
12466 var prefix = contains ? '^' : '';
12467 var after = contains ? '$' : '';
12468 pattern = ('(?:' + pattern + ')' + after);
12469 if (isNegated) {
12470 pattern = prefix + negate(pattern);
12471 }
12472 return new RegExp(prefix + pattern);
12473}
12474
12475/*!
12476 * is-glob <https://github.com/jonschlinkert/is-glob>
12477 *
12478 * Copyright (c) 2014-2015, Jon Schlinkert.
12479 * Licensed under the MIT License.
12480 */
12481
12482
12483
12484var index$48 = function isGlob(str) {
12485 return typeof str === 'string'
12486 && (/[*!?{}(|)[\]]/.test(str)
12487 || index$46(str));
12488};
12489
12490var isWin = process.platform === 'win32';
12491
12492var index$52 = function (str) {
12493 while (endsInSeparator(str)) {
12494 str = str.slice(0, -1);
12495 }
12496 return str;
12497};
12498
12499function endsInSeparator(str) {
12500 var last = str[str.length - 1];
12501 return str.length > 1 && (last === '/' || (isWin && last === '\\'));
12502}
12503
12504/*!
12505 * normalize-path <https://github.com/jonschlinkert/normalize-path>
12506 *
12507 * Copyright (c) 2014-2017, Jon Schlinkert.
12508 * Released under the MIT License.
12509 */
12510
12511
12512
12513var index$50 = function normalizePath(str, stripTrailing) {
12514 if (typeof str !== 'string') {
12515 throw new TypeError('expected a string');
12516 }
12517 str = str.replace(/[\\\/]+/g, '/');
12518 if (stripTrailing !== false) {
12519 str = index$52(str);
12520 }
12521 return str;
12522};
12523
12524/*!
12525 * is-extendable <https://github.com/jonschlinkert/is-extendable>
12526 *
12527 * Copyright (c) 2015, Jon Schlinkert.
12528 * Licensed under the MIT License.
12529 */
12530
12531var index$56 = function isExtendable(val) {
12532 return typeof val !== 'undefined' && val !== null
12533 && (typeof val === 'object' || typeof val === 'function');
12534};
12535
12536/*!
12537 * for-in <https://github.com/jonschlinkert/for-in>
12538 *
12539 * Copyright (c) 2014-2017, Jon Schlinkert.
12540 * Released under the MIT License.
12541 */
12542
12543var index$60 = function forIn(obj, fn, thisArg) {
12544 for (var key in obj) {
12545 if (fn.call(thisArg, obj[key], key, obj) === false) {
12546 break;
12547 }
12548 }
12549};
12550
12551var hasOwn = Object.prototype.hasOwnProperty;
12552
12553var index$58 = function forOwn(obj, fn, thisArg) {
12554 index$60(obj, function(val, key) {
12555 if (hasOwn.call(obj, key)) {
12556 return fn.call(thisArg, obj[key], key, obj);
12557 }
12558 });
12559};
12560
12561var index$54 = function omit(obj, keys) {
12562 if (!index$56(obj)) return {};
12563
12564 keys = [].concat.apply([], [].slice.call(arguments, 1));
12565 var last = keys[keys.length - 1];
12566 var res = {}, fn;
12567
12568 if (typeof last === 'function') {
12569 fn = keys.pop();
12570 }
12571
12572 var isFunction = typeof fn === 'function';
12573 if (!keys.length && !isFunction) {
12574 return obj;
12575 }
12576
12577 index$58(obj, function(value, key) {
12578 if (keys.indexOf(key) === -1) {
12579
12580 if (!isFunction) {
12581 res[key] = value;
12582 } else if (fn(value, key, obj)) {
12583 res[key] = value;
12584 }
12585 }
12586 });
12587 return res;
12588};
12589
12590var index$66 = function globParent(str) {
12591 str += 'a'; // preserves full path in case of trailing path separator
12592 do {str = path__default.dirname(str);} while (index$48(str));
12593 return str;
12594};
12595
12596var index$64 = function globBase(pattern) {
12597 if (typeof pattern !== 'string') {
12598 throw new TypeError('glob-base expects a string.');
12599 }
12600
12601 var res = {};
12602 res.base = index$66(pattern);
12603 res.isGlob = index$48(pattern);
12604
12605 if (res.base !== '.') {
12606 res.glob = pattern.substr(res.base.length);
12607 if (res.glob.charAt(0) === '/') {
12608 res.glob = res.glob.substr(1);
12609 }
12610 } else {
12611 res.glob = pattern;
12612 }
12613
12614 if (!res.isGlob) {
12615 res.base = dirname$1(pattern);
12616 res.glob = res.base !== '.'
12617 ? pattern.substr(res.base.length)
12618 : pattern;
12619 }
12620
12621 if (res.glob.substr(0, 2) === './') {
12622 res.glob = res.glob.substr(2);
12623 }
12624 if (res.glob.charAt(0) === '/') {
12625 res.glob = res.glob.substr(1);
12626 }
12627 return res;
12628};
12629
12630function dirname$1(glob) {
12631 if (glob.slice(-1) === '/') return glob;
12632 return path__default.dirname(glob);
12633}
12634
12635/*!
12636 * is-dotfile <https://github.com/jonschlinkert/is-dotfile>
12637 *
12638 * Copyright (c) 2015-2017, Jon Schlinkert.
12639 * Released under the MIT License.
12640 */
12641
12642var index$68 = function(str) {
12643 if (str.charCodeAt(0) === 46 /* . */ && str.indexOf('/', 1) === -1) {
12644 return true;
12645 }
12646 var slash = str.lastIndexOf('/');
12647 return slash !== -1 ? str.charCodeAt(slash + 1) === 46 /* . */ : false;
12648};
12649
12650var index$62 = createCommonjsModule(function (module) {
12651/*!
12652 * parse-glob <https://github.com/jonschlinkert/parse-glob>
12653 *
12654 * Copyright (c) 2015, Jon Schlinkert.
12655 * Licensed under the MIT License.
12656 */
12657
12658'use strict';
12659
12660
12661
12662
12663
12664
12665/**
12666 * Expose `cache`
12667 */
12668
12669var cache = module.exports.cache = {};
12670
12671/**
12672 * Parse a glob pattern into tokens.
12673 *
12674 * When no paths or '**' are in the glob, we use a
12675 * different strategy for parsing the filename, since
12676 * file names can contain braces and other difficult
12677 * patterns. such as:
12678 *
12679 * - `*.{a,b}`
12680 * - `(**|*.js)`
12681 */
12682
12683module.exports = function parseGlob(glob) {
12684 if (cache.hasOwnProperty(glob)) {
12685 return cache[glob];
12686 }
12687
12688 var tok = {};
12689 tok.orig = glob;
12690 tok.is = {};
12691
12692 // unescape dots and slashes in braces/brackets
12693 glob = escape(glob);
12694
12695 var parsed = index$64(glob);
12696 tok.is.glob = parsed.isGlob;
12697
12698 tok.glob = parsed.glob;
12699 tok.base = parsed.base;
12700 var segs = /([^\/]*)$/.exec(glob);
12701
12702 tok.path = {};
12703 tok.path.dirname = '';
12704 tok.path.basename = segs[1] || '';
12705 tok.path.dirname = glob.split(tok.path.basename).join('') || '';
12706 var basename$$1 = (tok.path.basename || '').split('.') || '';
12707 tok.path.filename = basename$$1[0] || '';
12708 tok.path.extname = basename$$1.slice(1).join('.') || '';
12709 tok.path.ext = '';
12710
12711 if (index$48(tok.path.dirname) && !tok.path.basename) {
12712 if (!/\/$/.test(tok.glob)) {
12713 tok.path.basename = tok.glob;
12714 }
12715 tok.path.dirname = tok.base;
12716 }
12717
12718 if (glob.indexOf('/') === -1 && !tok.is.globstar) {
12719 tok.path.dirname = '';
12720 tok.path.basename = tok.orig;
12721 }
12722
12723 var dot = tok.path.basename.indexOf('.');
12724 if (dot !== -1) {
12725 tok.path.filename = tok.path.basename.slice(0, dot);
12726 tok.path.extname = tok.path.basename.slice(dot);
12727 }
12728
12729 if (tok.path.extname.charAt(0) === '.') {
12730 var exts = tok.path.extname.split('.');
12731 tok.path.ext = exts[exts.length - 1];
12732 }
12733
12734 // unescape dots and slashes in braces/brackets
12735 tok.glob = unescape(tok.glob);
12736 tok.path.dirname = unescape(tok.path.dirname);
12737 tok.path.basename = unescape(tok.path.basename);
12738 tok.path.filename = unescape(tok.path.filename);
12739 tok.path.extname = unescape(tok.path.extname);
12740
12741 // Booleans
12742 var is = (glob && tok.is.glob);
12743 tok.is.negated = glob && glob.charAt(0) === '!';
12744 tok.is.extglob = glob && index$46(glob);
12745 tok.is.braces = has(is, glob, '{');
12746 tok.is.brackets = has(is, glob, '[:');
12747 tok.is.globstar = has(is, glob, '**');
12748 tok.is.dotfile = index$68(tok.path.basename) || index$68(tok.path.filename);
12749 tok.is.dotdir = dotdir(tok.path.dirname);
12750 return (cache[glob] = tok);
12751};
12752
12753/**
12754 * Returns true if the glob matches dot-directories.
12755 *
12756 * @param {Object} `tok` The tokens object
12757 * @param {Object} `path` The path object
12758 * @return {Object}
12759 */
12760
12761function dotdir(base) {
12762 if (base.indexOf('/.') !== -1) {
12763 return true;
12764 }
12765 if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
12766 return true;
12767 }
12768 return false;
12769}
12770
12771/**
12772 * Returns true if the pattern has the given `ch`aracter(s)
12773 *
12774 * @param {Object} `glob` The glob pattern.
12775 * @param {Object} `ch` The character to test for
12776 * @return {Object}
12777 */
12778
12779function has(is, glob, ch) {
12780 return is && glob.indexOf(ch) !== -1;
12781}
12782
12783/**
12784 * Escape/unescape utils
12785 */
12786
12787function escape(str) {
12788 var re = /\{([^{}]*?)}|\(([^()]*?)\)|\[([^\[\]]*?)\]/g;
12789 return str.replace(re, function (outter, braces, parens, brackets) {
12790 var inner = braces || parens || brackets;
12791 if (!inner) { return outter; }
12792 return outter.split(inner).join(esc(inner));
12793 });
12794}
12795
12796function esc(str) {
12797 str = str.split('/').join('__SLASH__');
12798 str = str.split('.').join('__DOT__');
12799 return str;
12800}
12801
12802function unescape(str) {
12803 str = str.split('__SLASH__').join('/');
12804 str = str.split('__DOT__').join('.');
12805 return str;
12806}
12807});
12808
12809/*!
12810 * is-primitive <https://github.com/jonschlinkert/is-primitive>
12811 *
12812 * Copyright (c) 2014-2015, Jon Schlinkert.
12813 * Licensed under the MIT License.
12814 */
12815
12816// see http://jsperf.com/testing-value-is-primitive/7
12817var index$72 = function isPrimitive(value) {
12818 return value == null || (typeof value !== 'function' && typeof value !== 'object');
12819};
12820
12821var index$74 = function isEqual(a, b) {
12822 if (!a && !b) { return true; }
12823 if (!a && b || a && !b) { return false; }
12824
12825 var numKeysA = 0, numKeysB = 0, key;
12826 for (key in b) {
12827 numKeysB++;
12828 if (!index$72(b[key]) || !a.hasOwnProperty(key) || (a[key] !== b[key])) {
12829 return false;
12830 }
12831 }
12832 for (key in a) {
12833 numKeysA++;
12834 }
12835 return numKeysA === numKeysB;
12836};
12837
12838var basic = {};
12839var cache$3 = {};
12840
12841/**
12842 * Expose `regexCache`
12843 */
12844
12845var index$70 = regexCache;
12846
12847/**
12848 * Memoize the results of a call to the new RegExp constructor.
12849 *
12850 * @param {Function} fn [description]
12851 * @param {String} str [description]
12852 * @param {Options} options [description]
12853 * @param {Boolean} nocompare [description]
12854 * @return {RegExp}
12855 */
12856
12857function regexCache(fn, str, opts) {
12858 var key = '_default_', regex, cached;
12859
12860 if (!str && !opts) {
12861 if (typeof fn !== 'function') {
12862 return fn;
12863 }
12864 return basic[key] || (basic[key] = fn(str));
12865 }
12866
12867 var isString = typeof str === 'string';
12868 if (isString) {
12869 if (!opts) {
12870 return basic[str] || (basic[str] = fn(str));
12871 }
12872 key = str;
12873 } else {
12874 opts = str;
12875 }
12876
12877 cached = cache$3[key];
12878 if (cached && index$74(cached.opts, opts)) {
12879 return cached.regex;
12880 }
12881
12882 memo(key, opts, (regex = fn(str, opts)));
12883 return regex;
12884}
12885
12886function memo(key, opts, regex) {
12887 cache$3[key] = {regex: regex, opts: opts};
12888}
12889
12890/**
12891 * Expose `cache`
12892 */
12893
12894var cache_1 = cache$3;
12895var basic_1 = basic;
12896
12897index$70.cache = cache_1;
12898index$70.basic = basic_1;
12899
12900var utils_1 = createCommonjsModule(function (module) {
12901'use strict';
12902
12903var win32 = process && process.platform === 'win32';
12904
12905
12906var utils = module.exports;
12907
12908/**
12909 * Module dependencies
12910 */
12911
12912utils.diff = index$4;
12913utils.unique = index$8;
12914utils.braces = index$10;
12915utils.brackets = index$40;
12916utils.extglob = index$44;
12917utils.isExtglob = index$46;
12918utils.isGlob = index$48;
12919utils.typeOf = index$22;
12920utils.normalize = index$50;
12921utils.omit = index$54;
12922utils.parseGlob = index$62;
12923utils.cache = index$70;
12924
12925/**
12926 * Get the filename of a filepath
12927 *
12928 * @param {String} `string`
12929 * @return {String}
12930 */
12931
12932utils.filename = function filename(fp) {
12933 var seg = fp.match(index$2());
12934 return seg && seg[0];
12935};
12936
12937/**
12938 * Returns a function that returns true if the given
12939 * pattern is the same as a given `filepath`
12940 *
12941 * @param {String} `pattern`
12942 * @return {Function}
12943 */
12944
12945utils.isPath = function isPath(pattern, opts) {
12946 opts = opts || {};
12947 return function(fp) {
12948 var unixified = utils.unixify(fp, opts);
12949 if(opts.nocase){
12950 return pattern.toLowerCase() === unixified.toLowerCase();
12951 }
12952 return pattern === unixified;
12953 };
12954};
12955
12956/**
12957 * Returns a function that returns true if the given
12958 * pattern contains a `filepath`
12959 *
12960 * @param {String} `pattern`
12961 * @return {Function}
12962 */
12963
12964utils.hasPath = function hasPath(pattern, opts) {
12965 return function(fp) {
12966 return utils.unixify(pattern, opts).indexOf(fp) !== -1;
12967 };
12968};
12969
12970/**
12971 * Returns a function that returns true if the given
12972 * pattern matches or contains a `filepath`
12973 *
12974 * @param {String} `pattern`
12975 * @return {Function}
12976 */
12977
12978utils.matchPath = function matchPath(pattern, opts) {
12979 var fn = (opts && opts.contains)
12980 ? utils.hasPath(pattern, opts)
12981 : utils.isPath(pattern, opts);
12982 return fn;
12983};
12984
12985/**
12986 * Returns a function that returns true if the given
12987 * regex matches the `filename` of a file path.
12988 *
12989 * @param {RegExp} `re`
12990 * @return {Boolean}
12991 */
12992
12993utils.hasFilename = function hasFilename(re) {
12994 return function(fp) {
12995 var name = utils.filename(fp);
12996 return name && re.test(name);
12997 };
12998};
12999
13000/**
13001 * Coerce `val` to an array
13002 *
13003 * @param {*} val
13004 * @return {Array}
13005 */
13006
13007utils.arrayify = function arrayify(val) {
13008 return !Array.isArray(val)
13009 ? [val]
13010 : val;
13011};
13012
13013/**
13014 * Normalize all slashes in a file path or glob pattern to
13015 * forward slashes.
13016 */
13017
13018utils.unixify = function unixify(fp, opts) {
13019 if (opts && opts.unixify === false) return fp;
13020 if (opts && opts.unixify === true || win32 || path__default.sep === '\\') {
13021 return utils.normalize(fp, false);
13022 }
13023 if (opts && opts.unescape === true) {
13024 return fp ? fp.toString().replace(/\\(\w)/g, '$1') : '';
13025 }
13026 return fp;
13027};
13028
13029/**
13030 * Escape/unescape utils
13031 */
13032
13033utils.escapePath = function escapePath(fp) {
13034 return fp.replace(/[\\.]/g, '\\$&');
13035};
13036
13037utils.unescapeGlob = function unescapeGlob(fp) {
13038 return fp.replace(/[\\"']/g, '');
13039};
13040
13041utils.escapeRe = function escapeRe(str) {
13042 return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&');
13043};
13044
13045/**
13046 * Expose `utils`
13047 */
13048
13049module.exports = utils;
13050});
13051
13052var chars = {};
13053var unesc;
13054var temp;
13055
13056function reverse(object, prepender) {
13057 return Object.keys(object).reduce(function(reversed, key) {
13058 var newKey = prepender ? prepender + key : key; // Optionally prepend a string to key.
13059 reversed[object[key]] = newKey; // Swap key and value.
13060 return reversed; // Return the result.
13061 }, {});
13062}
13063
13064/**
13065 * Regex for common characters
13066 */
13067
13068chars.escapeRegex = {
13069 '?': /\?/g,
13070 '@': /\@/g,
13071 '!': /\!/g,
13072 '+': /\+/g,
13073 '*': /\*/g,
13074 '(': /\(/g,
13075 ')': /\)/g,
13076 '[': /\[/g,
13077 ']': /\]/g
13078};
13079
13080/**
13081 * Escape characters
13082 */
13083
13084chars.ESC = {
13085 '?': '__UNESC_QMRK__',
13086 '@': '__UNESC_AMPE__',
13087 '!': '__UNESC_EXCL__',
13088 '+': '__UNESC_PLUS__',
13089 '*': '__UNESC_STAR__',
13090 ',': '__UNESC_COMMA__',
13091 '(': '__UNESC_LTPAREN__',
13092 ')': '__UNESC_RTPAREN__',
13093 '[': '__UNESC_LTBRACK__',
13094 ']': '__UNESC_RTBRACK__'
13095};
13096
13097/**
13098 * Unescape characters
13099 */
13100
13101chars.UNESC = unesc || (unesc = reverse(chars.ESC, '\\'));
13102
13103chars.ESC_TEMP = {
13104 '?': '__TEMP_QMRK__',
13105 '@': '__TEMP_AMPE__',
13106 '!': '__TEMP_EXCL__',
13107 '*': '__TEMP_STAR__',
13108 '+': '__TEMP_PLUS__',
13109 ',': '__TEMP_COMMA__',
13110 '(': '__TEMP_LTPAREN__',
13111 ')': '__TEMP_RTPAREN__',
13112 '[': '__TEMP_LTBRACK__',
13113 ']': '__TEMP_RTBRACK__'
13114};
13115
13116chars.TEMP = temp || (temp = reverse(chars.ESC_TEMP));
13117
13118var chars_1 = chars;
13119
13120var glob = createCommonjsModule(function (module) {
13121'use strict';
13122
13123
13124
13125
13126/**
13127 * Expose `Glob`
13128 */
13129
13130var Glob = module.exports = function Glob(pattern, options) {
13131 if (!(this instanceof Glob)) {
13132 return new Glob(pattern, options);
13133 }
13134 this.options = options || {};
13135 this.pattern = pattern;
13136 this.history = [];
13137 this.tokens = {};
13138 this.init(pattern);
13139};
13140
13141/**
13142 * Initialize defaults
13143 */
13144
13145Glob.prototype.init = function(pattern) {
13146 this.orig = pattern;
13147 this.negated = this.isNegated();
13148 this.options.track = this.options.track || false;
13149 this.options.makeRe = true;
13150};
13151
13152/**
13153 * Push a change into `glob.history`. Useful
13154 * for debugging.
13155 */
13156
13157Glob.prototype.track = function(msg) {
13158 if (this.options.track) {
13159 this.history.push({msg: msg, pattern: this.pattern});
13160 }
13161};
13162
13163/**
13164 * Return true if `glob.pattern` was negated
13165 * with `!`, also remove the `!` from the pattern.
13166 *
13167 * @return {Boolean}
13168 */
13169
13170Glob.prototype.isNegated = function() {
13171 if (this.pattern.charCodeAt(0) === 33 /* '!' */) {
13172 this.pattern = this.pattern.slice(1);
13173 return true;
13174 }
13175 return false;
13176};
13177
13178/**
13179 * Expand braces in the given glob pattern.
13180 *
13181 * We only need to use the [braces] lib when
13182 * patterns are nested.
13183 */
13184
13185Glob.prototype.braces = function() {
13186 if (this.options.nobraces !== true && this.options.nobrace !== true) {
13187 // naive/fast check for imbalanced characters
13188 var a = this.pattern.match(/[\{\(\[]/g);
13189 var b = this.pattern.match(/[\}\)\]]/g);
13190
13191 // if imbalanced, don't optimize the pattern
13192 if (a && b && (a.length !== b.length)) {
13193 this.options.makeRe = false;
13194 }
13195
13196 // expand brace patterns and join the resulting array
13197 var expanded = utils_1.braces(this.pattern, this.options);
13198 this.pattern = expanded.join('|');
13199 }
13200};
13201
13202/**
13203 * Expand bracket expressions in `glob.pattern`
13204 */
13205
13206Glob.prototype.brackets = function() {
13207 if (this.options.nobrackets !== true) {
13208 this.pattern = utils_1.brackets(this.pattern);
13209 }
13210};
13211
13212/**
13213 * Expand bracket expressions in `glob.pattern`
13214 */
13215
13216Glob.prototype.extglob = function() {
13217 if (this.options.noextglob === true) return;
13218
13219 if (utils_1.isExtglob(this.pattern)) {
13220 this.pattern = utils_1.extglob(this.pattern, {escape: true});
13221 }
13222};
13223
13224/**
13225 * Parse the given pattern
13226 */
13227
13228Glob.prototype.parse = function(pattern) {
13229 this.tokens = utils_1.parseGlob(pattern || this.pattern, true);
13230 return this.tokens;
13231};
13232
13233/**
13234 * Replace `a` with `b`. Also tracks the change before and
13235 * after each replacement. This is disabled by default, but
13236 * can be enabled by setting `options.track` to true.
13237 *
13238 * Also, when the pattern is a string, `.split()` is used,
13239 * because it's much faster than replace.
13240 *
13241 * @param {RegExp|String} `a`
13242 * @param {String} `b`
13243 * @param {Boolean} `escape` When `true`, escapes `*` and `?` in the replacement.
13244 * @return {String}
13245 */
13246
13247Glob.prototype._replace = function(a, b, escape) {
13248 this.track('before (find): "' + a + '" (replace with): "' + b + '"');
13249 if (escape) b = esc(b);
13250 if (a && b && typeof a === 'string') {
13251 this.pattern = this.pattern.split(a).join(b);
13252 } else {
13253 this.pattern = this.pattern.replace(a, b);
13254 }
13255 this.track('after');
13256};
13257
13258/**
13259 * Escape special characters in the given string.
13260 *
13261 * @param {String} `str` Glob pattern
13262 * @return {String}
13263 */
13264
13265Glob.prototype.escape = function(str) {
13266 this.track('before escape: ');
13267 var re = /["\\](['"]?[^"'\\]['"]?)/g;
13268
13269 this.pattern = str.replace(re, function($0, $1) {
13270 var o = chars_1.ESC;
13271 var ch = o && o[$1];
13272 if (ch) {
13273 return ch;
13274 }
13275 if (/[a-z]/i.test($0)) {
13276 return $0.split('\\').join('');
13277 }
13278 return $0;
13279 });
13280
13281 this.track('after escape: ');
13282};
13283
13284/**
13285 * Unescape special characters in the given string.
13286 *
13287 * @param {String} `str`
13288 * @return {String}
13289 */
13290
13291Glob.prototype.unescape = function(str) {
13292 var re = /__([A-Z]+)_([A-Z]+)__/g;
13293 this.pattern = str.replace(re, function($0, $1) {
13294 return chars_1[$1][$0];
13295 });
13296 this.pattern = unesc(this.pattern);
13297};
13298
13299/**
13300 * Escape/unescape utils
13301 */
13302
13303function esc(str) {
13304 str = str.split('?').join('%~');
13305 str = str.split('*').join('%%');
13306 return str;
13307}
13308
13309function unesc(str) {
13310 str = str.split('%~').join('?');
13311 str = str.split('%%').join('*');
13312 return str;
13313}
13314});
13315
13316/**
13317 * Expose `expand`
13318 */
13319
13320var expand_1 = expand;
13321
13322/**
13323 * Expand a glob pattern to resolve braces and
13324 * similar patterns before converting to regex.
13325 *
13326 * @param {String|Array} `pattern`
13327 * @param {Array} `files`
13328 * @param {Options} `opts`
13329 * @return {Array}
13330 */
13331
13332function expand(pattern, options) {
13333 if (typeof pattern !== 'string') {
13334 throw new TypeError('micromatch.expand(): argument should be a string.');
13335 }
13336
13337 var glob$$1 = new glob(pattern, options || {});
13338 var opts = glob$$1.options;
13339
13340 if (!utils_1.isGlob(pattern)) {
13341 glob$$1.pattern = glob$$1.pattern.replace(/([\/.])/g, '\\$1');
13342 return glob$$1;
13343 }
13344
13345 glob$$1.pattern = glob$$1.pattern.replace(/(\+)(?!\()/g, '\\$1');
13346 glob$$1.pattern = glob$$1.pattern.split('$').join('\\$');
13347
13348 if (typeof opts.braces !== 'boolean' && typeof opts.nobraces !== 'boolean') {
13349 opts.braces = true;
13350 }
13351
13352 if (glob$$1.pattern === '.*') {
13353 return {
13354 pattern: '\\.' + star,
13355 tokens: tok,
13356 options: opts
13357 };
13358 }
13359
13360 if (glob$$1.pattern === '*') {
13361 return {
13362 pattern: oneStar(opts.dot),
13363 tokens: tok,
13364 options: opts
13365 };
13366 }
13367
13368 // parse the glob pattern into tokens
13369 glob$$1.parse();
13370 var tok = glob$$1.tokens;
13371 tok.is.negated = opts.negated;
13372
13373 // dotfile handling
13374 if ((opts.dotfiles === true || tok.is.dotfile) && opts.dot !== false) {
13375 opts.dotfiles = true;
13376 opts.dot = true;
13377 }
13378
13379 if ((opts.dotdirs === true || tok.is.dotdir) && opts.dot !== false) {
13380 opts.dotdirs = true;
13381 opts.dot = true;
13382 }
13383
13384 // check for braces with a dotfile pattern
13385 if (/[{,]\./.test(glob$$1.pattern)) {
13386 opts.makeRe = false;
13387 opts.dot = true;
13388 }
13389
13390 if (opts.nonegate !== true) {
13391 opts.negated = glob$$1.negated;
13392 }
13393
13394 // if the leading character is a dot or a slash, escape it
13395 if (glob$$1.pattern.charAt(0) === '.' && glob$$1.pattern.charAt(1) !== '/') {
13396 glob$$1.pattern = '\\' + glob$$1.pattern;
13397 }
13398
13399 /**
13400 * Extended globs
13401 */
13402
13403 // expand braces, e.g `{1..5}`
13404 glob$$1.track('before braces');
13405 if (tok.is.braces) {
13406 glob$$1.braces();
13407 }
13408 glob$$1.track('after braces');
13409
13410 // expand extglobs, e.g `foo/!(a|b)`
13411 glob$$1.track('before extglob');
13412 if (tok.is.extglob) {
13413 glob$$1.extglob();
13414 }
13415 glob$$1.track('after extglob');
13416
13417 // expand brackets, e.g `[[:alpha:]]`
13418 glob$$1.track('before brackets');
13419 if (tok.is.brackets) {
13420 glob$$1.brackets();
13421 }
13422 glob$$1.track('after brackets');
13423
13424 // special patterns
13425 glob$$1._replace('[!', '[^');
13426 glob$$1._replace('(?', '(%~');
13427 glob$$1._replace(/\[\]/, '\\[\\]');
13428 glob$$1._replace('/[', '/' + (opts.dot ? dotfiles : nodot) + '[', true);
13429 glob$$1._replace('/?', '/' + (opts.dot ? dotfiles : nodot) + '[^/]', true);
13430 glob$$1._replace('/.', '/(?=.)\\.', true);
13431
13432 // windows drives
13433 glob$$1._replace(/^(\w):([\\\/]+?)/gi, '(?=.)$1:$2', true);
13434
13435 // negate slashes in exclusion ranges
13436 if (glob$$1.pattern.indexOf('[^') !== -1) {
13437 glob$$1.pattern = negateSlash(glob$$1.pattern);
13438 }
13439
13440 if (opts.globstar !== false && glob$$1.pattern === '**') {
13441 glob$$1.pattern = globstar(opts.dot);
13442
13443 } else {
13444 glob$$1.pattern = balance(glob$$1.pattern, '[', ']');
13445 glob$$1.escape(glob$$1.pattern);
13446
13447 // if the pattern has `**`
13448 if (tok.is.globstar) {
13449 glob$$1.pattern = collapse(glob$$1.pattern, '/**');
13450 glob$$1.pattern = collapse(glob$$1.pattern, '**/');
13451 glob$$1._replace('/**/', '(?:/' + globstar(opts.dot) + '/|/)', true);
13452 glob$$1._replace(/\*{2,}/g, '**');
13453
13454 // 'foo/*'
13455 glob$$1._replace(/(\w+)\*(?!\/)/g, '$1[^/]*?', true);
13456 glob$$1._replace(/\*\*\/\*(\w)/g, globstar(opts.dot) + '\\/' + (opts.dot ? dotfiles : nodot) + '[^/]*?$1', true);
13457
13458 if (opts.dot !== true) {
13459 glob$$1._replace(/\*\*\/(.)/g, '(?:**\\/|)$1');
13460 }
13461
13462 // 'foo/**' or '{**,*}', but not 'foo**'
13463 if (tok.path.dirname !== '' || /,\*\*|\*\*,/.test(glob$$1.orig)) {
13464 glob$$1._replace('**', globstar(opts.dot), true);
13465 }
13466 }
13467
13468 // ends with /*
13469 glob$$1._replace(/\/\*$/, '\\/' + oneStar(opts.dot), true);
13470 // ends with *, no slashes
13471 glob$$1._replace(/(?!\/)\*$/, star, true);
13472 // has 'n*.' (partial wildcard w/ file extension)
13473 glob$$1._replace(/([^\/]+)\*/, '$1' + oneStar(true), true);
13474 // has '*'
13475 glob$$1._replace('*', oneStar(opts.dot), true);
13476 glob$$1._replace('?.', '?\\.', true);
13477 glob$$1._replace('?:', '?:', true);
13478
13479 glob$$1._replace(/\?+/g, function(match) {
13480 var len = match.length;
13481 if (len === 1) {
13482 return qmark;
13483 }
13484 return qmark + '{' + len + '}';
13485 });
13486
13487 // escape '.abc' => '\\.abc'
13488 glob$$1._replace(/\.([*\w]+)/g, '\\.$1');
13489 // fix '[^\\\\/]'
13490 glob$$1._replace(/\[\^[\\\/]+\]/g, qmark);
13491 // '///' => '\/'
13492 glob$$1._replace(/\/+/g, '\\/');
13493 // '\\\\\\' => '\\'
13494 glob$$1._replace(/\\{2,}/g, '\\');
13495 }
13496
13497 // unescape previously escaped patterns
13498 glob$$1.unescape(glob$$1.pattern);
13499 glob$$1._replace('__UNESC_STAR__', '*');
13500
13501 // escape dots that follow qmarks
13502 glob$$1._replace('?.', '?\\.');
13503
13504 // remove unnecessary slashes in character classes
13505 glob$$1._replace('[^\\/]', qmark);
13506
13507 if (glob$$1.pattern.length > 1) {
13508 if (/^[\[?*]/.test(glob$$1.pattern)) {
13509 // only prepend the string if we don't want to match dotfiles
13510 glob$$1.pattern = (opts.dot ? dotfiles : nodot) + glob$$1.pattern;
13511 }
13512 }
13513
13514 return glob$$1;
13515}
13516
13517/**
13518 * Collapse repeated character sequences.
13519 *
13520 * ```js
13521 * collapse('a/../../../b', '../');
13522 * //=> 'a/../b'
13523 * ```
13524 *
13525 * @param {String} `str`
13526 * @param {String} `ch` Character sequence to collapse
13527 * @return {String}
13528 */
13529
13530function collapse(str, ch) {
13531 var res = str.split(ch);
13532 var isFirst = res[0] === '';
13533 var isLast = res[res.length - 1] === '';
13534 res = res.filter(Boolean);
13535 if (isFirst) res.unshift('');
13536 if (isLast) res.push('');
13537 return res.join(ch);
13538}
13539
13540/**
13541 * Negate slashes in exclusion ranges, per glob spec:
13542 *
13543 * ```js
13544 * negateSlash('[^foo]');
13545 * //=> '[^\\/foo]'
13546 * ```
13547 *
13548 * @param {String} `str` glob pattern
13549 * @return {String}
13550 */
13551
13552function negateSlash(str) {
13553 return str.replace(/\[\^([^\]]*?)\]/g, function(match, inner) {
13554 if (inner.indexOf('/') === -1) {
13555 inner = '\\/' + inner;
13556 }
13557 return '[^' + inner + ']';
13558 });
13559}
13560
13561/**
13562 * Escape imbalanced braces/bracket. This is a very
13563 * basic, naive implementation that only does enough
13564 * to serve the purpose.
13565 */
13566
13567function balance(str, a, b) {
13568 var aarr = str.split(a);
13569 var alen = aarr.join('').length;
13570 var blen = str.split(b).join('').length;
13571
13572 if (alen !== blen) {
13573 str = aarr.join('\\' + a);
13574 return str.split(b).join('\\' + b);
13575 }
13576 return str;
13577}
13578
13579/**
13580 * Special patterns to be converted to regex.
13581 * Heuristics are used to simplify patterns
13582 * and speed up processing.
13583 */
13584
13585/* eslint no-multi-spaces: 0 */
13586var qmark = '[^/]';
13587var star = qmark + '*?';
13588var nodot = '(?!\\.)(?=.)';
13589var dotfileGlob = '(?:\\/|^)\\.{1,2}($|\\/)';
13590var dotfiles = '(?!' + dotfileGlob + ')(?=.)';
13591var twoStarDot = '(?:(?!' + dotfileGlob + ').)*?';
13592
13593/**
13594 * Create a regex for `*`.
13595 *
13596 * If `dot` is true, or the pattern does not begin with
13597 * a leading star, then return the simpler regex.
13598 */
13599
13600function oneStar(dotfile) {
13601 return dotfile ? '(?!' + dotfileGlob + ')(?=.)' + star : (nodot + star);
13602}
13603
13604function globstar(dotfile) {
13605 if (dotfile) { return twoStarDot; }
13606 return '(?:(?!(?:\\/|^)\\.).)*?';
13607}
13608
13609/**
13610 * The main function. Pass an array of filepaths,
13611 * and a string or array of glob patterns
13612 *
13613 * @param {Array|String} `files`
13614 * @param {Array|String} `patterns`
13615 * @param {Object} `opts`
13616 * @return {Array} Array of matches
13617 */
13618
13619function micromatch(files, patterns, opts) {
13620 if (!files || !patterns) return [];
13621 opts = opts || {};
13622
13623 if (typeof opts.cache === 'undefined') {
13624 opts.cache = true;
13625 }
13626
13627 if (!Array.isArray(patterns)) {
13628 return match(files, patterns, opts);
13629 }
13630
13631 var len = patterns.length, i = 0;
13632 var omit = [], keep = [];
13633
13634 while (len--) {
13635 var glob = patterns[i++];
13636 if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) {
13637 omit.push.apply(omit, match(files, glob.slice(1), opts));
13638 } else {
13639 keep.push.apply(keep, match(files, glob, opts));
13640 }
13641 }
13642 return utils_1.diff(keep, omit);
13643}
13644
13645/**
13646 * Return an array of files that match the given glob pattern.
13647 *
13648 * This function is called by the main `micromatch` function If you only
13649 * need to pass a single pattern you might get very minor speed improvements
13650 * using this function.
13651 *
13652 * @param {Array} `files`
13653 * @param {String} `pattern`
13654 * @param {Object} `options`
13655 * @return {Array}
13656 */
13657
13658function match(files, pattern, opts) {
13659 if (utils_1.typeOf(files) !== 'string' && !Array.isArray(files)) {
13660 throw new Error(msg('match', 'files', 'a string or array'));
13661 }
13662
13663 files = utils_1.arrayify(files);
13664 opts = opts || {};
13665
13666 var negate = opts.negate || false;
13667 var orig = pattern;
13668
13669 if (typeof pattern === 'string') {
13670 negate = pattern.charAt(0) === '!';
13671 if (negate) {
13672 pattern = pattern.slice(1);
13673 }
13674
13675 // we need to remove the character regardless,
13676 // so the above logic is still needed
13677 if (opts.nonegate === true) {
13678 negate = false;
13679 }
13680 }
13681
13682 var _isMatch = matcher(pattern, opts);
13683 var len = files.length, i = 0;
13684 var res = [];
13685
13686 while (i < len) {
13687 var file = files[i++];
13688 var fp = utils_1.unixify(file, opts);
13689
13690 if (!_isMatch(fp)) { continue; }
13691 res.push(fp);
13692 }
13693
13694 if (res.length === 0) {
13695 if (opts.failglob === true) {
13696 throw new Error('micromatch.match() found no matches for: "' + orig + '".');
13697 }
13698
13699 if (opts.nonull || opts.nullglob) {
13700 res.push(utils_1.unescapeGlob(orig));
13701 }
13702 }
13703
13704 // if `negate` was defined, diff negated files
13705 if (negate) { res = utils_1.diff(files, res); }
13706
13707 // if `ignore` was defined, diff ignored filed
13708 if (opts.ignore && opts.ignore.length) {
13709 pattern = opts.ignore;
13710 opts = utils_1.omit(opts, ['ignore']);
13711 res = utils_1.diff(res, micromatch(res, pattern, opts));
13712 }
13713
13714 if (opts.nodupes) {
13715 return utils_1.unique(res);
13716 }
13717 return res;
13718}
13719
13720/**
13721 * Returns a function that takes a glob pattern or array of glob patterns
13722 * to be used with `Array#filter()`. (Internally this function generates
13723 * the matching function using the [matcher] method).
13724 *
13725 * ```js
13726 * var fn = mm.filter('[a-c]');
13727 * ['a', 'b', 'c', 'd', 'e'].filter(fn);
13728 * //=> ['a', 'b', 'c']
13729 * ```
13730 * @param {String|Array} `patterns` Can be a glob or array of globs.
13731 * @param {Options} `opts` Options to pass to the [matcher] method.
13732 * @return {Function} Filter function to be passed to `Array#filter()`.
13733 */
13734
13735function filter(patterns, opts) {
13736 if (!Array.isArray(patterns) && typeof patterns !== 'string') {
13737 throw new TypeError(msg('filter', 'patterns', 'a string or array'));
13738 }
13739
13740 patterns = utils_1.arrayify(patterns);
13741 var len = patterns.length, i = 0;
13742 var patternMatchers = Array(len);
13743 while (i < len) {
13744 patternMatchers[i] = matcher(patterns[i++], opts);
13745 }
13746
13747 return function(fp) {
13748 if (fp == null) return [];
13749 var len = patternMatchers.length, i = 0;
13750 var res = true;
13751
13752 fp = utils_1.unixify(fp, opts);
13753 while (i < len) {
13754 var fn = patternMatchers[i++];
13755 if (!fn(fp)) {
13756 res = false;
13757 break;
13758 }
13759 }
13760 return res;
13761 };
13762}
13763
13764/**
13765 * Returns true if the filepath contains the given
13766 * pattern. Can also return a function for matching.
13767 *
13768 * ```js
13769 * isMatch('foo.md', '*.md', {});
13770 * //=> true
13771 *
13772 * isMatch('*.md', {})('foo.md')
13773 * //=> true
13774 * ```
13775 * @param {String} `fp`
13776 * @param {String} `pattern`
13777 * @param {Object} `opts`
13778 * @return {Boolean}
13779 */
13780
13781function isMatch(fp, pattern, opts) {
13782 if (typeof fp !== 'string') {
13783 throw new TypeError(msg('isMatch', 'filepath', 'a string'));
13784 }
13785
13786 fp = utils_1.unixify(fp, opts);
13787 if (utils_1.typeOf(pattern) === 'object') {
13788 return matcher(fp, pattern);
13789 }
13790 return matcher(pattern, opts)(fp);
13791}
13792
13793/**
13794 * Returns true if the filepath matches the
13795 * given pattern.
13796 */
13797
13798function contains(fp, pattern, opts) {
13799 if (typeof fp !== 'string') {
13800 throw new TypeError(msg('contains', 'pattern', 'a string'));
13801 }
13802
13803 opts = opts || {};
13804 opts.contains = (pattern !== '');
13805 fp = utils_1.unixify(fp, opts);
13806
13807 if (opts.contains && !utils_1.isGlob(pattern)) {
13808 return fp.indexOf(pattern) !== -1;
13809 }
13810 return matcher(pattern, opts)(fp);
13811}
13812
13813/**
13814 * Returns true if a file path matches any of the
13815 * given patterns.
13816 *
13817 * @param {String} `fp` The filepath to test.
13818 * @param {String|Array} `patterns` Glob patterns to use.
13819 * @param {Object} `opts` Options to pass to the `matcher()` function.
13820 * @return {String}
13821 */
13822
13823function any(fp, patterns, opts) {
13824 if (!Array.isArray(patterns) && typeof patterns !== 'string') {
13825 throw new TypeError(msg('any', 'patterns', 'a string or array'));
13826 }
13827
13828 patterns = utils_1.arrayify(patterns);
13829 var len = patterns.length;
13830
13831 fp = utils_1.unixify(fp, opts);
13832 while (len--) {
13833 var isMatch = matcher(patterns[len], opts);
13834 if (isMatch(fp)) {
13835 return true;
13836 }
13837 }
13838 return false;
13839}
13840
13841/**
13842 * Filter the keys of an object with the given `glob` pattern
13843 * and `options`
13844 *
13845 * @param {Object} `object`
13846 * @param {Pattern} `object`
13847 * @return {Array}
13848 */
13849
13850function matchKeys(obj, glob, options) {
13851 if (utils_1.typeOf(obj) !== 'object') {
13852 throw new TypeError(msg('matchKeys', 'first argument', 'an object'));
13853 }
13854
13855 var fn = matcher(glob, options);
13856 var res = {};
13857
13858 for (var key in obj) {
13859 if (obj.hasOwnProperty(key) && fn(key)) {
13860 res[key] = obj[key];
13861 }
13862 }
13863 return res;
13864}
13865
13866/**
13867 * Return a function for matching based on the
13868 * given `pattern` and `options`.
13869 *
13870 * @param {String} `pattern`
13871 * @param {Object} `options`
13872 * @return {Function}
13873 */
13874
13875function matcher(pattern, opts) {
13876 // pattern is a function
13877 if (typeof pattern === 'function') {
13878 return pattern;
13879 }
13880 // pattern is a regex
13881 if (pattern instanceof RegExp) {
13882 return function(fp) {
13883 return pattern.test(fp);
13884 };
13885 }
13886
13887 if (typeof pattern !== 'string') {
13888 throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function'));
13889 }
13890
13891 // strings, all the way down...
13892 pattern = utils_1.unixify(pattern, opts);
13893
13894 // pattern is a non-glob string
13895 if (!utils_1.isGlob(pattern)) {
13896 return utils_1.matchPath(pattern, opts);
13897 }
13898 // pattern is a glob string
13899 var re = makeRe(pattern, opts);
13900
13901 // `matchBase` is defined
13902 if (opts && opts.matchBase) {
13903 return utils_1.hasFilename(re, opts);
13904 }
13905 // `matchBase` is not defined
13906 return function(fp) {
13907 fp = utils_1.unixify(fp, opts);
13908 return re.test(fp);
13909 };
13910}
13911
13912/**
13913 * Create and cache a regular expression for matching
13914 * file paths.
13915 *
13916 * If the leading character in the `glob` is `!`, a negation
13917 * regex is returned.
13918 *
13919 * @param {String} `glob`
13920 * @param {Object} `options`
13921 * @return {RegExp}
13922 */
13923
13924function toRegex(glob, options) {
13925 // clone options to prevent mutating the original object
13926 var opts = Object.create(options || {});
13927 var flags = opts.flags || '';
13928 if (opts.nocase && flags.indexOf('i') === -1) {
13929 flags += 'i';
13930 }
13931
13932 var parsed = expand_1(glob, opts);
13933
13934 // pass in tokens to avoid parsing more than once
13935 opts.negated = opts.negated || parsed.negated;
13936 opts.negate = opts.negated;
13937 glob = wrapGlob(parsed.pattern, opts);
13938 var re;
13939
13940 try {
13941 re = new RegExp(glob, flags);
13942 return re;
13943 } catch (err) {
13944 err.reason = 'micromatch invalid regex: (' + re + ')';
13945 if (opts.strict) throw new SyntaxError(err);
13946 }
13947
13948 // we're only here if a bad pattern was used and the user
13949 // passed `options.silent`, so match nothing
13950 return /$^/;
13951}
13952
13953/**
13954 * Create the regex to do the matching. If the leading
13955 * character in the `glob` is `!` a negation regex is returned.
13956 *
13957 * @param {String} `glob`
13958 * @param {Boolean} `negate`
13959 */
13960
13961function wrapGlob(glob, opts) {
13962 var prefix = (opts && !opts.contains) ? '^' : '';
13963 var after = (opts && !opts.contains) ? '$' : '';
13964 glob = ('(?:' + glob + ')' + after);
13965 if (opts && opts.negate) {
13966 return prefix + ('(?!^' + glob + ').*$');
13967 }
13968 return prefix + glob;
13969}
13970
13971/**
13972 * Create and cache a regular expression for matching file paths.
13973 * If the leading character in the `glob` is `!`, a negation
13974 * regex is returned.
13975 *
13976 * @param {String} `glob`
13977 * @param {Object} `options`
13978 * @return {RegExp}
13979 */
13980
13981function makeRe(glob, opts) {
13982 if (utils_1.typeOf(glob) !== 'string') {
13983 throw new Error(msg('makeRe', 'glob', 'a string'));
13984 }
13985 return utils_1.cache(toRegex, glob, opts);
13986}
13987
13988/**
13989 * Make error messages consistent. Follows this format:
13990 *
13991 * ```js
13992 * msg(methodName, argNumber, nativeType);
13993 * // example:
13994 * msg('matchKeys', 'first', 'an object');
13995 * ```
13996 *
13997 * @param {String} `method`
13998 * @param {String} `num`
13999 * @param {String} `type`
14000 * @return {String}
14001 */
14002
14003function msg(method, what, type) {
14004 return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.';
14005}
14006
14007/**
14008 * Public methods
14009 */
14010
14011/* eslint no-multi-spaces: 0 */
14012micromatch.any = any;
14013micromatch.braces = micromatch.braceExpand = utils_1.braces;
14014micromatch.contains = contains;
14015micromatch.expand = expand_1;
14016micromatch.filter = filter;
14017micromatch.isMatch = isMatch;
14018micromatch.makeRe = makeRe;
14019micromatch.match = match;
14020micromatch.matcher = matcher;
14021micromatch.matchKeys = matchKeys;
14022
14023/**
14024 * Expose `micromatch`
14025 */
14026
14027var index$1 = micromatch;
14028
14029function ensureArray$1 ( thing ) {
14030 if ( Array.isArray( thing ) ) return thing;
14031 if ( thing == undefined ) return [];
14032 return [ thing ];
14033}
14034
14035function createFilter ( include, exclude ) {
14036 const getMatcher = id => ( isRegexp( id ) ? id : { test: index$1.matcher( path.resolve( id ) ) } );
14037 include = ensureArray$1( include ).map( getMatcher );
14038 exclude = ensureArray$1( exclude ).map( getMatcher );
14039
14040 return function ( id ) {
14041
14042 if ( typeof id !== 'string' ) return false;
14043 if ( /\0/.test( id ) ) return false;
14044
14045 id = id.split( path.sep ).join( '/' );
14046
14047 for ( let i = 0; i < exclude.length; ++i ) {
14048 const matcher = exclude[i];
14049 if ( matcher.test( id ) ) return false;
14050 }
14051
14052 for ( let i = 0; i < include.length; ++i ) {
14053 const matcher = include[i];
14054 if ( matcher.test( id ) ) return true;
14055 }
14056
14057 return !include.length;
14058 };
14059}
14060
14061function isRegexp ( val ) {
14062 return val instanceof RegExp;
14063}
14064
14065var modules = {};
14066
14067var getModule = function(dir) {
14068 var rootPath = dir ? path__default.resolve(dir) : process.cwd();
14069 var rootName = path__default.join(rootPath, '@root');
14070 var root = modules[rootName];
14071 if (!root) {
14072 root = new module$1(rootName);
14073 root.filename = rootName;
14074 root.paths = module$1._nodeModulePaths(rootPath);
14075 modules[rootName] = root;
14076 }
14077 return root;
14078};
14079
14080var requireRelative = function(requested, relativeTo) {
14081 var root = getModule(relativeTo);
14082 return root.require(requested);
14083};
14084
14085requireRelative.resolve = function(requested, relativeTo) {
14086 var root = getModule(relativeTo);
14087 return module$1._resolveFilename(requested, root);
14088};
14089
14090var index$76 = requireRelative;
14091
14092var chokidar;
14093
14094try {
14095 chokidar = index$76( 'chokidar', process.cwd() );
14096} catch (err) {
14097 chokidar = null;
14098}
14099
14100var chokidar$1 = chokidar;
14101
14102var opts = { encoding: 'utf-8', persistent: true };
14103
14104var watchers = new Map();
14105
14106function addTask(id, task, chokidarOptions, chokidarOptionsHash) {
14107 if (!watchers.has(chokidarOptionsHash)) { watchers.set(chokidarOptionsHash, new Map()); }
14108 var group = watchers.get(chokidarOptionsHash);
14109
14110 if (!group.has(id)) {
14111 var watcher = new FileWatcher(id, chokidarOptions, function () {
14112 group.delete(id);
14113 });
14114
14115 if (watcher.fileExists) {
14116 group.set(id, watcher);
14117 } else {
14118 return;
14119 }
14120 }
14121
14122 group.get(id).tasks.add(task);
14123}
14124
14125function deleteTask(id, target, chokidarOptionsHash) {
14126 var group = watchers.get(chokidarOptionsHash);
14127
14128 var watcher = group.get(id);
14129 if (watcher) {
14130 watcher.tasks.delete(target);
14131
14132 if (watcher.tasks.size === 0) {
14133 watcher.close();
14134 group.delete(id);
14135 }
14136 }
14137}
14138
14139var FileWatcher = function FileWatcher(id, chokidarOptions, dispose) {
14140 var this$1 = this;
14141
14142 this.tasks = new Set();
14143
14144 var data;
14145
14146 try {
14147 fs.statSync(id);
14148 this.fileExists = true;
14149 } catch (err) {
14150 if (err.code === 'ENOENT') {
14151 // can't watch files that don't exist (e.g. injected
14152 // by plugins somehow)
14153 this.fileExists = false;
14154 return;
14155 } else {
14156 throw err;
14157 }
14158 }
14159
14160 var handleWatchEvent = function (event) {
14161 if (event === 'rename' || event === 'unlink') {
14162 this$1.fsWatcher.close();
14163 this$1.trigger();
14164 dispose();
14165 } else {
14166 // this is necessary because we get duplicate events...
14167 var contents = fs.readFileSync(id, 'utf-8');
14168 if (contents !== data) {
14169 data = contents;
14170 this$1.trigger();
14171 }
14172 }
14173 };
14174
14175 if (chokidarOptions) {
14176 this.fsWatcher = chokidar$1
14177 .watch(id, chokidarOptions)
14178 .on('all', handleWatchEvent);
14179 } else {
14180 this.fsWatcher = fs.watch(id, opts, handleWatchEvent);
14181 }
14182};
14183
14184FileWatcher.prototype.close = function close () {
14185 this.fsWatcher.close();
14186};
14187
14188FileWatcher.prototype.trigger = function trigger () {
14189 this.tasks.forEach(function (task) {
14190 task.makeDirty();
14191 });
14192};
14193
14194var DELAY = 100;
14195
14196var Watcher = (function (EventEmitter$$1) {
14197 function Watcher(configs) {
14198 var this$1 = this;
14199
14200 EventEmitter$$1.call(this);
14201
14202 this.dirty = true;
14203 this.running = false;
14204 this.tasks = ensureArray(configs).map(function (config) { return new Task(this$1, config); });
14205 this.succeeded = false;
14206
14207 process.nextTick(function () {
14208 this$1._run();
14209 });
14210 }
14211
14212 if ( EventEmitter$$1 ) Watcher.__proto__ = EventEmitter$$1;
14213 Watcher.prototype = Object.create( EventEmitter$$1 && EventEmitter$$1.prototype );
14214 Watcher.prototype.constructor = Watcher;
14215
14216 Watcher.prototype.close = function close () {
14217 this.tasks.forEach(function (task) {
14218 task.close();
14219 });
14220
14221 this.removeAllListeners();
14222 };
14223
14224 Watcher.prototype._makeDirty = function _makeDirty () {
14225 var this$1 = this;
14226
14227 if (this.dirty) { return; }
14228 this.dirty = true;
14229
14230 if (!this.running) {
14231 setTimeout(function () {
14232 this$1._run();
14233 }, DELAY);
14234 }
14235 };
14236
14237 Watcher.prototype._run = function _run () {
14238 var this$1 = this;
14239
14240 this.running = true;
14241 this.dirty = false;
14242
14243 this.emit('event', {
14244 code: 'START'
14245 });
14246
14247 mapSequence(this.tasks, function (task) { return task.run(); })
14248 .then(function () {
14249 this$1.succeeded = true;
14250
14251 this$1.emit('event', {
14252 code: 'END'
14253 });
14254 })
14255 .catch(function (error) {
14256 this$1.emit('event', {
14257 code: this$1.succeeded ? 'ERROR' : 'FATAL',
14258 error: error
14259 });
14260 })
14261 .then(function () {
14262 this$1.running = false;
14263
14264 if (this$1.dirty) {
14265 this$1._run();
14266 }
14267 });
14268 };
14269
14270 return Watcher;
14271}(EventEmitter));
14272
14273var Task = function Task(watcher, options) {
14274 this.cache = null;
14275 this.watcher = watcher;
14276 this.options = options;
14277
14278 this.dirty = true;
14279 this.closed = false;
14280 this.watched = new Set();
14281
14282 this.targets = options.targets ? options.targets : [{ dest: options.dest, format: options.format }];
14283
14284 this.dests = (this.targets.map(function (t) { return t.dest; })).map(function (dest) { return path__default.resolve(dest); });
14285
14286 var watchOptions = options.watch || {};
14287 if ('useChokidar' in watchOptions) { watchOptions.chokidar = watchOptions.useChokidar; }
14288 var chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
14289 if (chokidarOptions) {
14290 chokidarOptions = Object.assign(
14291 chokidarOptions === true ? {} : chokidarOptions,
14292 {
14293 ignoreInitial: true
14294 }
14295 );
14296 }
14297
14298 if (chokidarOptions && !chokidar$1) {
14299 throw new Error("options.watch.chokidar was provided, but chokidar could not be found. Have you installed it?");
14300 }
14301
14302 this.chokidarOptions = chokidarOptions;
14303 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
14304
14305 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
14306};
14307
14308Task.prototype.close = function close () {
14309 var this$1 = this;
14310
14311 this.closed = true;
14312 this.watched.forEach(function (id) {
14313 deleteTask(id, this$1, this$1.chokidarOptionsHash);
14314 });
14315};
14316
14317Task.prototype.makeDirty = function makeDirty () {
14318 if (!this.dirty) {
14319 this.dirty = true;
14320 this.watcher._makeDirty();
14321 }
14322};
14323
14324Task.prototype.run = function run () {
14325 var this$1 = this;
14326
14327 if (!this.dirty) { return; }
14328 this.dirty = false;
14329
14330 var options = Object.assign(this.options, {
14331 cache: this.cache
14332 });
14333
14334 var start = Date.now();
14335
14336 this.watcher.emit('event', {
14337 code: 'BUNDLE_START',
14338 input: this.options.entry,
14339 output: this.dests
14340 });
14341
14342 return rollup(options)
14343 .then(function (bundle) {
14344 if (this$1.closed) { return; }
14345
14346 this$1.cache = bundle;
14347
14348 var watched = new Set();
14349
14350 bundle.modules.forEach(function (module) {
14351 watched.add(module.id);
14352 this$1.watchFile(module.id);
14353 });
14354
14355 this$1.watched.forEach(function (id) {
14356 if (!watched.has(id)) { deleteTask(id, this$1, this$1.chokidarOptionsHash); }
14357 });
14358
14359 this$1.watched = watched;
14360
14361 return Promise.all(
14362 this$1.targets.map(function (target) {
14363 var options = Object.assign({}, this$1.options, target);
14364 return bundle.write(options);
14365 })
14366 );
14367 })
14368 .then(function () {
14369 this$1.watcher.emit('event', {
14370 code: 'BUNDLE_END',
14371 input: this$1.options.entry,
14372 output: this$1.dests,
14373 duration: Date.now() - start
14374 });
14375 })
14376 .catch(function (error) {
14377 if (this$1.closed) { return; }
14378
14379 if (this$1.cache) {
14380 this$1.cache.modules.forEach(function (module) {
14381 // this is necessary to ensure that any 'renamed' files
14382 // continue to be watched following an error
14383 this$1.watchFile(module.id);
14384 });
14385 }
14386 throw error;
14387 });
14388};
14389
14390Task.prototype.watchFile = function watchFile (id) {
14391 if (!this.filter(id)) { return; }
14392
14393 if (~this.dests.indexOf(id)) {
14394 throw new Error('Cannot import the generated bundle');
14395 }
14396
14397 // this is necessary to ensure that any 'renamed' files
14398 // continue to be watched following an error
14399 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash);
14400};
14401
14402function watch$1(configs) {
14403 return new Watcher(configs);
14404}
14405
14406var version$1 = "0.47.4";
14407
14408exports.rollup = rollup;
14409exports.watch = watch$1;
14410exports.VERSION = version$1;
14411//# sourceMappingURL=rollup.js.map