UNPKG

414 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
11import path, { basename, dirname, extname, relative, resolve, sep } from 'path';
12import { lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFile } from 'fs';
13import EventEmitter from 'events';
14import module$1 from 'module';
15
16var DEBUG = false;
17var map = new Map;
18
19var timeStartHelper;
20var timeEndHelper;
21
22if ( typeof process === 'undefined' || typeof process.hrtime === 'undefined' ) {
23 timeStartHelper = function timeStartHelper () {
24 return window.performance.now();
25 };
26
27 timeEndHelper = function timeEndHelper ( previous ) {
28 return window.performance.now() - previous;
29 };
30} else {
31 timeStartHelper = function timeStartHelper () {
32 return process.hrtime();
33 };
34
35 timeEndHelper = function timeEndHelper ( previous ) {
36 var hrtime = process.hrtime( previous );
37 return hrtime[0] * 1e3 + Math.floor( hrtime[1] / 1e6 );
38 };
39}
40
41function timeStart ( label ) {
42 if ( !map.has( label ) ) {
43 map.set( label, {
44 time: 0
45 });
46 }
47 map.get( label ).start = timeStartHelper();
48}
49
50function timeEnd ( label ) {
51 if ( map.has( label ) ) {
52 var item = map.get( label );
53 item.time += timeEndHelper( item.start );
54 }
55}
56
57function flushTime ( log ) {
58 if ( log === void 0 ) log = defaultLog;
59
60 for ( var item of map.entries() ) {
61 log( item[0], item[1].time );
62 }
63 map.clear();
64}
65
66function defaultLog ( label, time ) {
67 if ( DEBUG ) {
68 /* eslint-disable no-console */
69 console.info( '%dms: %s', time, label );
70 /* eslint-enable no-console */
71 }
72}
73
74var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
75var relativePath = /^\.?\.\//;
76
77function isAbsolute ( path$$1 ) {
78 return absolutePath.test( path$$1 );
79}
80
81function isRelative ( path$$1 ) {
82 return relativePath.test( path$$1 );
83}
84
85function normalize ( path$$1 ) {
86 return path$$1.replace( /\\/g, '/' );
87}
88
89function mkdirpath ( path$$1 ) {
90 var dir = dirname( path$$1 );
91 try {
92 readdirSync( dir );
93 } catch ( err ) {
94 mkdirpath( dir );
95 mkdirSync( dir );
96 }
97}
98
99function writeFile$1 ( dest, data ) {
100 return new Promise( function ( fulfil, reject ) {
101 mkdirpath( dest );
102
103 writeFile( dest, data, function (err) {
104 if ( err ) {
105 reject( err );
106 } else {
107 fulfil();
108 }
109 });
110 });
111}
112
113var keys = Object.keys;
114
115function blank () {
116 return Object.create( null );
117}
118
119function forOwn ( object, func ) {
120 Object.keys( object ).forEach( function (key) { return func( object[ key ], key ); } );
121}
122
123function assign ( target ) {
124 var sources = [], len = arguments.length - 1;
125 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
126
127 sources.forEach( function (source) {
128 for ( var key in source ) {
129 if ( source.hasOwnProperty( key ) ) { target[ key ] = source[ key ]; }
130 }
131 });
132
133 return target;
134}
135
136function mapSequence ( array, fn ) {
137 var results = [];
138 var promise = Promise.resolve();
139
140 function next ( member, i ) {
141 return fn( member ).then( function (value) { return results[i] = value; } );
142 }
143
144 var loop = function ( i ) {
145 promise = promise.then( function () { return next( array[i], i ); } );
146 };
147
148 for ( var i = 0; i < array.length; i += 1 ) loop( i );
149
150 return promise.then( function () { return results; } );
151}
152
153function validateKeys ( actualKeys, allowedKeys ) {
154 var i = actualKeys.length;
155
156 while ( i-- ) {
157 var key = actualKeys[i];
158
159 if ( allowedKeys.indexOf( key ) === -1 ) {
160 return new Error(
161 ("Unexpected key '" + key + "' found, expected one of: " + (allowedKeys.join( ', ' )))
162 );
163 }
164 }
165}
166
167function error ( props ) {
168 // use the same constructor as props (if it's an error object)
169 // so that err.name is preserved etc
170 // (Object.keys below does not update these values because they
171 // are properties on the prototype chain)
172 // basically if props is a SyntaxError it will not be overriden as a generic Error
173 var constructor = (props instanceof Error) ? props.constructor : Error;
174 var err = new constructor( props.message );
175
176 Object.keys( props ).forEach( function (key) {
177 err[ key ] = props[ key ];
178 });
179
180 throw err;
181}
182
183// this looks ridiculous, but it prevents sourcemap tooling from mistaking
184// this for an actual sourceMappingURL
185var SOURCEMAPPING_URL = 'sourceMa';
186SOURCEMAPPING_URL += 'ppingURL';
187
188var SOURCEMAPPING_URL_RE = new RegExp( ("^#\\s+" + SOURCEMAPPING_URL + "=.+\\n?") );
189
190var charToInteger = {};
191var integerToChar = {};
192
193'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
194 charToInteger[ char ] = i;
195 integerToChar[ i ] = char;
196});
197
198function decode$1 ( string ) {
199 var result = [],
200 len = string.length,
201 i,
202 hasContinuationBit,
203 shift = 0,
204 value = 0,
205 integer,
206 shouldNegate;
207
208 for ( i = 0; i < len; i += 1 ) {
209 integer = charToInteger[ string[i] ];
210
211 if ( integer === undefined ) {
212 throw new Error( 'Invalid character (' + string[i] + ')' );
213 }
214
215 hasContinuationBit = integer & 32;
216
217 integer &= 31;
218 value += integer << shift;
219
220 if ( hasContinuationBit ) {
221 shift += 5;
222 } else {
223 shouldNegate = value & 1;
224 value >>= 1;
225
226 result.push( shouldNegate ? -value : value );
227
228 // reset
229 value = shift = 0;
230 }
231 }
232
233 return result;
234}
235
236function encode$1 ( value ) {
237 var result, i;
238
239 if ( typeof value === 'number' ) {
240 result = encodeInteger( value );
241 } else {
242 result = '';
243 for ( i = 0; i < value.length; i += 1 ) {
244 result += encodeInteger( value[i] );
245 }
246 }
247
248 return result;
249}
250
251function encodeInteger ( num ) {
252 var result = '', clamped;
253
254 if ( num < 0 ) {
255 num = ( -num << 1 ) | 1;
256 } else {
257 num <<= 1;
258 }
259
260 do {
261 clamped = num & 31;
262 num >>= 5;
263
264 if ( num > 0 ) {
265 clamped |= 32;
266 }
267
268 result += integerToChar[ clamped ];
269 } while ( num > 0 );
270
271 return result;
272}
273
274function decodeSegments ( encodedSegments ) {
275 var i = encodedSegments.length;
276 var segments = new Array( i );
277
278 while ( i-- ) { segments[i] = decode$1( encodedSegments[i] ); }
279 return segments;
280}
281
282function decode$$1 ( mappings ) {
283 var sourceFileIndex = 0; // second field
284 var sourceCodeLine = 0; // third field
285 var sourceCodeColumn = 0; // fourth field
286 var nameIndex = 0; // fifth field
287
288 var lines = mappings.split( ';' );
289 var numLines = lines.length;
290 var decoded = new Array( numLines );
291
292 var i;
293 var j;
294 var line;
295 var generatedCodeColumn;
296 var decodedLine;
297 var segments;
298 var segment;
299 var result;
300
301 for ( i = 0; i < numLines; i += 1 ) {
302 line = lines[i];
303
304 generatedCodeColumn = 0; // first field - reset each time
305 decodedLine = [];
306
307 segments = decodeSegments( line.split( ',' ) );
308
309 for ( j = 0; j < segments.length; j += 1 ) {
310 segment = segments[j];
311
312 if ( !segment.length ) {
313 break;
314 }
315
316 generatedCodeColumn += segment[0];
317
318 result = [ generatedCodeColumn ];
319 decodedLine.push( result );
320
321 if ( segment.length === 1 ) {
322 // only one field!
323 continue;
324 }
325
326 sourceFileIndex += segment[1];
327 sourceCodeLine += segment[2];
328 sourceCodeColumn += segment[3];
329
330 result.push( sourceFileIndex, sourceCodeLine, sourceCodeColumn );
331
332 if ( segment.length === 5 ) {
333 nameIndex += segment[4];
334 result.push( nameIndex );
335 }
336 }
337
338 decoded[i] = decodedLine;
339 }
340
341 return decoded;
342}
343
344function encode$$1 ( decoded ) {
345 var offsets = {
346 generatedCodeColumn: 0,
347 sourceFileIndex: 0, // second field
348 sourceCodeLine: 0, // third field
349 sourceCodeColumn: 0, // fourth field
350 nameIndex: 0 // fifth field
351 };
352
353 return decoded.map( function (line) {
354 offsets.generatedCodeColumn = 0; // first field - reset each time
355 return line.map( encodeSegment ).join( ',' );
356 }).join( ';' );
357
358 function encodeSegment ( segment ) {
359 if ( !segment.length ) {
360 return segment;
361 }
362
363 var result = new Array( segment.length );
364
365 result[0] = segment[0] - offsets.generatedCodeColumn;
366 offsets.generatedCodeColumn = segment[0];
367
368 if ( segment.length === 1 ) {
369 // only one field!
370 return encode$1( result );
371 }
372
373 result[1] = segment[1] - offsets.sourceFileIndex;
374 result[2] = segment[2] - offsets.sourceCodeLine;
375 result[3] = segment[3] - offsets.sourceCodeColumn;
376
377 offsets.sourceFileIndex = segment[1];
378 offsets.sourceCodeLine = segment[2];
379 offsets.sourceCodeColumn = segment[3];
380
381 if ( segment.length === 5 ) {
382 result[4] = segment[4] - offsets.nameIndex;
383 offsets.nameIndex = segment[4];
384 }
385
386 return encode$1( result );
387 }
388}
389
390var charToInteger$1 = {};
391var integerToChar$1 = {};
392
393'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
394 charToInteger$1[ char ] = i;
395 integerToChar$1[ i ] = char;
396});
397
398
399
400function encode ( value ) {
401 var result;
402
403 if ( typeof value === 'number' ) {
404 result = encodeInteger$1( value );
405 } else {
406 result = '';
407 for ( var i = 0; i < value.length; i += 1 ) {
408 result += encodeInteger$1( value[i] );
409 }
410 }
411
412 return result;
413}
414
415function encodeInteger$1 ( num ) {
416 var result = '';
417
418 if ( num < 0 ) {
419 num = ( -num << 1 ) | 1;
420 } else {
421 num <<= 1;
422 }
423
424 do {
425 var clamped = num & 31;
426 num >>= 5;
427
428 if ( num > 0 ) {
429 clamped |= 32;
430 }
431
432 result += integerToChar$1[ clamped ];
433 } while ( num > 0 );
434
435 return result;
436}
437
438function Chunk ( start, end, content ) {
439 this.start = start;
440 this.end = end;
441 this.original = content;
442
443 this.intro = '';
444 this.outro = '';
445
446 this.content = content;
447 this.storeName = false;
448 this.edited = false;
449
450 // we make these non-enumerable, for sanity while debugging
451 Object.defineProperties( this, {
452 previous: { writable: true, value: null },
453 next: { writable: true, value: null }
454 });
455}
456
457Chunk.prototype = {
458 appendLeft: function appendLeft ( content ) {
459 this.outro += content;
460 },
461
462 appendRight: function appendRight ( content ) {
463 this.intro = this.intro + content;
464 },
465
466 clone: function clone () {
467 var chunk = new Chunk( this.start, this.end, this.original );
468
469 chunk.intro = this.intro;
470 chunk.outro = this.outro;
471 chunk.content = this.content;
472 chunk.storeName = this.storeName;
473 chunk.edited = this.edited;
474
475 return chunk;
476 },
477
478 contains: function contains ( index ) {
479 return this.start < index && index < this.end;
480 },
481
482 eachNext: function eachNext ( fn ) {
483 var chunk = this;
484 while ( chunk ) {
485 fn( chunk );
486 chunk = chunk.next;
487 }
488 },
489
490 eachPrevious: function eachPrevious ( fn ) {
491 var chunk = this;
492 while ( chunk ) {
493 fn( chunk );
494 chunk = chunk.previous;
495 }
496 },
497
498 edit: function edit ( content, storeName, contentOnly ) {
499 this.content = content;
500 if ( !contentOnly ) {
501 this.intro = '';
502 this.outro = '';
503 }
504 this.storeName = storeName;
505
506 this.edited = true;
507
508 return this;
509 },
510
511 prependLeft: function prependLeft ( content ) {
512 this.outro = content + this.outro;
513 },
514
515 prependRight: function prependRight ( content ) {
516 this.intro = content + this.intro;
517 },
518
519 split: function split ( index ) {
520 var sliceIndex = index - this.start;
521
522 var originalBefore = this.original.slice( 0, sliceIndex );
523 var originalAfter = this.original.slice( sliceIndex );
524
525 this.original = originalBefore;
526
527 var newChunk = new Chunk( index, this.end, originalAfter );
528 newChunk.outro = this.outro;
529 this.outro = '';
530
531 this.end = index;
532
533 if ( this.edited ) {
534 // TODO is this block necessary?...
535 newChunk.edit( '', false );
536 this.content = '';
537 } else {
538 this.content = originalBefore;
539 }
540
541 newChunk.next = this.next;
542 if ( newChunk.next ) { newChunk.next.previous = newChunk; }
543 newChunk.previous = this;
544 this.next = newChunk;
545
546 return newChunk;
547 },
548
549 toString: function toString () {
550 return this.intro + this.content + this.outro;
551 },
552
553 trimEnd: function trimEnd ( rx ) {
554 this.outro = this.outro.replace( rx, '' );
555 if ( this.outro.length ) { return true; }
556
557 var trimmed = this.content.replace( rx, '' );
558
559 if ( trimmed.length ) {
560 if ( trimmed !== this.content ) {
561 this.split( this.start + trimmed.length ).edit( '', false );
562 }
563
564 return true;
565 } else {
566 this.edit( '', false );
567
568 this.intro = this.intro.replace( rx, '' );
569 if ( this.intro.length ) { return true; }
570 }
571 },
572
573 trimStart: function trimStart ( rx ) {
574 this.intro = this.intro.replace( rx, '' );
575 if ( this.intro.length ) { return true; }
576
577 var trimmed = this.content.replace( rx, '' );
578
579 if ( trimmed.length ) {
580 if ( trimmed !== this.content ) {
581 this.split( this.end - trimmed.length );
582 this.edit( '', false );
583 }
584
585 return true;
586 } else {
587 this.edit( '', false );
588
589 this.outro = this.outro.replace( rx, '' );
590 if ( this.outro.length ) { return true; }
591 }
592 }
593};
594
595var _btoa;
596
597if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) {
598 _btoa = window.btoa;
599} else if ( typeof Buffer === 'function' ) {
600 _btoa = function (str) { return new Buffer( str ).toString( 'base64' ); };
601} else {
602 _btoa = function () {
603 throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' );
604 };
605}
606
607var btoa = _btoa;
608
609function SourceMap ( properties ) {
610 this.version = 3;
611
612 this.file = properties.file;
613 this.sources = properties.sources;
614 this.sourcesContent = properties.sourcesContent;
615 this.names = properties.names;
616 this.mappings = properties.mappings;
617}
618
619SourceMap.prototype = {
620 toString: function toString () {
621 return JSON.stringify( this );
622 },
623
624 toUrl: function toUrl () {
625 return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() );
626 }
627};
628
629function guessIndent ( code ) {
630 var lines = code.split( '\n' );
631
632 var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } );
633 var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } );
634
635 if ( tabbed.length === 0 && spaced.length === 0 ) {
636 return null;
637 }
638
639 // More lines tabbed than spaced? Assume tabs, and
640 // default to tabs in the case of a tie (or nothing
641 // to go on)
642 if ( tabbed.length >= spaced.length ) {
643 return '\t';
644 }
645
646 // Otherwise, we need to guess the multiple
647 var min = spaced.reduce( function ( previous, current ) {
648 var numSpaces = /^ +/.exec( current )[0].length;
649 return Math.min( numSpaces, previous );
650 }, Infinity );
651
652 return new Array( min + 1 ).join( ' ' );
653}
654
655function getRelativePath ( from, to ) {
656 var fromParts = from.split( /[\/\\]/ );
657 var toParts = to.split( /[\/\\]/ );
658
659 fromParts.pop(); // get dirname
660
661 while ( fromParts[0] === toParts[0] ) {
662 fromParts.shift();
663 toParts.shift();
664 }
665
666 if ( fromParts.length ) {
667 var i = fromParts.length;
668 while ( i-- ) { fromParts[i] = '..'; }
669 }
670
671 return fromParts.concat( toParts ).join( '/' );
672}
673
674var toString$1 = Object.prototype.toString;
675
676function isObject ( thing ) {
677 return toString$1.call( thing ) === '[object Object]';
678}
679
680function getLocator ( source ) {
681 var originalLines = source.split( '\n' );
682
683 var start = 0;
684 var lineRanges = originalLines.map( function ( line, i ) {
685 var end = start + line.length + 1;
686 var range = { start: start, end: end, line: i };
687
688 start = end;
689 return range;
690 });
691
692 var i = 0;
693
694 function rangeContains ( range, index ) {
695 return range.start <= index && index < range.end;
696 }
697
698 function getLocation ( range, index ) {
699 return { line: range.line, column: index - range.start };
700 }
701
702 return function locate ( index ) {
703 var range = lineRanges[i];
704
705 var d = index >= range.end ? 1 : -1;
706
707 while ( range ) {
708 if ( rangeContains( range, index ) ) { return getLocation( range, index ); }
709
710 i += d;
711 range = lineRanges[i];
712 }
713 };
714}
715
716function Mappings ( hires ) {
717 var this$1 = this;
718
719 var offsets = {
720 generatedCodeColumn: 0,
721 sourceIndex: 0,
722 sourceCodeLine: 0,
723 sourceCodeColumn: 0,
724 sourceCodeName: 0
725 };
726
727 var generatedCodeLine = 0;
728 var generatedCodeColumn = 0;
729
730 this.raw = [];
731 var rawSegments = this.raw[ generatedCodeLine ] = [];
732
733 var pending = null;
734
735 this.addEdit = function ( sourceIndex, content, original, loc, nameIndex ) {
736 if ( content.length ) {
737 rawSegments.push([
738 generatedCodeColumn,
739 sourceIndex,
740 loc.line,
741 loc.column,
742 nameIndex ]);
743 } else if ( pending ) {
744 rawSegments.push( pending );
745 }
746
747 this$1.advance( content );
748 pending = null;
749 };
750
751 this.addUneditedChunk = function ( sourceIndex, chunk, original, loc, sourcemapLocations ) {
752 var originalCharIndex = chunk.start;
753 var first = true;
754
755 while ( originalCharIndex < chunk.end ) {
756 if ( hires || first || sourcemapLocations[ originalCharIndex ] ) {
757 rawSegments.push([
758 generatedCodeColumn,
759 sourceIndex,
760 loc.line,
761 loc.column,
762 -1
763 ]);
764 }
765
766 if ( original[ originalCharIndex ] === '\n' ) {
767 loc.line += 1;
768 loc.column = 0;
769 generatedCodeLine += 1;
770 this$1.raw[ generatedCodeLine ] = rawSegments = [];
771 generatedCodeColumn = 0;
772 } else {
773 loc.column += 1;
774 generatedCodeColumn += 1;
775 }
776
777 originalCharIndex += 1;
778 first = false;
779 }
780
781 pending = [
782 generatedCodeColumn,
783 sourceIndex,
784 loc.line,
785 loc.column,
786 -1 ];
787 };
788
789 this.advance = function (str) {
790 if ( !str ) { return; }
791
792 var lines = str.split( '\n' );
793 var lastLine = lines.pop();
794
795 if ( lines.length ) {
796 generatedCodeLine += lines.length;
797 this$1.raw[ generatedCodeLine ] = rawSegments = [];
798 generatedCodeColumn = lastLine.length;
799 } else {
800 generatedCodeColumn += lastLine.length;
801 }
802 };
803
804 this.encode = function () {
805 return this$1.raw.map( function (segments) {
806 var generatedCodeColumn = 0;
807
808 return segments.map( function (segment) {
809 var arr = [
810 segment[0] - generatedCodeColumn,
811 segment[1] - offsets.sourceIndex,
812 segment[2] - offsets.sourceCodeLine,
813 segment[3] - offsets.sourceCodeColumn
814 ];
815
816 generatedCodeColumn = segment[0];
817 offsets.sourceIndex = segment[1];
818 offsets.sourceCodeLine = segment[2];
819 offsets.sourceCodeColumn = segment[3];
820
821 if ( ~segment[4] ) {
822 arr.push( segment[4] - offsets.sourceCodeName );
823 offsets.sourceCodeName = segment[4];
824 }
825
826 return encode( arr );
827 }).join( ',' );
828 }).join( ';' );
829 };
830}
831
832var Stats = function Stats () {
833 Object.defineProperties( this, {
834 startTimes: { value: {} }
835 });
836};
837
838Stats.prototype.time = function time ( label ) {
839 this.startTimes[ label ] = process.hrtime();
840};
841
842Stats.prototype.timeEnd = function timeEnd ( label ) {
843 var elapsed = process.hrtime( this.startTimes[ label ] );
844
845 if ( !this[ label ] ) { this[ label ] = 0; }
846 this[ label ] += elapsed[0] * 1e3 + elapsed[1] * 1e-6;
847};
848
849var warned = {
850 insertLeft: false,
851 insertRight: false,
852 storeName: false
853};
854
855function MagicString$1 ( string, options ) {
856 if ( options === void 0 ) options = {};
857
858 var chunk = new Chunk( 0, string.length, string );
859
860 Object.defineProperties( this, {
861 original: { writable: true, value: string },
862 outro: { writable: true, value: '' },
863 intro: { writable: true, value: '' },
864 firstChunk: { writable: true, value: chunk },
865 lastChunk: { writable: true, value: chunk },
866 lastSearchedChunk: { writable: true, value: chunk },
867 byStart: { writable: true, value: {} },
868 byEnd: { writable: true, value: {} },
869 filename: { writable: true, value: options.filename },
870 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
871 sourcemapLocations: { writable: true, value: {} },
872 storedNames: { writable: true, value: {} },
873 indentStr: { writable: true, value: guessIndent( string ) }
874 });
875
876 this.byStart[ 0 ] = chunk;
877 this.byEnd[ string.length ] = chunk;
878}
879
880MagicString$1.prototype = {
881 addSourcemapLocation: function addSourcemapLocation ( char ) {
882 this.sourcemapLocations[ char ] = true;
883 },
884
885 append: function append ( content ) {
886 if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
887
888 this.outro += content;
889 return this;
890 },
891
892 appendLeft: function appendLeft ( index, content ) {
893 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
894
895 this._split( index );
896
897 var chunk = this.byEnd[ index ];
898
899 if ( chunk ) {
900 chunk.appendLeft( content );
901 } else {
902 this.intro += content;
903 }
904
905 return this;
906 },
907
908 appendRight: function appendRight ( index, content ) {
909 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
910
911 this._split( index );
912
913 var chunk = this.byStart[ index ];
914
915 if ( chunk ) {
916 chunk.appendRight( content );
917 } else {
918 this.outro += content;
919 }
920
921 return this;
922 },
923
924 clone: function clone () {
925 var cloned = new MagicString$1( this.original, { filename: this.filename });
926
927 var originalChunk = this.firstChunk;
928 var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
929
930 while ( originalChunk ) {
931 cloned.byStart[ clonedChunk.start ] = clonedChunk;
932 cloned.byEnd[ clonedChunk.end ] = clonedChunk;
933
934 var nextOriginalChunk = originalChunk.next;
935 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
936
937 if ( nextClonedChunk ) {
938 clonedChunk.next = nextClonedChunk;
939 nextClonedChunk.previous = clonedChunk;
940
941 clonedChunk = nextClonedChunk;
942 }
943
944 originalChunk = nextOriginalChunk;
945 }
946
947 cloned.lastChunk = clonedChunk;
948
949 if ( this.indentExclusionRanges ) {
950 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
951 }
952
953 Object.keys( this.sourcemapLocations ).forEach( function (loc) {
954 cloned.sourcemapLocations[ loc ] = true;
955 });
956
957 return cloned;
958 },
959
960 generateMap: function generateMap ( options ) {
961 var this$1 = this;
962
963 options = options || {};
964
965 var sourceIndex = 0;
966 var names = Object.keys( this.storedNames );
967 var mappings = new Mappings( options.hires );
968
969 var locate = getLocator( this.original );
970
971 if ( this.intro ) {
972 mappings.advance( this.intro );
973 }
974
975 this.firstChunk.eachNext( function (chunk) {
976 var loc = locate( chunk.start );
977
978 if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
979
980 if ( chunk.edited ) {
981 mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
982 } else {
983 mappings.addUneditedChunk( sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations );
984 }
985
986 if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
987 });
988
989 var map = new SourceMap({
990 file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
991 sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ],
992 sourcesContent: options.includeContent ? [ this.original ] : [ null ],
993 names: names,
994 mappings: mappings.encode()
995 });
996 return map;
997 },
998
999 getIndentString: function getIndentString () {
1000 return this.indentStr === null ? '\t' : this.indentStr;
1001 },
1002
1003 indent: function indent ( indentStr, options ) {
1004 var this$1 = this;
1005
1006 var pattern = /^[^\r\n]/gm;
1007
1008 if ( isObject( indentStr ) ) {
1009 options = indentStr;
1010 indentStr = undefined;
1011 }
1012
1013 indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' );
1014
1015 if ( indentStr === '' ) { return this; } // noop
1016
1017 options = options || {};
1018
1019 // Process exclusion ranges
1020 var isExcluded = {};
1021
1022 if ( options.exclude ) {
1023 var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude;
1024 exclusions.forEach( function (exclusion) {
1025 for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) {
1026 isExcluded[i] = true;
1027 }
1028 });
1029 }
1030
1031 var shouldIndentNextCharacter = options.indentStart !== false;
1032 var replacer = function (match) {
1033 if ( shouldIndentNextCharacter ) { return ("" + indentStr + match); }
1034 shouldIndentNextCharacter = true;
1035 return match;
1036 };
1037
1038 this.intro = this.intro.replace( pattern, replacer );
1039
1040 var charIndex = 0;
1041
1042 var chunk = this.firstChunk;
1043
1044 while ( chunk ) {
1045 var end = chunk.end;
1046
1047 if ( chunk.edited ) {
1048 if ( !isExcluded[ charIndex ] ) {
1049 chunk.content = chunk.content.replace( pattern, replacer );
1050
1051 if ( chunk.content.length ) {
1052 shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n';
1053 }
1054 }
1055 } else {
1056 charIndex = chunk.start;
1057
1058 while ( charIndex < end ) {
1059 if ( !isExcluded[ charIndex ] ) {
1060 var char = this$1.original[ charIndex ];
1061
1062 if ( char === '\n' ) {
1063 shouldIndentNextCharacter = true;
1064 } else if ( char !== '\r' && shouldIndentNextCharacter ) {
1065 shouldIndentNextCharacter = false;
1066
1067 if ( charIndex === chunk.start ) {
1068 chunk.prependRight( indentStr );
1069 } else {
1070 this$1._splitChunk( chunk, charIndex );
1071 chunk = chunk.next;
1072 chunk.prependRight( indentStr );
1073 }
1074 }
1075 }
1076
1077 charIndex += 1;
1078 }
1079 }
1080
1081 charIndex = chunk.end;
1082 chunk = chunk.next;
1083 }
1084
1085 this.outro = this.outro.replace( pattern, replacer );
1086
1087 return this;
1088 },
1089
1090 insert: function insert () {
1091 throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' );
1092 },
1093
1094 insertLeft: function insertLeft ( index, content ) {
1095 if ( !warned.insertLeft ) {
1096 console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console
1097 warned.insertLeft = true;
1098 }
1099
1100 return this.appendLeft( index, content );
1101 },
1102
1103 insertRight: function insertRight ( index, content ) {
1104 if ( !warned.insertRight ) {
1105 console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console
1106 warned.insertRight = true;
1107 }
1108
1109 return this.prependRight( index, content );
1110 },
1111
1112 move: function move ( start, end, index ) {
1113 if ( index >= start && index <= end ) { throw new Error( 'Cannot move a selection inside itself' ); }
1114
1115 this._split( start );
1116 this._split( end );
1117 this._split( index );
1118
1119 var first = this.byStart[ start ];
1120 var last = this.byEnd[ end ];
1121
1122 var oldLeft = first.previous;
1123 var oldRight = last.next;
1124
1125 var newRight = this.byStart[ index ];
1126 if ( !newRight && last === this.lastChunk ) { return this; }
1127 var newLeft = newRight ? newRight.previous : this.lastChunk;
1128
1129 if ( oldLeft ) { oldLeft.next = oldRight; }
1130 if ( oldRight ) { oldRight.previous = oldLeft; }
1131
1132 if ( newLeft ) { newLeft.next = first; }
1133 if ( newRight ) { newRight.previous = last; }
1134
1135 if ( !first.previous ) { this.firstChunk = last.next; }
1136 if ( !last.next ) {
1137 this.lastChunk = first.previous;
1138 this.lastChunk.next = null;
1139 }
1140
1141 first.previous = newLeft;
1142 last.next = newRight || null;
1143
1144 if ( !newLeft ) { this.firstChunk = first; }
1145 if ( !newRight ) { this.lastChunk = last; }
1146
1147 return this;
1148 },
1149
1150 overwrite: function overwrite ( start, end, content, options ) {
1151 var this$1 = this;
1152
1153 if ( typeof content !== 'string' ) { throw new TypeError( 'replacement content must be a string' ); }
1154
1155 while ( start < 0 ) { start += this$1.original.length; }
1156 while ( end < 0 ) { end += this$1.original.length; }
1157
1158 if ( end > this.original.length ) { throw new Error( 'end is out of bounds' ); }
1159 if ( start === end ) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); }
1160
1161 this._split( start );
1162 this._split( end );
1163
1164 if ( options === true ) {
1165 if ( !warned.storeName ) {
1166 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
1167 warned.storeName = true;
1168 }
1169
1170 options = { storeName: true };
1171 }
1172 var storeName = options !== undefined ? options.storeName : false;
1173 var contentOnly = options !== undefined ? options.contentOnly : false;
1174
1175 if ( storeName ) {
1176 var original = this.original.slice( start, end );
1177 this.storedNames[ original ] = true;
1178 }
1179
1180 var first = this.byStart[ start ];
1181 var last = this.byEnd[ end ];
1182
1183 if ( first ) {
1184 if ( end > first.end && first.next !== this.byStart[ first.end ] ) {
1185 throw new Error( 'Cannot overwrite across a split point' );
1186 }
1187
1188 first.edit( content, storeName, contentOnly );
1189
1190 if ( first !== last ) {
1191 var chunk = first.next;
1192 while ( chunk !== last ) {
1193 chunk.edit( '', false );
1194 chunk = chunk.next;
1195 }
1196
1197 chunk.edit( '', false );
1198 }
1199 }
1200
1201 else {
1202 // must be inserting at the end
1203 var newChunk = new Chunk( start, end, '' ).edit( content, storeName );
1204
1205 // TODO last chunk in the array may not be the last chunk, if it's moved...
1206 last.next = newChunk;
1207 newChunk.previous = last;
1208 }
1209
1210 return this;
1211 },
1212
1213 prepend: function prepend ( content ) {
1214 if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); }
1215
1216 this.intro = content + this.intro;
1217 return this;
1218 },
1219
1220 prependLeft: function prependLeft ( index, content ) {
1221 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
1222
1223 this._split( index );
1224
1225 var chunk = this.byEnd[ index ];
1226
1227 if ( chunk ) {
1228 chunk.prependLeft( content );
1229 } else {
1230 this.intro = content + this.intro;
1231 }
1232
1233 return this;
1234 },
1235
1236 prependRight: function prependRight ( index, content ) {
1237 if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); }
1238
1239 this._split( index );
1240
1241 var chunk = this.byStart[ index ];
1242
1243 if ( chunk ) {
1244 chunk.prependRight( content );
1245 } else {
1246 this.outro = content + this.outro;
1247 }
1248
1249 return this;
1250 },
1251
1252 remove: function remove ( start, end ) {
1253 var this$1 = this;
1254
1255 while ( start < 0 ) { start += this$1.original.length; }
1256 while ( end < 0 ) { end += this$1.original.length; }
1257
1258 if ( start === end ) { return this; }
1259
1260 if ( start < 0 || end > this.original.length ) { throw new Error( 'Character is out of bounds' ); }
1261 if ( start > end ) { throw new Error( 'end must be greater than start' ); }
1262
1263 this._split( start );
1264 this._split( end );
1265
1266 var chunk = this.byStart[ start ];
1267
1268 while ( chunk ) {
1269 chunk.intro = '';
1270 chunk.outro = '';
1271 chunk.edit( '' );
1272
1273 chunk = end > chunk.end ? this$1.byStart[ chunk.end ] : null;
1274 }
1275
1276 return this;
1277 },
1278
1279 slice: function slice ( start, end ) {
1280 var this$1 = this;
1281 if ( start === void 0 ) start = 0;
1282 if ( end === void 0 ) end = this.original.length;
1283
1284 while ( start < 0 ) { start += this$1.original.length; }
1285 while ( end < 0 ) { end += this$1.original.length; }
1286
1287 var result = '';
1288
1289 // find start chunk
1290 var chunk = this.firstChunk;
1291 while ( chunk && ( chunk.start > start || chunk.end <= start ) ) {
1292
1293 // found end chunk before start
1294 if ( chunk.start < end && chunk.end >= end ) {
1295 return result;
1296 }
1297
1298 chunk = chunk.next;
1299 }
1300
1301 if ( chunk && chunk.edited && chunk.start !== start ) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1302
1303 var startChunk = chunk;
1304 while ( chunk ) {
1305 if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) {
1306 result += chunk.intro;
1307 }
1308
1309 var containsEnd = chunk.start < end && chunk.end >= end;
1310 if ( containsEnd && chunk.edited && chunk.end !== end ) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1311
1312 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1313 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1314
1315 result += chunk.content.slice( sliceStart, sliceEnd );
1316
1317 if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) {
1318 result += chunk.outro;
1319 }
1320
1321 if ( containsEnd ) {
1322 break;
1323 }
1324
1325 chunk = chunk.next;
1326 }
1327
1328 return result;
1329 },
1330
1331 // TODO deprecate this? not really very useful
1332 snip: function snip ( start, end ) {
1333 var clone = this.clone();
1334 clone.remove( 0, start );
1335 clone.remove( end, clone.original.length );
1336
1337 return clone;
1338 },
1339
1340 _split: function _split ( index ) {
1341 var this$1 = this;
1342
1343 if ( this.byStart[ index ] || this.byEnd[ index ] ) { return; }
1344
1345 var chunk = this.lastSearchedChunk;
1346 var searchForward = index > chunk.end;
1347
1348 while ( true ) {
1349 if ( chunk.contains( index ) ) { return this$1._splitChunk( chunk, index ); }
1350
1351 chunk = searchForward ?
1352 this$1.byStart[ chunk.end ] :
1353 this$1.byEnd[ chunk.start ];
1354 }
1355 },
1356
1357 _splitChunk: function _splitChunk ( chunk, index ) {
1358 if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements)
1359 var loc = getLocator( this.original )( index );
1360 throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") );
1361 }
1362
1363 var newChunk = chunk.split( index );
1364
1365 this.byEnd[ index ] = chunk;
1366 this.byStart[ index ] = newChunk;
1367 this.byEnd[ newChunk.end ] = newChunk;
1368
1369 if ( chunk === this.lastChunk ) { this.lastChunk = newChunk; }
1370
1371 this.lastSearchedChunk = chunk;
1372 return true;
1373 },
1374
1375 toString: function toString () {
1376 var str = this.intro;
1377
1378 var chunk = this.firstChunk;
1379 while ( chunk ) {
1380 str += chunk.toString();
1381 chunk = chunk.next;
1382 }
1383
1384 return str + this.outro;
1385 },
1386
1387 trimLines: function trimLines () {
1388 return this.trim('[\\r\\n]');
1389 },
1390
1391 trim: function trim ( charType ) {
1392 return this.trimStart( charType ).trimEnd( charType );
1393 },
1394
1395 trimEnd: function trimEnd ( charType ) {
1396 var this$1 = this;
1397
1398 var rx = new RegExp( ( charType || '\\s' ) + '+$' );
1399
1400 this.outro = this.outro.replace( rx, '' );
1401 if ( this.outro.length ) { return this; }
1402
1403 var chunk = this.lastChunk;
1404
1405 do {
1406 var end = chunk.end;
1407 var aborted = chunk.trimEnd( rx );
1408
1409 // if chunk was trimmed, we have a new lastChunk
1410 if ( chunk.end !== end ) {
1411 if ( this$1.lastChunk === chunk ) {
1412 this$1.lastChunk = chunk.next;
1413 }
1414
1415 this$1.byEnd[ chunk.end ] = chunk;
1416 this$1.byStart[ chunk.next.start ] = chunk.next;
1417 this$1.byEnd[ chunk.next.end ] = chunk.next;
1418 }
1419
1420 if ( aborted ) { return this$1; }
1421 chunk = chunk.previous;
1422 } while ( chunk );
1423
1424 return this;
1425 },
1426
1427 trimStart: function trimStart ( charType ) {
1428 var this$1 = this;
1429
1430 var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
1431
1432 this.intro = this.intro.replace( rx, '' );
1433 if ( this.intro.length ) { return this; }
1434
1435 var chunk = this.firstChunk;
1436
1437 do {
1438 var end = chunk.end;
1439 var aborted = chunk.trimStart( rx );
1440
1441 if ( chunk.end !== end ) {
1442 // special case...
1443 if ( chunk === this$1.lastChunk ) { this$1.lastChunk = chunk.next; }
1444
1445 this$1.byEnd[ chunk.end ] = chunk;
1446 this$1.byStart[ chunk.next.start ] = chunk.next;
1447 this$1.byEnd[ chunk.next.end ] = chunk.next;
1448 }
1449
1450 if ( aborted ) { return this$1; }
1451 chunk = chunk.next;
1452 } while ( chunk );
1453
1454 return this;
1455 }
1456};
1457
1458var hasOwnProp = Object.prototype.hasOwnProperty;
1459
1460function Bundle$2 ( options ) {
1461 if ( options === void 0 ) options = {};
1462
1463 this.intro = options.intro || '';
1464 this.separator = options.separator !== undefined ? options.separator : '\n';
1465
1466 this.sources = [];
1467
1468 this.uniqueSources = [];
1469 this.uniqueSourceIndexByFilename = {};
1470}
1471
1472Bundle$2.prototype = {
1473 addSource: function addSource ( source ) {
1474 if ( source instanceof MagicString$1 ) {
1475 return this.addSource({
1476 content: source,
1477 filename: source.filename,
1478 separator: this.separator
1479 });
1480 }
1481
1482 if ( !isObject( source ) || !source.content ) {
1483 throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' );
1484 }
1485
1486 [ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) {
1487 if ( !hasOwnProp.call( source, option ) ) { source[ option ] = source.content[ option ]; }
1488 });
1489
1490 if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up
1491 source.separator = this.separator;
1492 }
1493
1494 if ( source.filename ) {
1495 if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) {
1496 this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length;
1497 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1498 } else {
1499 var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ];
1500 if ( source.content.original !== uniqueSource.content ) {
1501 throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") );
1502 }
1503 }
1504 }
1505
1506 this.sources.push( source );
1507 return this;
1508 },
1509
1510 append: function append ( str, options ) {
1511 this.addSource({
1512 content: new MagicString$1( str ),
1513 separator: ( options && options.separator ) || ''
1514 });
1515
1516 return this;
1517 },
1518
1519 clone: function clone () {
1520 var bundle = new Bundle$2({
1521 intro: this.intro,
1522 separator: this.separator
1523 });
1524
1525 this.sources.forEach( function (source) {
1526 bundle.addSource({
1527 filename: source.filename,
1528 content: source.content.clone(),
1529 separator: source.separator
1530 });
1531 });
1532
1533 return bundle;
1534 },
1535
1536 generateMap: function generateMap ( options ) {
1537 var this$1 = this;
1538 if ( options === void 0 ) options = {};
1539
1540 var names = [];
1541 this.sources.forEach( function (source) {
1542 Object.keys( source.content.storedNames ).forEach( function (name) {
1543 if ( !~names.indexOf( name ) ) { names.push( name ); }
1544 });
1545 });
1546
1547 var mappings = new Mappings( options.hires );
1548
1549 if ( this.intro ) {
1550 mappings.advance( this.intro );
1551 }
1552
1553 this.sources.forEach( function ( source, i ) {
1554 if ( i > 0 ) {
1555 mappings.advance( this$1.separator );
1556 }
1557
1558 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[ source.filename ] : -1;
1559 var magicString = source.content;
1560 var locate = getLocator( magicString.original );
1561
1562 if ( magicString.intro ) {
1563 mappings.advance( magicString.intro );
1564 }
1565
1566 magicString.firstChunk.eachNext( function (chunk) {
1567 var loc = locate( chunk.start );
1568
1569 if ( chunk.intro.length ) { mappings.advance( chunk.intro ); }
1570
1571 if ( source.filename ) {
1572 if ( chunk.edited ) {
1573 mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 );
1574 } else {
1575 mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations );
1576 }
1577 }
1578
1579 else {
1580 mappings.advance( chunk.content );
1581 }
1582
1583 if ( chunk.outro.length ) { mappings.advance( chunk.outro ); }
1584 });
1585
1586 if ( magicString.outro ) {
1587 mappings.advance( magicString.outro );
1588 }
1589 });
1590
1591 return new SourceMap({
1592 file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ),
1593 sources: this.uniqueSources.map( function (source) {
1594 return options.file ? getRelativePath( options.file, source.filename ) : source.filename;
1595 }),
1596 sourcesContent: this.uniqueSources.map( function (source) {
1597 return options.includeContent ? source.content : null;
1598 }),
1599 names: names,
1600 mappings: mappings.encode()
1601 });
1602 },
1603
1604 getIndentString: function getIndentString () {
1605 var indentStringCounts = {};
1606
1607 this.sources.forEach( function (source) {
1608 var indentStr = source.content.indentStr;
1609
1610 if ( indentStr === null ) { return; }
1611
1612 if ( !indentStringCounts[ indentStr ] ) { indentStringCounts[ indentStr ] = 0; }
1613 indentStringCounts[ indentStr ] += 1;
1614 });
1615
1616 return ( Object.keys( indentStringCounts ).sort( function ( a, b ) {
1617 return indentStringCounts[a] - indentStringCounts[b];
1618 })[0] ) || '\t';
1619 },
1620
1621 indent: function indent ( indentStr ) {
1622 var this$1 = this;
1623
1624 if ( !arguments.length ) {
1625 indentStr = this.getIndentString();
1626 }
1627
1628 if ( indentStr === '' ) { return this; } // noop
1629
1630 var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n';
1631
1632 this.sources.forEach( function ( source, i ) {
1633 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1634 var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) );
1635
1636 source.content.indent( indentStr, {
1637 exclude: source.indentExclusionRanges,
1638 indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1639 });
1640
1641 // TODO this is a very slow way to determine this
1642 trailingNewline = source.content.toString().slice( 0, -1 ) === '\n';
1643 });
1644
1645 if ( this.intro ) {
1646 this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) {
1647 return index > 0 ? indentStr + match : match;
1648 });
1649 }
1650
1651 return this;
1652 },
1653
1654 prepend: function prepend ( str ) {
1655 this.intro = str + this.intro;
1656 return this;
1657 },
1658
1659 toString: function toString () {
1660 var this$1 = this;
1661
1662 var body = this.sources.map( function ( source, i ) {
1663 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1664 var str = ( i > 0 ? separator : '' ) + source.content.toString();
1665
1666 return str;
1667 }).join( '' );
1668
1669 return this.intro + body;
1670 },
1671
1672 trimLines: function trimLines () {
1673 return this.trim('[\\r\\n]');
1674 },
1675
1676 trim: function trim ( charType ) {
1677 return this.trimStart( charType ).trimEnd( charType );
1678 },
1679
1680 trimStart: function trimStart ( charType ) {
1681 var this$1 = this;
1682
1683 var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' );
1684 this.intro = this.intro.replace( rx, '' );
1685
1686 if ( !this.intro ) {
1687 var source;
1688 var i = 0;
1689
1690 do {
1691 source = this$1.sources[i];
1692
1693 if ( !source ) {
1694 break;
1695 }
1696
1697 source.content.trimStart( charType );
1698 i += 1;
1699 } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
1700 }
1701
1702 return this;
1703 },
1704
1705 trimEnd: function trimEnd ( charType ) {
1706 var this$1 = this;
1707
1708 var rx = new RegExp( ( charType || '\\s' ) + '+$' );
1709
1710 var source;
1711 var i = this.sources.length - 1;
1712
1713 do {
1714 source = this$1.sources[i];
1715
1716 if ( !source ) {
1717 this$1.intro = this$1.intro.replace( rx, '' );
1718 break;
1719 }
1720
1721 source.content.trimEnd( charType );
1722 i -= 1;
1723 } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source?
1724
1725 return this;
1726 }
1727};
1728
1729// Return the first non-falsy result from an array of
1730// maybe-sync, maybe-promise-returning functions
1731function first ( candidates ) {
1732 return function () {
1733 var args = [], len = arguments.length;
1734 while ( len-- ) args[ len ] = arguments[ len ];
1735
1736 return candidates.reduce( function ( promise, candidate ) {
1737 return promise.then( function (result) { return result != null ?
1738 result :
1739 Promise.resolve( candidate.apply( void 0, args ) ); } );
1740 }, Promise.resolve() );
1741 };
1742}
1743
1744function find ( array, fn ) {
1745 for ( var i = 0; i < array.length; i += 1 ) {
1746 if ( fn( array[i], i ) ) { return array[i]; }
1747 }
1748
1749 return null;
1750}
1751
1752// Reserved word lists for various dialects of the language
1753
1754var reservedWords = {
1755 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",
1756 5: "class enum extends super const export import",
1757 6: "enum",
1758 strict: "implements interface let package private protected public static yield",
1759 strictBind: "eval arguments"
1760};
1761
1762// And the keywords
1763
1764var 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";
1765
1766var keywords = {
1767 5: ecma5AndLessKeywords,
1768 6: ecma5AndLessKeywords + " const class extends export import super"
1769};
1770
1771// ## Character categories
1772
1773// Big ugly regular expressions that match characters in the
1774// whitespace, identifier, and identifier-start categories. These
1775// are only applied when a character is found to actually have a
1776// code point above 128.
1777// Generated by `bin/generate-identifier-regex.js`.
1778
1779var 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";
1780var 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";
1781
1782var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1783var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1784
1785nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1786
1787// These are a run-length and offset encoded representation of the
1788// >0xffff code points that are a valid part of identifiers. The
1789// offset starts at 0x10000, and each pair of numbers represents an
1790// offset to the next range, and then a size of the range. They were
1791// generated by bin/generate-identifier-regex.js
1792
1793// eslint-disable-next-line comma-spacing
1794var 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];
1795
1796// eslint-disable-next-line comma-spacing
1797var 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];
1798
1799// This has a complexity linear to the value of the code. The
1800// assumption is that looking up astral identifier characters is
1801// rare.
1802function isInAstralSet(code, set) {
1803 var pos = 0x10000;
1804 for (var i = 0; i < set.length; i += 2) {
1805 pos += set[i];
1806 if (pos > code) { return false }
1807 pos += set[i + 1];
1808 if (pos >= code) { return true }
1809 }
1810}
1811
1812// Test whether a given character code starts an identifier.
1813
1814function isIdentifierStart(code, astral) {
1815 if (code < 65) { return code === 36 }
1816 if (code < 91) { return true }
1817 if (code < 97) { return code === 95 }
1818 if (code < 123) { return true }
1819 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
1820 if (astral === false) { return false }
1821 return isInAstralSet(code, astralIdentifierStartCodes)
1822}
1823
1824// Test whether a given character is part of an identifier.
1825
1826function isIdentifierChar(code, astral) {
1827 if (code < 48) { return code === 36 }
1828 if (code < 58) { return true }
1829 if (code < 65) { return false }
1830 if (code < 91) { return true }
1831 if (code < 97) { return code === 95 }
1832 if (code < 123) { return true }
1833 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
1834 if (astral === false) { return false }
1835 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
1836}
1837
1838// ## Token types
1839
1840// The assignment of fine-grained, information-carrying type objects
1841// allows the tokenizer to store the information it has about a
1842// token in a way that is very cheap for the parser to look up.
1843
1844// All token type variables start with an underscore, to make them
1845// easy to recognize.
1846
1847// The `beforeExpr` property is used to disambiguate between regular
1848// expressions and divisions. It is set on all token types that can
1849// be followed by an expression (thus, a slash after them would be a
1850// regular expression).
1851//
1852// The `startsExpr` property is used to check if the token ends a
1853// `yield` expression. It is set on all token types that either can
1854// directly start an expression (like a quotation mark) or can
1855// continue an expression (like the body of a string).
1856//
1857// `isLoop` marks a keyword as starting a loop, which is important
1858// to know when parsing a label, in order to allow or disallow
1859// continue jumps to that label.
1860
1861var TokenType = function TokenType(label, conf) {
1862 if ( conf === void 0 ) { conf = {}; }
1863
1864 this.label = label;
1865 this.keyword = conf.keyword;
1866 this.beforeExpr = !!conf.beforeExpr;
1867 this.startsExpr = !!conf.startsExpr;
1868 this.isLoop = !!conf.isLoop;
1869 this.isAssign = !!conf.isAssign;
1870 this.prefix = !!conf.prefix;
1871 this.postfix = !!conf.postfix;
1872 this.binop = conf.binop || null;
1873 this.updateContext = null;
1874};
1875
1876function binop(name, prec) {
1877 return new TokenType(name, {beforeExpr: true, binop: prec})
1878}
1879var beforeExpr = {beforeExpr: true};
1880var startsExpr = {startsExpr: true};
1881
1882// Map keyword names to token types.
1883
1884var keywords$1 = {};
1885
1886// Succinct definitions of keyword token types
1887function kw(name, options) {
1888 if ( options === void 0 ) { options = {}; }
1889
1890 options.keyword = name;
1891 return keywords$1[name] = new TokenType(name, options)
1892}
1893
1894var types = {
1895 num: new TokenType("num", startsExpr),
1896 regexp: new TokenType("regexp", startsExpr),
1897 string: new TokenType("string", startsExpr),
1898 name: new TokenType("name", startsExpr),
1899 eof: new TokenType("eof"),
1900
1901 // Punctuation token types.
1902 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
1903 bracketR: new TokenType("]"),
1904 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
1905 braceR: new TokenType("}"),
1906 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
1907 parenR: new TokenType(")"),
1908 comma: new TokenType(",", beforeExpr),
1909 semi: new TokenType(";", beforeExpr),
1910 colon: new TokenType(":", beforeExpr),
1911 dot: new TokenType("."),
1912 question: new TokenType("?", beforeExpr),
1913 arrow: new TokenType("=>", beforeExpr),
1914 template: new TokenType("template"),
1915 invalidTemplate: new TokenType("invalidTemplate"),
1916 ellipsis: new TokenType("...", beforeExpr),
1917 backQuote: new TokenType("`", startsExpr),
1918 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
1919
1920 // Operators. These carry several kinds of properties to help the
1921 // parser use them properly (the presence of these properties is
1922 // what categorizes them as operators).
1923 //
1924 // `binop`, when present, specifies that this operator is a binary
1925 // operator, and will refer to its precedence.
1926 //
1927 // `prefix` and `postfix` mark the operator as a prefix or postfix
1928 // unary operator.
1929 //
1930 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1931 // binary operators with a very low precedence, that should result
1932 // in AssignmentExpression nodes.
1933
1934 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
1935 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
1936 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
1937 prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
1938 logicalOR: binop("||", 1),
1939 logicalAND: binop("&&", 2),
1940 bitwiseOR: binop("|", 3),
1941 bitwiseXOR: binop("^", 4),
1942 bitwiseAND: binop("&", 5),
1943 equality: binop("==/!=", 6),
1944 relational: binop("</>", 7),
1945 bitShift: binop("<</>>", 8),
1946 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
1947 modulo: binop("%", 10),
1948 star: binop("*", 10),
1949 slash: binop("/", 10),
1950 starstar: new TokenType("**", {beforeExpr: true}),
1951
1952 // Keyword token types.
1953 _break: kw("break"),
1954 _case: kw("case", beforeExpr),
1955 _catch: kw("catch"),
1956 _continue: kw("continue"),
1957 _debugger: kw("debugger"),
1958 _default: kw("default", beforeExpr),
1959 _do: kw("do", {isLoop: true, beforeExpr: true}),
1960 _else: kw("else", beforeExpr),
1961 _finally: kw("finally"),
1962 _for: kw("for", {isLoop: true}),
1963 _function: kw("function", startsExpr),
1964 _if: kw("if"),
1965 _return: kw("return", beforeExpr),
1966 _switch: kw("switch"),
1967 _throw: kw("throw", beforeExpr),
1968 _try: kw("try"),
1969 _var: kw("var"),
1970 _const: kw("const"),
1971 _while: kw("while", {isLoop: true}),
1972 _with: kw("with"),
1973 _new: kw("new", {beforeExpr: true, startsExpr: true}),
1974 _this: kw("this", startsExpr),
1975 _super: kw("super", startsExpr),
1976 _class: kw("class", startsExpr),
1977 _extends: kw("extends", beforeExpr),
1978 _export: kw("export"),
1979 _import: kw("import"),
1980 _null: kw("null", startsExpr),
1981 _true: kw("true", startsExpr),
1982 _false: kw("false", startsExpr),
1983 _in: kw("in", {beforeExpr: true, binop: 7}),
1984 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
1985 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
1986 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
1987 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
1988};
1989
1990// Matches a whole line break (where CRLF is considered a single
1991// line break). Used to count lines.
1992
1993var lineBreak = /\r\n?|\n|\u2028|\u2029/;
1994var lineBreakG = new RegExp(lineBreak.source, "g");
1995
1996function isNewLine(code) {
1997 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
1998}
1999
2000var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
2001
2002var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
2003
2004var ref = Object.prototype;
2005var hasOwnProperty = ref.hasOwnProperty;
2006var toString = ref.toString;
2007
2008// Checks if an object has a property.
2009
2010function has(obj, propName) {
2011 return hasOwnProperty.call(obj, propName)
2012}
2013
2014var isArray = Array.isArray || (function (obj) { return (
2015 toString.call(obj) === "[object Array]"
2016); });
2017
2018// These are used when `options.locations` is on, for the
2019// `startLoc` and `endLoc` properties.
2020
2021var Position = function Position(line, col) {
2022 this.line = line;
2023 this.column = col;
2024};
2025
2026Position.prototype.offset = function offset (n) {
2027 return new Position(this.line, this.column + n)
2028};
2029
2030var SourceLocation = function SourceLocation(p, start, end) {
2031 this.start = start;
2032 this.end = end;
2033 if (p.sourceFile !== null) { this.source = p.sourceFile; }
2034};
2035
2036// The `getLineInfo` function is mostly useful when the
2037// `locations` option is off (for performance reasons) and you
2038// want to find the line/column position for a given character
2039// offset. `input` should be the code string that the offset refers
2040// into.
2041
2042function getLineInfo(input, offset) {
2043 for (var line = 1, cur = 0;;) {
2044 lineBreakG.lastIndex = cur;
2045 var match = lineBreakG.exec(input);
2046 if (match && match.index < offset) {
2047 ++line;
2048 cur = match.index + match[0].length;
2049 } else {
2050 return new Position(line, offset - cur)
2051 }
2052 }
2053}
2054
2055// A second optional argument can be given to further configure
2056// the parser process. These options are recognized:
2057
2058var defaultOptions = {
2059 // `ecmaVersion` indicates the ECMAScript version to parse. Must
2060 // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
2061 // for strict mode, the set of reserved words, and support for
2062 // new syntax features. The default is 7.
2063 ecmaVersion: 7,
2064 // `sourceType` indicates the mode the code should be parsed in.
2065 // Can be either `"script"` or `"module"`. This influences global
2066 // strict mode and parsing of `import` and `export` declarations.
2067 sourceType: "script",
2068 // `onInsertedSemicolon` can be a callback that will be called
2069 // when a semicolon is automatically inserted. It will be passed
2070 // th position of the comma as an offset, and if `locations` is
2071 // enabled, it is given the location as a `{line, column}` object
2072 // as second argument.
2073 onInsertedSemicolon: null,
2074 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
2075 // trailing commas.
2076 onTrailingComma: null,
2077 // By default, reserved words are only enforced if ecmaVersion >= 5.
2078 // Set `allowReserved` to a boolean value to explicitly turn this on
2079 // an off. When this option has the value "never", reserved words
2080 // and keywords can also not be used as property names.
2081 allowReserved: null,
2082 // When enabled, a return at the top level is not considered an
2083 // error.
2084 allowReturnOutsideFunction: false,
2085 // When enabled, import/export statements are not constrained to
2086 // appearing at the top of the program.
2087 allowImportExportEverywhere: false,
2088 // When enabled, hashbang directive in the beginning of file
2089 // is allowed and treated as a line comment.
2090 allowHashBang: false,
2091 // When `locations` is on, `loc` properties holding objects with
2092 // `start` and `end` properties in `{line, column}` form (with
2093 // line being 1-based and column 0-based) will be attached to the
2094 // nodes.
2095 locations: false,
2096 // A function can be passed as `onToken` option, which will
2097 // cause Acorn to call that function with object in the same
2098 // format as tokens returned from `tokenizer().getToken()`. Note
2099 // that you are not allowed to call the parser from the
2100 // callback—that will corrupt its internal state.
2101 onToken: null,
2102 // A function can be passed as `onComment` option, which will
2103 // cause Acorn to call that function with `(block, text, start,
2104 // end)` parameters whenever a comment is skipped. `block` is a
2105 // boolean indicating whether this is a block (`/* */`) comment,
2106 // `text` is the content of the comment, and `start` and `end` are
2107 // character offsets that denote the start and end of the comment.
2108 // When the `locations` option is on, two more parameters are
2109 // passed, the full `{line, column}` locations of the start and
2110 // end of the comments. Note that you are not allowed to call the
2111 // parser from the callback—that will corrupt its internal state.
2112 onComment: null,
2113 // Nodes have their start and end characters offsets recorded in
2114 // `start` and `end` properties (directly on the node, rather than
2115 // the `loc` object, which holds line/column data. To also add a
2116 // [semi-standardized][range] `range` property holding a `[start,
2117 // end]` array with the same numbers, set the `ranges` option to
2118 // `true`.
2119 //
2120 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
2121 ranges: false,
2122 // It is possible to parse multiple files into a single AST by
2123 // passing the tree produced by parsing the first file as
2124 // `program` option in subsequent parses. This will add the
2125 // toplevel forms of the parsed file to the `Program` (top) node
2126 // of an existing parse tree.
2127 program: null,
2128 // When `locations` is on, you can pass this to record the source
2129 // file in every node's `loc` object.
2130 sourceFile: null,
2131 // This value, if given, is stored in every node, whether
2132 // `locations` is on or off.
2133 directSourceFile: null,
2134 // When enabled, parenthesized expressions are represented by
2135 // (non-standard) ParenthesizedExpression nodes
2136 preserveParens: false,
2137 plugins: {}
2138};
2139
2140// Interpret and default an options object
2141
2142function getOptions(opts) {
2143 var options = {};
2144
2145 for (var opt in defaultOptions)
2146 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
2147
2148 if (options.ecmaVersion >= 2015)
2149 { options.ecmaVersion -= 2009; }
2150
2151 if (options.allowReserved == null)
2152 { options.allowReserved = options.ecmaVersion < 5; }
2153
2154 if (isArray(options.onToken)) {
2155 var tokens = options.onToken;
2156 options.onToken = function (token) { return tokens.push(token); };
2157 }
2158 if (isArray(options.onComment))
2159 { options.onComment = pushComment(options, options.onComment); }
2160
2161 return options
2162}
2163
2164function pushComment(options, array) {
2165 return function(block, text, start, end, startLoc, endLoc) {
2166 var comment = {
2167 type: block ? "Block" : "Line",
2168 value: text,
2169 start: start,
2170 end: end
2171 };
2172 if (options.locations)
2173 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
2174 if (options.ranges)
2175 { comment.range = [start, end]; }
2176 array.push(comment);
2177 }
2178}
2179
2180// Registered plugins
2181var plugins = {};
2182
2183function keywordRegexp(words) {
2184 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
2185}
2186
2187var Parser = function Parser(options, input, startPos) {
2188 this.options = options = getOptions(options);
2189 this.sourceFile = options.sourceFile;
2190 this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
2191 var reserved = "";
2192 if (!options.allowReserved) {
2193 for (var v = options.ecmaVersion;; v--)
2194 { if (reserved = reservedWords[v]) { break } }
2195 if (options.sourceType == "module") { reserved += " await"; }
2196 }
2197 this.reservedWords = keywordRegexp(reserved);
2198 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
2199 this.reservedWordsStrict = keywordRegexp(reservedStrict);
2200 this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind);
2201 this.input = String(input);
2202
2203 // Used to signal to callers of `readWord1` whether the word
2204 // contained any escape sequences. This is needed because words with
2205 // escape sequences must not be interpreted as keywords.
2206 this.containsEsc = false;
2207
2208 // Load plugins
2209 this.loadPlugins(options.plugins);
2210
2211 // Set up token state
2212
2213 // The current position of the tokenizer in the input.
2214 if (startPos) {
2215 this.pos = startPos;
2216 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
2217 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
2218 } else {
2219 this.pos = this.lineStart = 0;
2220 this.curLine = 1;
2221 }
2222
2223 // Properties of the current token:
2224 // Its type
2225 this.type = types.eof;
2226 // For tokens that include more information than their type, the value
2227 this.value = null;
2228 // Its start and end offset
2229 this.start = this.end = this.pos;
2230 // And, if locations are used, the {line, column} object
2231 // corresponding to those offsets
2232 this.startLoc = this.endLoc = this.curPosition();
2233
2234 // Position information for the previous token
2235 this.lastTokEndLoc = this.lastTokStartLoc = null;
2236 this.lastTokStart = this.lastTokEnd = this.pos;
2237
2238 // The context stack is used to superficially track syntactic
2239 // context to predict whether a regular expression is allowed in a
2240 // given position.
2241 this.context = this.initialContext();
2242 this.exprAllowed = true;
2243
2244 // Figure out if it's a module code.
2245 this.inModule = options.sourceType === "module";
2246 this.strict = this.inModule || this.strictDirective(this.pos);
2247
2248 // Used to signify the start of a potential arrow function
2249 this.potentialArrowAt = -1;
2250
2251 // Flags to track whether we are in a function, a generator, an async function.
2252 this.inFunction = this.inGenerator = this.inAsync = false;
2253 // Positions to delayed-check that yield/await does not exist in default parameters.
2254 this.yieldPos = this.awaitPos = 0;
2255 // Labels in scope.
2256 this.labels = [];
2257
2258 // If enabled, skip leading hashbang line.
2259 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
2260 { this.skipLineComment(2); }
2261
2262 // Scope tracking for duplicate variable names (see scope.js)
2263 this.scopeStack = [];
2264 this.enterFunctionScope();
2265};
2266
2267// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
2268Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
2269Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
2270
2271Parser.prototype.extend = function extend (name, f) {
2272 this[name] = f(this[name]);
2273};
2274
2275Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
2276 var this$1 = this;
2277
2278 for (var name in pluginConfigs) {
2279 var plugin = plugins[name];
2280 if (!plugin) { throw new Error("Plugin '" + name + "' not found") }
2281 plugin(this$1, pluginConfigs[name]);
2282 }
2283};
2284
2285Parser.prototype.parse = function parse () {
2286 var node = this.options.program || this.startNode();
2287 this.nextToken();
2288 return this.parseTopLevel(node)
2289};
2290
2291var pp = Parser.prototype;
2292
2293// ## Parser utilities
2294
2295var literal = /^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/;
2296pp.strictDirective = function(start) {
2297 var this$1 = this;
2298
2299 for (;;) {
2300 skipWhiteSpace.lastIndex = start;
2301 start += skipWhiteSpace.exec(this$1.input)[0].length;
2302 var match = literal.exec(this$1.input.slice(start));
2303 if (!match) { return false }
2304 if ((match[1] || match[2]) == "use strict") { return true }
2305 start += match[0].length;
2306 }
2307};
2308
2309// Predicate that tests whether the next token is of the given
2310// type, and if yes, consumes it as a side effect.
2311
2312pp.eat = function(type) {
2313 if (this.type === type) {
2314 this.next();
2315 return true
2316 } else {
2317 return false
2318 }
2319};
2320
2321// Tests whether parsed token is a contextual keyword.
2322
2323pp.isContextual = function(name) {
2324 return this.type === types.name && this.value === name
2325};
2326
2327// Consumes contextual keyword if possible.
2328
2329pp.eatContextual = function(name) {
2330 return this.value === name && this.eat(types.name)
2331};
2332
2333// Asserts that following token is given contextual keyword.
2334
2335pp.expectContextual = function(name) {
2336 if (!this.eatContextual(name)) { this.unexpected(); }
2337};
2338
2339// Test whether a semicolon can be inserted at the current position.
2340
2341pp.canInsertSemicolon = function() {
2342 return this.type === types.eof ||
2343 this.type === types.braceR ||
2344 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
2345};
2346
2347pp.insertSemicolon = function() {
2348 if (this.canInsertSemicolon()) {
2349 if (this.options.onInsertedSemicolon)
2350 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
2351 return true
2352 }
2353};
2354
2355// Consume a semicolon, or, failing that, see if we are allowed to
2356// pretend that there is a semicolon at this position.
2357
2358pp.semicolon = function() {
2359 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
2360};
2361
2362pp.afterTrailingComma = function(tokType, notNext) {
2363 if (this.type == tokType) {
2364 if (this.options.onTrailingComma)
2365 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
2366 if (!notNext)
2367 { this.next(); }
2368 return true
2369 }
2370};
2371
2372// Expect a token of a given type. If found, consume it, otherwise,
2373// raise an unexpected token error.
2374
2375pp.expect = function(type) {
2376 this.eat(type) || this.unexpected();
2377};
2378
2379// Raise an unexpected token error.
2380
2381pp.unexpected = function(pos) {
2382 this.raise(pos != null ? pos : this.start, "Unexpected token");
2383};
2384
2385function DestructuringErrors() {
2386 this.shorthandAssign =
2387 this.trailingComma =
2388 this.parenthesizedAssign =
2389 this.parenthesizedBind =
2390 -1;
2391}
2392
2393pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
2394 if (!refDestructuringErrors) { return }
2395 if (refDestructuringErrors.trailingComma > -1)
2396 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
2397 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
2398 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
2399};
2400
2401pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
2402 var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1;
2403 if (!andThrow) { return pos >= 0 }
2404 if (pos > -1) { this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); }
2405};
2406
2407pp.checkYieldAwaitInDefaultParams = function() {
2408 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
2409 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
2410 if (this.awaitPos)
2411 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
2412};
2413
2414pp.isSimpleAssignTarget = function(expr) {
2415 if (expr.type === "ParenthesizedExpression")
2416 { return this.isSimpleAssignTarget(expr.expression) }
2417 return expr.type === "Identifier" || expr.type === "MemberExpression"
2418};
2419
2420var pp$1 = Parser.prototype;
2421
2422// ### Statement parsing
2423
2424// Parse a program. Initializes the parser, reads any number of
2425// statements, and wraps them in a Program node. Optionally takes a
2426// `program` argument. If present, the statements will be appended
2427// to its body instead of creating a new node.
2428
2429pp$1.parseTopLevel = function(node) {
2430 var this$1 = this;
2431
2432 var exports = {};
2433 if (!node.body) { node.body = []; }
2434 while (this.type !== types.eof) {
2435 var stmt = this$1.parseStatement(true, true, exports);
2436 node.body.push(stmt);
2437 }
2438 this.next();
2439 if (this.options.ecmaVersion >= 6) {
2440 node.sourceType = this.options.sourceType;
2441 }
2442 return this.finishNode(node, "Program")
2443};
2444
2445var loopLabel = {kind: "loop"};
2446var switchLabel = {kind: "switch"};
2447
2448pp$1.isLet = function() {
2449 if (this.type !== types.name || this.options.ecmaVersion < 6 || this.value != "let") { return false }
2450 skipWhiteSpace.lastIndex = this.pos;
2451 var skip = skipWhiteSpace.exec(this.input);
2452 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
2453 if (nextCh === 91 || nextCh == 123) { return true } // '{' and '['
2454 if (isIdentifierStart(nextCh, true)) {
2455 var pos = next + 1;
2456 while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
2457 var ident = this.input.slice(next, pos);
2458 if (!this.isKeyword(ident)) { return true }
2459 }
2460 return false
2461};
2462
2463// check 'async [no LineTerminator here] function'
2464// - 'async /*foo*/ function' is OK.
2465// - 'async /*\n*/ function' is invalid.
2466pp$1.isAsyncFunction = function() {
2467 if (this.type !== types.name || this.options.ecmaVersion < 8 || this.value != "async")
2468 { return false }
2469
2470 skipWhiteSpace.lastIndex = this.pos;
2471 var skip = skipWhiteSpace.exec(this.input);
2472 var next = this.pos + skip[0].length;
2473 return !lineBreak.test(this.input.slice(this.pos, next)) &&
2474 this.input.slice(next, next + 8) === "function" &&
2475 (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
2476};
2477
2478// Parse a single statement.
2479//
2480// If expecting a statement and finding a slash operator, parse a
2481// regular expression literal. This is to handle cases like
2482// `if (foo) /blah/.exec(foo)`, where looking at the previous token
2483// does not help.
2484
2485pp$1.parseStatement = function(declaration, topLevel, exports) {
2486 var starttype = this.type, node = this.startNode(), kind;
2487
2488 if (this.isLet()) {
2489 starttype = types._var;
2490 kind = "let";
2491 }
2492
2493 // Most types of statements are recognized by the keyword they
2494 // start with. Many are trivial to parse, some require a bit of
2495 // complexity.
2496
2497 switch (starttype) {
2498 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
2499 case types._debugger: return this.parseDebuggerStatement(node)
2500 case types._do: return this.parseDoStatement(node)
2501 case types._for: return this.parseForStatement(node)
2502 case types._function:
2503 if (!declaration && this.options.ecmaVersion >= 6) { this.unexpected(); }
2504 return this.parseFunctionStatement(node, false)
2505 case types._class:
2506 if (!declaration) { this.unexpected(); }
2507 return this.parseClass(node, true)
2508 case types._if: return this.parseIfStatement(node)
2509 case types._return: return this.parseReturnStatement(node)
2510 case types._switch: return this.parseSwitchStatement(node)
2511 case types._throw: return this.parseThrowStatement(node)
2512 case types._try: return this.parseTryStatement(node)
2513 case types._const: case types._var:
2514 kind = kind || this.value;
2515 if (!declaration && kind != "var") { this.unexpected(); }
2516 return this.parseVarStatement(node, kind)
2517 case types._while: return this.parseWhileStatement(node)
2518 case types._with: return this.parseWithStatement(node)
2519 case types.braceL: return this.parseBlock()
2520 case types.semi: return this.parseEmptyStatement(node)
2521 case types._export:
2522 case types._import:
2523 if (!this.options.allowImportExportEverywhere) {
2524 if (!topLevel)
2525 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
2526 if (!this.inModule)
2527 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
2528 }
2529 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
2530
2531 // If the statement does not start with a statement keyword or a
2532 // brace, it's an ExpressionStatement or LabeledStatement. We
2533 // simply start parsing an expression, and afterwards, if the
2534 // next token is a colon and the expression was a simple
2535 // Identifier node, we switch to interpreting it as a label.
2536 default:
2537 if (this.isAsyncFunction() && declaration) {
2538 this.next();
2539 return this.parseFunctionStatement(node, true)
2540 }
2541
2542 var maybeName = this.value, expr = this.parseExpression();
2543 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
2544 { return this.parseLabeledStatement(node, maybeName, expr) }
2545 else { return this.parseExpressionStatement(node, expr) }
2546 }
2547};
2548
2549pp$1.parseBreakContinueStatement = function(node, keyword) {
2550 var this$1 = this;
2551
2552 var isBreak = keyword == "break";
2553 this.next();
2554 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
2555 else if (this.type !== types.name) { this.unexpected(); }
2556 else {
2557 node.label = this.parseIdent();
2558 this.semicolon();
2559 }
2560
2561 // Verify that there is an actual destination to break or
2562 // continue to.
2563 var i = 0;
2564 for (; i < this.labels.length; ++i) {
2565 var lab = this$1.labels[i];
2566 if (node.label == null || lab.name === node.label.name) {
2567 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
2568 if (node.label && isBreak) { break }
2569 }
2570 }
2571 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
2572 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
2573};
2574
2575pp$1.parseDebuggerStatement = function(node) {
2576 this.next();
2577 this.semicolon();
2578 return this.finishNode(node, "DebuggerStatement")
2579};
2580
2581pp$1.parseDoStatement = function(node) {
2582 this.next();
2583 this.labels.push(loopLabel);
2584 node.body = this.parseStatement(false);
2585 this.labels.pop();
2586 this.expect(types._while);
2587 node.test = this.parseParenExpression();
2588 if (this.options.ecmaVersion >= 6)
2589 { this.eat(types.semi); }
2590 else
2591 { this.semicolon(); }
2592 return this.finishNode(node, "DoWhileStatement")
2593};
2594
2595// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
2596// loop is non-trivial. Basically, we have to parse the init `var`
2597// statement or expression, disallowing the `in` operator (see
2598// the second parameter to `parseExpression`), and then check
2599// whether the next token is `in` or `of`. When there is no init
2600// part (semicolon immediately after the opening parenthesis), it
2601// is a regular `for` loop.
2602
2603pp$1.parseForStatement = function(node) {
2604 this.next();
2605 this.labels.push(loopLabel);
2606 this.enterLexicalScope();
2607 this.expect(types.parenL);
2608 if (this.type === types.semi) { return this.parseFor(node, null) }
2609 var isLet = this.isLet();
2610 if (this.type === types._var || this.type === types._const || isLet) {
2611 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
2612 this.next();
2613 this.parseVar(init$1, true, kind);
2614 this.finishNode(init$1, "VariableDeclaration");
2615 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
2616 !(kind !== "var" && init$1.declarations[0].init))
2617 { return this.parseForIn(node, init$1) }
2618 return this.parseFor(node, init$1)
2619 }
2620 var refDestructuringErrors = new DestructuringErrors;
2621 var init = this.parseExpression(true, refDestructuringErrors);
2622 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
2623 this.toAssignable(init);
2624 this.checkLVal(init);
2625 this.checkPatternErrors(refDestructuringErrors, true);
2626 return this.parseForIn(node, init)
2627 } else {
2628 this.checkExpressionErrors(refDestructuringErrors, true);
2629 }
2630 return this.parseFor(node, init)
2631};
2632
2633pp$1.parseFunctionStatement = function(node, isAsync) {
2634 this.next();
2635 return this.parseFunction(node, true, false, isAsync)
2636};
2637
2638pp$1.isFunction = function() {
2639 return this.type === types._function || this.isAsyncFunction()
2640};
2641
2642pp$1.parseIfStatement = function(node) {
2643 this.next();
2644 node.test = this.parseParenExpression();
2645 // allow function declarations in branches, but only in non-strict mode
2646 node.consequent = this.parseStatement(!this.strict && this.isFunction());
2647 node.alternate = this.eat(types._else) ? this.parseStatement(!this.strict && this.isFunction()) : null;
2648 return this.finishNode(node, "IfStatement")
2649};
2650
2651pp$1.parseReturnStatement = function(node) {
2652 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
2653 { this.raise(this.start, "'return' outside of function"); }
2654 this.next();
2655
2656 // In `return` (and `break`/`continue`), the keywords with
2657 // optional arguments, we eagerly look for a semicolon or the
2658 // possibility to insert one.
2659
2660 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
2661 else { node.argument = this.parseExpression(); this.semicolon(); }
2662 return this.finishNode(node, "ReturnStatement")
2663};
2664
2665pp$1.parseSwitchStatement = function(node) {
2666 var this$1 = this;
2667
2668 this.next();
2669 node.discriminant = this.parseParenExpression();
2670 node.cases = [];
2671 this.expect(types.braceL);
2672 this.labels.push(switchLabel);
2673 this.enterLexicalScope();
2674
2675 // Statements under must be grouped (by label) in SwitchCase
2676 // nodes. `cur` is used to keep the node that we are currently
2677 // adding statements to.
2678
2679 var cur;
2680 for (var sawDefault = false; this.type != types.braceR;) {
2681 if (this$1.type === types._case || this$1.type === types._default) {
2682 var isCase = this$1.type === types._case;
2683 if (cur) { this$1.finishNode(cur, "SwitchCase"); }
2684 node.cases.push(cur = this$1.startNode());
2685 cur.consequent = [];
2686 this$1.next();
2687 if (isCase) {
2688 cur.test = this$1.parseExpression();
2689 } else {
2690 if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); }
2691 sawDefault = true;
2692 cur.test = null;
2693 }
2694 this$1.expect(types.colon);
2695 } else {
2696 if (!cur) { this$1.unexpected(); }
2697 cur.consequent.push(this$1.parseStatement(true));
2698 }
2699 }
2700 this.exitLexicalScope();
2701 if (cur) { this.finishNode(cur, "SwitchCase"); }
2702 this.next(); // Closing brace
2703 this.labels.pop();
2704 return this.finishNode(node, "SwitchStatement")
2705};
2706
2707pp$1.parseThrowStatement = function(node) {
2708 this.next();
2709 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
2710 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
2711 node.argument = this.parseExpression();
2712 this.semicolon();
2713 return this.finishNode(node, "ThrowStatement")
2714};
2715
2716// Reused empty array added for node fields that are always empty.
2717
2718var empty = [];
2719
2720pp$1.parseTryStatement = function(node) {
2721 this.next();
2722 node.block = this.parseBlock();
2723 node.handler = null;
2724 if (this.type === types._catch) {
2725 var clause = this.startNode();
2726 this.next();
2727 this.expect(types.parenL);
2728 clause.param = this.parseBindingAtom();
2729 this.enterLexicalScope();
2730 this.checkLVal(clause.param, "let");
2731 this.expect(types.parenR);
2732 clause.body = this.parseBlock(false);
2733 this.exitLexicalScope();
2734 node.handler = this.finishNode(clause, "CatchClause");
2735 }
2736 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
2737 if (!node.handler && !node.finalizer)
2738 { this.raise(node.start, "Missing catch or finally clause"); }
2739 return this.finishNode(node, "TryStatement")
2740};
2741
2742pp$1.parseVarStatement = function(node, kind) {
2743 this.next();
2744 this.parseVar(node, false, kind);
2745 this.semicolon();
2746 return this.finishNode(node, "VariableDeclaration")
2747};
2748
2749pp$1.parseWhileStatement = function(node) {
2750 this.next();
2751 node.test = this.parseParenExpression();
2752 this.labels.push(loopLabel);
2753 node.body = this.parseStatement(false);
2754 this.labels.pop();
2755 return this.finishNode(node, "WhileStatement")
2756};
2757
2758pp$1.parseWithStatement = function(node) {
2759 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
2760 this.next();
2761 node.object = this.parseParenExpression();
2762 node.body = this.parseStatement(false);
2763 return this.finishNode(node, "WithStatement")
2764};
2765
2766pp$1.parseEmptyStatement = function(node) {
2767 this.next();
2768 return this.finishNode(node, "EmptyStatement")
2769};
2770
2771pp$1.parseLabeledStatement = function(node, maybeName, expr) {
2772 var this$1 = this;
2773
2774 for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1)
2775 {
2776 var label = list[i$1];
2777
2778 if (label.name === maybeName)
2779 { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared");
2780 } }
2781 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
2782 for (var i = this.labels.length - 1; i >= 0; i--) {
2783 var label$1 = this$1.labels[i];
2784 if (label$1.statementStart == node.start) {
2785 label$1.statementStart = this$1.start;
2786 label$1.kind = kind;
2787 } else { break }
2788 }
2789 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
2790 node.body = this.parseStatement(true);
2791 if (node.body.type == "ClassDeclaration" ||
2792 node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
2793 node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
2794 { this.raiseRecoverable(node.body.start, "Invalid labeled declaration"); }
2795 this.labels.pop();
2796 node.label = expr;
2797 return this.finishNode(node, "LabeledStatement")
2798};
2799
2800pp$1.parseExpressionStatement = function(node, expr) {
2801 node.expression = expr;
2802 this.semicolon();
2803 return this.finishNode(node, "ExpressionStatement")
2804};
2805
2806// Parse a semicolon-enclosed block of statements, handling `"use
2807// strict"` declarations when `allowStrict` is true (used for
2808// function bodies).
2809
2810pp$1.parseBlock = function(createNewLexicalScope) {
2811 var this$1 = this;
2812 if ( createNewLexicalScope === void 0 ) { createNewLexicalScope = true; }
2813
2814 var node = this.startNode();
2815 node.body = [];
2816 this.expect(types.braceL);
2817 if (createNewLexicalScope) {
2818 this.enterLexicalScope();
2819 }
2820 while (!this.eat(types.braceR)) {
2821 var stmt = this$1.parseStatement(true);
2822 node.body.push(stmt);
2823 }
2824 if (createNewLexicalScope) {
2825 this.exitLexicalScope();
2826 }
2827 return this.finishNode(node, "BlockStatement")
2828};
2829
2830// Parse a regular `for` loop. The disambiguation code in
2831// `parseStatement` will already have parsed the init statement or
2832// expression.
2833
2834pp$1.parseFor = function(node, init) {
2835 node.init = init;
2836 this.expect(types.semi);
2837 node.test = this.type === types.semi ? null : this.parseExpression();
2838 this.expect(types.semi);
2839 node.update = this.type === types.parenR ? null : this.parseExpression();
2840 this.expect(types.parenR);
2841 this.exitLexicalScope();
2842 node.body = this.parseStatement(false);
2843 this.labels.pop();
2844 return this.finishNode(node, "ForStatement")
2845};
2846
2847// Parse a `for`/`in` and `for`/`of` loop, which are almost
2848// same from parser's perspective.
2849
2850pp$1.parseForIn = function(node, init) {
2851 var type = this.type === types._in ? "ForInStatement" : "ForOfStatement";
2852 this.next();
2853 node.left = init;
2854 node.right = this.parseExpression();
2855 this.expect(types.parenR);
2856 this.exitLexicalScope();
2857 node.body = this.parseStatement(false);
2858 this.labels.pop();
2859 return this.finishNode(node, type)
2860};
2861
2862// Parse a list of variable declarations.
2863
2864pp$1.parseVar = function(node, isFor, kind) {
2865 var this$1 = this;
2866
2867 node.declarations = [];
2868 node.kind = kind;
2869 for (;;) {
2870 var decl = this$1.startNode();
2871 this$1.parseVarId(decl, kind);
2872 if (this$1.eat(types.eq)) {
2873 decl.init = this$1.parseMaybeAssign(isFor);
2874 } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
2875 this$1.unexpected();
2876 } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) {
2877 this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value");
2878 } else {
2879 decl.init = null;
2880 }
2881 node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"));
2882 if (!this$1.eat(types.comma)) { break }
2883 }
2884 return node
2885};
2886
2887pp$1.parseVarId = function(decl, kind) {
2888 decl.id = this.parseBindingAtom(kind);
2889 this.checkLVal(decl.id, kind, false);
2890};
2891
2892// Parse a function declaration or literal (depending on the
2893// `isStatement` parameter).
2894
2895pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
2896 this.initFunction(node);
2897 if (this.options.ecmaVersion >= 6 && !isAsync)
2898 { node.generator = this.eat(types.star); }
2899 if (this.options.ecmaVersion >= 8)
2900 { node.async = !!isAsync; }
2901
2902 if (isStatement) {
2903 node.id = isStatement === "nullableID" && this.type != types.name ? null : this.parseIdent();
2904 if (node.id) {
2905 this.checkLVal(node.id, "var");
2906 }
2907 }
2908
2909 var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
2910 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
2911 this.inGenerator = node.generator;
2912 this.inAsync = node.async;
2913 this.yieldPos = 0;
2914 this.awaitPos = 0;
2915 this.inFunction = true;
2916 this.enterFunctionScope();
2917
2918 if (!isStatement)
2919 { node.id = this.type == types.name ? this.parseIdent() : null; }
2920
2921 this.parseFunctionParams(node);
2922 this.parseFunctionBody(node, allowExpressionBody);
2923
2924 this.inGenerator = oldInGen;
2925 this.inAsync = oldInAsync;
2926 this.yieldPos = oldYieldPos;
2927 this.awaitPos = oldAwaitPos;
2928 this.inFunction = oldInFunc;
2929 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
2930};
2931
2932pp$1.parseFunctionParams = function(node) {
2933 this.expect(types.parenL);
2934 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
2935 this.checkYieldAwaitInDefaultParams();
2936};
2937
2938// Parse a class declaration or literal (depending on the
2939// `isStatement` parameter).
2940
2941pp$1.parseClass = function(node, isStatement) {
2942 var this$1 = this;
2943
2944 this.next();
2945
2946 this.parseClassId(node, isStatement);
2947 this.parseClassSuper(node);
2948 var classBody = this.startNode();
2949 var hadConstructor = false;
2950 classBody.body = [];
2951 this.expect(types.braceL);
2952 while (!this.eat(types.braceR)) {
2953 if (this$1.eat(types.semi)) { continue }
2954 var method = this$1.startNode();
2955 var isGenerator = this$1.eat(types.star);
2956 var isAsync = false;
2957 var isMaybeStatic = this$1.type === types.name && this$1.value === "static";
2958 this$1.parsePropertyName(method);
2959 method.static = isMaybeStatic && this$1.type !== types.parenL;
2960 if (method.static) {
2961 if (isGenerator) { this$1.unexpected(); }
2962 isGenerator = this$1.eat(types.star);
2963 this$1.parsePropertyName(method);
2964 }
2965 if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
2966 method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== types.parenL &&
2967 !this$1.canInsertSemicolon()) {
2968 isAsync = true;
2969 this$1.parsePropertyName(method);
2970 }
2971 method.kind = "method";
2972 var isGetSet = false;
2973 if (!method.computed) {
2974 var key = method.key;
2975 if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== types.parenL && (key.name === "get" || key.name === "set")) {
2976 isGetSet = true;
2977 method.kind = key.name;
2978 key = this$1.parsePropertyName(method);
2979 }
2980 if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
2981 key.type === "Literal" && key.value === "constructor")) {
2982 if (hadConstructor) { this$1.raise(key.start, "Duplicate constructor in the same class"); }
2983 if (isGetSet) { this$1.raise(key.start, "Constructor can't have get/set modifier"); }
2984 if (isGenerator) { this$1.raise(key.start, "Constructor can't be a generator"); }
2985 if (isAsync) { this$1.raise(key.start, "Constructor can't be an async method"); }
2986 method.kind = "constructor";
2987 hadConstructor = true;
2988 }
2989 }
2990 this$1.parseClassMethod(classBody, method, isGenerator, isAsync);
2991 if (isGetSet) {
2992 var paramCount = method.kind === "get" ? 0 : 1;
2993 if (method.value.params.length !== paramCount) {
2994 var start = method.value.start;
2995 if (method.kind === "get")
2996 { this$1.raiseRecoverable(start, "getter should have no params"); }
2997 else
2998 { this$1.raiseRecoverable(start, "setter should have exactly one param"); }
2999 } else {
3000 if (method.kind === "set" && method.value.params[0].type === "RestElement")
3001 { this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
3002 }
3003 }
3004 }
3005 node.body = this.finishNode(classBody, "ClassBody");
3006 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
3007};
3008
3009pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
3010 method.value = this.parseMethod(isGenerator, isAsync);
3011 classBody.body.push(this.finishNode(method, "MethodDefinition"));
3012};
3013
3014pp$1.parseClassId = function(node, isStatement) {
3015 node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null;
3016};
3017
3018pp$1.parseClassSuper = function(node) {
3019 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
3020};
3021
3022// Parses module export declaration.
3023
3024pp$1.parseExport = function(node, exports) {
3025 var this$1 = this;
3026
3027 this.next();
3028 // export * from '...'
3029 if (this.eat(types.star)) {
3030 this.expectContextual("from");
3031 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3032 this.semicolon();
3033 return this.finishNode(node, "ExportAllDeclaration")
3034 }
3035 if (this.eat(types._default)) { // export default ...
3036 this.checkExport(exports, "default", this.lastTokStart);
3037 var isAsync;
3038 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
3039 var fNode = this.startNode();
3040 this.next();
3041 if (isAsync) { this.next(); }
3042 node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync);
3043 } else if (this.type === types._class) {
3044 var cNode = this.startNode();
3045 node.declaration = this.parseClass(cNode, "nullableID");
3046 } else {
3047 node.declaration = this.parseMaybeAssign();
3048 this.semicolon();
3049 }
3050 return this.finishNode(node, "ExportDefaultDeclaration")
3051 }
3052 // export var|const|let|function|class ...
3053 if (this.shouldParseExportStatement()) {
3054 node.declaration = this.parseStatement(true);
3055 if (node.declaration.type === "VariableDeclaration")
3056 { this.checkVariableExport(exports, node.declaration.declarations); }
3057 else
3058 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
3059 node.specifiers = [];
3060 node.source = null;
3061 } else { // export { x, y as z } [from '...']
3062 node.declaration = null;
3063 node.specifiers = this.parseExportSpecifiers(exports);
3064 if (this.eatContextual("from")) {
3065 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3066 } else {
3067 // check for keywords used as local names
3068 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
3069 var spec = list[i];
3070
3071 this$1.checkUnreserved(spec.local);
3072 }
3073
3074 node.source = null;
3075 }
3076 this.semicolon();
3077 }
3078 return this.finishNode(node, "ExportNamedDeclaration")
3079};
3080
3081pp$1.checkExport = function(exports, name, pos) {
3082 if (!exports) { return }
3083 if (has(exports, name))
3084 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
3085 exports[name] = true;
3086};
3087
3088pp$1.checkPatternExport = function(exports, pat) {
3089 var this$1 = this;
3090
3091 var type = pat.type;
3092 if (type == "Identifier")
3093 { this.checkExport(exports, pat.name, pat.start); }
3094 else if (type == "ObjectPattern")
3095 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
3096 {
3097 var prop = list[i];
3098
3099 this$1.checkPatternExport(exports, prop.value);
3100 } }
3101 else if (type == "ArrayPattern")
3102 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
3103 var elt = list$1[i$1];
3104
3105 if (elt) { this$1.checkPatternExport(exports, elt); }
3106 } }
3107 else if (type == "AssignmentPattern")
3108 { this.checkPatternExport(exports, pat.left); }
3109 else if (type == "ParenthesizedExpression")
3110 { this.checkPatternExport(exports, pat.expression); }
3111};
3112
3113pp$1.checkVariableExport = function(exports, decls) {
3114 var this$1 = this;
3115
3116 if (!exports) { return }
3117 for (var i = 0, list = decls; i < list.length; i += 1)
3118 {
3119 var decl = list[i];
3120
3121 this$1.checkPatternExport(exports, decl.id);
3122 }
3123};
3124
3125pp$1.shouldParseExportStatement = function() {
3126 return this.type.keyword === "var" ||
3127 this.type.keyword === "const" ||
3128 this.type.keyword === "class" ||
3129 this.type.keyword === "function" ||
3130 this.isLet() ||
3131 this.isAsyncFunction()
3132};
3133
3134// Parses a comma-separated list of module exports.
3135
3136pp$1.parseExportSpecifiers = function(exports) {
3137 var this$1 = this;
3138
3139 var nodes = [], first = true;
3140 // export { x, y as z } [from '...']
3141 this.expect(types.braceL);
3142 while (!this.eat(types.braceR)) {
3143 if (!first) {
3144 this$1.expect(types.comma);
3145 if (this$1.afterTrailingComma(types.braceR)) { break }
3146 } else { first = false; }
3147
3148 var node = this$1.startNode();
3149 node.local = this$1.parseIdent(true);
3150 node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local;
3151 this$1.checkExport(exports, node.exported.name, node.exported.start);
3152 nodes.push(this$1.finishNode(node, "ExportSpecifier"));
3153 }
3154 return nodes
3155};
3156
3157// Parses import declaration.
3158
3159pp$1.parseImport = function(node) {
3160 this.next();
3161 // import '...'
3162 if (this.type === types.string) {
3163 node.specifiers = empty;
3164 node.source = this.parseExprAtom();
3165 } else {
3166 node.specifiers = this.parseImportSpecifiers();
3167 this.expectContextual("from");
3168 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
3169 }
3170 this.semicolon();
3171 return this.finishNode(node, "ImportDeclaration")
3172};
3173
3174// Parses a comma-separated list of module imports.
3175
3176pp$1.parseImportSpecifiers = function() {
3177 var this$1 = this;
3178
3179 var nodes = [], first = true;
3180 if (this.type === types.name) {
3181 // import defaultObj, { x, y as z } from '...'
3182 var node = this.startNode();
3183 node.local = this.parseIdent();
3184 this.checkLVal(node.local, "let");
3185 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
3186 if (!this.eat(types.comma)) { return nodes }
3187 }
3188 if (this.type === types.star) {
3189 var node$1 = this.startNode();
3190 this.next();
3191 this.expectContextual("as");
3192 node$1.local = this.parseIdent();
3193 this.checkLVal(node$1.local, "let");
3194 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
3195 return nodes
3196 }
3197 this.expect(types.braceL);
3198 while (!this.eat(types.braceR)) {
3199 if (!first) {
3200 this$1.expect(types.comma);
3201 if (this$1.afterTrailingComma(types.braceR)) { break }
3202 } else { first = false; }
3203
3204 var node$2 = this$1.startNode();
3205 node$2.imported = this$1.parseIdent(true);
3206 if (this$1.eatContextual("as")) {
3207 node$2.local = this$1.parseIdent();
3208 } else {
3209 this$1.checkUnreserved(node$2.imported);
3210 node$2.local = node$2.imported;
3211 }
3212 this$1.checkLVal(node$2.local, "let");
3213 nodes.push(this$1.finishNode(node$2, "ImportSpecifier"));
3214 }
3215 return nodes
3216};
3217
3218var pp$2 = Parser.prototype;
3219
3220// Convert existing expression atom to assignable pattern
3221// if possible.
3222
3223pp$2.toAssignable = function(node, isBinding) {
3224 var this$1 = this;
3225
3226 if (this.options.ecmaVersion >= 6 && node) {
3227 switch (node.type) {
3228 case "Identifier":
3229 if (this.inAsync && node.name === "await")
3230 { this.raise(node.start, "Can not use 'await' as identifier inside an async function"); }
3231 break
3232
3233 case "ObjectPattern":
3234 case "ArrayPattern":
3235 break
3236
3237 case "ObjectExpression":
3238 node.type = "ObjectPattern";
3239 for (var i = 0, list = node.properties; i < list.length; i += 1) {
3240 var prop = list[i];
3241
3242 if (prop.kind !== "init") { this$1.raise(prop.key.start, "Object pattern can't contain getter or setter"); }
3243 this$1.toAssignable(prop.value, isBinding);
3244 }
3245 break
3246
3247 case "ArrayExpression":
3248 node.type = "ArrayPattern";
3249 this.toAssignableList(node.elements, isBinding);
3250 break
3251
3252 case "AssignmentExpression":
3253 if (node.operator === "=") {
3254 node.type = "AssignmentPattern";
3255 delete node.operator;
3256 this.toAssignable(node.left, isBinding);
3257 // falls through to AssignmentPattern
3258 } else {
3259 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
3260 break
3261 }
3262
3263 case "AssignmentPattern":
3264 break
3265
3266 case "ParenthesizedExpression":
3267 this.toAssignable(node.expression, isBinding);
3268 break
3269
3270 case "MemberExpression":
3271 if (!isBinding) { break }
3272
3273 default:
3274 this.raise(node.start, "Assigning to rvalue");
3275 }
3276 }
3277 return node
3278};
3279
3280// Convert list of expression atoms to binding list.
3281
3282pp$2.toAssignableList = function(exprList, isBinding) {
3283 var this$1 = this;
3284
3285 var end = exprList.length;
3286 if (end) {
3287 var last = exprList[end - 1];
3288 if (last && last.type == "RestElement") {
3289 --end;
3290 } else if (last && last.type == "SpreadElement") {
3291 last.type = "RestElement";
3292 var arg = last.argument;
3293 this.toAssignable(arg, isBinding);
3294 --end;
3295 }
3296
3297 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
3298 { this.unexpected(last.argument.start); }
3299 }
3300 for (var i = 0; i < end; i++) {
3301 var elt = exprList[i];
3302 if (elt) { this$1.toAssignable(elt, isBinding); }
3303 }
3304 return exprList
3305};
3306
3307// Parses spread element.
3308
3309pp$2.parseSpread = function(refDestructuringErrors) {
3310 var node = this.startNode();
3311 this.next();
3312 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
3313 return this.finishNode(node, "SpreadElement")
3314};
3315
3316pp$2.parseRestBinding = function() {
3317 var node = this.startNode();
3318 this.next();
3319
3320 // RestElement inside of a function parameter must be an identifier
3321 if (this.options.ecmaVersion === 6 && this.type !== types.name)
3322 { this.unexpected(); }
3323
3324 node.argument = this.parseBindingAtom();
3325
3326 return this.finishNode(node, "RestElement")
3327};
3328
3329// Parses lvalue (assignable) atom.
3330
3331pp$2.parseBindingAtom = function() {
3332 if (this.options.ecmaVersion < 6) { return this.parseIdent() }
3333 switch (this.type) {
3334 case types.name:
3335 return this.parseIdent()
3336
3337 case types.bracketL:
3338 var node = this.startNode();
3339 this.next();
3340 node.elements = this.parseBindingList(types.bracketR, true, true);
3341 return this.finishNode(node, "ArrayPattern")
3342
3343 case types.braceL:
3344 return this.parseObj(true)
3345
3346 default:
3347 this.unexpected();
3348 }
3349};
3350
3351pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
3352 var this$1 = this;
3353
3354 var elts = [], first = true;
3355 while (!this.eat(close)) {
3356 if (first) { first = false; }
3357 else { this$1.expect(types.comma); }
3358 if (allowEmpty && this$1.type === types.comma) {
3359 elts.push(null);
3360 } else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
3361 break
3362 } else if (this$1.type === types.ellipsis) {
3363 var rest = this$1.parseRestBinding();
3364 this$1.parseBindingListItem(rest);
3365 elts.push(rest);
3366 if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
3367 this$1.expect(close);
3368 break
3369 } else {
3370 var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc);
3371 this$1.parseBindingListItem(elem);
3372 elts.push(elem);
3373 }
3374 }
3375 return elts
3376};
3377
3378pp$2.parseBindingListItem = function(param) {
3379 return param
3380};
3381
3382// Parses assignment pattern around given atom if possible.
3383
3384pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
3385 left = left || this.parseBindingAtom();
3386 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
3387 var node = this.startNodeAt(startPos, startLoc);
3388 node.left = left;
3389 node.right = this.parseMaybeAssign();
3390 return this.finishNode(node, "AssignmentPattern")
3391};
3392
3393// Verify that a node is an lval — something that can be assigned
3394// to.
3395// bindingType can be either:
3396// 'var' indicating that the lval creates a 'var' binding
3397// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
3398// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
3399
3400pp$2.checkLVal = function(expr, bindingType, checkClashes) {
3401 var this$1 = this;
3402
3403 switch (expr.type) {
3404 case "Identifier":
3405 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
3406 { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
3407 if (checkClashes) {
3408 if (has(checkClashes, expr.name))
3409 { this.raiseRecoverable(expr.start, "Argument name clash"); }
3410 checkClashes[expr.name] = true;
3411 }
3412 if (bindingType && bindingType !== "none") {
3413 if (
3414 bindingType === "var" && !this.canDeclareVarName(expr.name) ||
3415 bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
3416 ) {
3417 this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"));
3418 }
3419 if (bindingType === "var") {
3420 this.declareVarName(expr.name);
3421 } else {
3422 this.declareLexicalName(expr.name);
3423 }
3424 }
3425 break
3426
3427 case "MemberExpression":
3428 if (bindingType) { this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression"); }
3429 break
3430
3431 case "ObjectPattern":
3432 for (var i = 0, list = expr.properties; i < list.length; i += 1)
3433 {
3434 var prop = list[i];
3435
3436 this$1.checkLVal(prop.value, bindingType, checkClashes);
3437 }
3438 break
3439
3440 case "ArrayPattern":
3441 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
3442 var elem = list$1[i$1];
3443
3444 if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); }
3445 }
3446 break
3447
3448 case "AssignmentPattern":
3449 this.checkLVal(expr.left, bindingType, checkClashes);
3450 break
3451
3452 case "RestElement":
3453 this.checkLVal(expr.argument, bindingType, checkClashes);
3454 break
3455
3456 case "ParenthesizedExpression":
3457 this.checkLVal(expr.expression, bindingType, checkClashes);
3458 break
3459
3460 default:
3461 this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
3462 }
3463};
3464
3465// A recursive descent parser operates by defining functions for all
3466// syntactic elements, and recursively calling those, each function
3467// advancing the input stream and returning an AST node. Precedence
3468// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
3469// instead of `(!x)[1]` is handled by the fact that the parser
3470// function that parses unary prefix operators is called first, and
3471// in turn calls the function that parses `[]` subscripts — that
3472// way, it'll receive the node for `x[1]` already parsed, and wraps
3473// *that* in the unary operator node.
3474//
3475// Acorn uses an [operator precedence parser][opp] to handle binary
3476// operator precedence, because it is much more compact than using
3477// the technique outlined above, which uses different, nesting
3478// functions to specify precedence, for all of the ten binary
3479// precedence levels that JavaScript defines.
3480//
3481// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
3482
3483var pp$3 = Parser.prototype;
3484
3485// Check if property name clashes with already added.
3486// Object/class getters and setters are not allowed to clash —
3487// either with each other or with an init property — and in
3488// strict mode, init properties are also not allowed to be repeated.
3489
3490pp$3.checkPropClash = function(prop, propHash) {
3491 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
3492 { return }
3493 var key = prop.key;
3494 var name;
3495 switch (key.type) {
3496 case "Identifier": name = key.name; break
3497 case "Literal": name = String(key.value); break
3498 default: return
3499 }
3500 var kind = prop.kind;
3501 if (this.options.ecmaVersion >= 6) {
3502 if (name === "__proto__" && kind === "init") {
3503 if (propHash.proto) { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
3504 propHash.proto = true;
3505 }
3506 return
3507 }
3508 name = "$" + name;
3509 var other = propHash[name];
3510 if (other) {
3511 var redefinition;
3512 if (kind === "init") {
3513 redefinition = this.strict && other.init || other.get || other.set;
3514 } else {
3515 redefinition = other.init || other[kind];
3516 }
3517 if (redefinition)
3518 { this.raiseRecoverable(key.start, "Redefinition of property"); }
3519 } else {
3520 other = propHash[name] = {
3521 init: false,
3522 get: false,
3523 set: false
3524 };
3525 }
3526 other[kind] = true;
3527};
3528
3529// ### Expression parsing
3530
3531// These nest, from the most general expression type at the top to
3532// 'atomic', nondivisible expression types at the bottom. Most of
3533// the functions will simply let the function(s) below them parse,
3534// and, *if* the syntactic construct they handle is present, wrap
3535// the AST node that the inner parser gave them in another node.
3536
3537// Parse a full expression. The optional arguments are used to
3538// forbid the `in` operator (in for loops initalization expressions)
3539// and provide reference for storing '=' operator inside shorthand
3540// property assignment in contexts where both object expression
3541// and object pattern might appear (so it's possible to raise
3542// delayed syntax error at correct position).
3543
3544pp$3.parseExpression = function(noIn, refDestructuringErrors) {
3545 var this$1 = this;
3546
3547 var startPos = this.start, startLoc = this.startLoc;
3548 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
3549 if (this.type === types.comma) {
3550 var node = this.startNodeAt(startPos, startLoc);
3551 node.expressions = [expr];
3552 while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); }
3553 return this.finishNode(node, "SequenceExpression")
3554 }
3555 return expr
3556};
3557
3558// Parse an assignment expression. This includes applications of
3559// operators like `+=`.
3560
3561pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
3562 if (this.inGenerator && this.isContextual("yield")) { return this.parseYield() }
3563
3564 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
3565 if (refDestructuringErrors) {
3566 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
3567 oldTrailingComma = refDestructuringErrors.trailingComma;
3568 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
3569 } else {
3570 refDestructuringErrors = new DestructuringErrors;
3571 ownDestructuringErrors = true;
3572 }
3573
3574 var startPos = this.start, startLoc = this.startLoc;
3575 if (this.type == types.parenL || this.type == types.name)
3576 { this.potentialArrowAt = this.start; }
3577 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
3578 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
3579 if (this.type.isAssign) {
3580 this.checkPatternErrors(refDestructuringErrors, true);
3581 if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
3582 var node = this.startNodeAt(startPos, startLoc);
3583 node.operator = this.value;
3584 node.left = this.type === types.eq ? this.toAssignable(left) : left;
3585 refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
3586 this.checkLVal(left);
3587 this.next();
3588 node.right = this.parseMaybeAssign(noIn);
3589 return this.finishNode(node, "AssignmentExpression")
3590 } else {
3591 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
3592 }
3593 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
3594 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
3595 return left
3596};
3597
3598// Parse a ternary conditional (`?:`) operator.
3599
3600pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
3601 var startPos = this.start, startLoc = this.startLoc;
3602 var expr = this.parseExprOps(noIn, refDestructuringErrors);
3603 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3604 if (this.eat(types.question)) {
3605 var node = this.startNodeAt(startPos, startLoc);
3606 node.test = expr;
3607 node.consequent = this.parseMaybeAssign();
3608 this.expect(types.colon);
3609 node.alternate = this.parseMaybeAssign(noIn);
3610 return this.finishNode(node, "ConditionalExpression")
3611 }
3612 return expr
3613};
3614
3615// Start the precedence parser.
3616
3617pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
3618 var startPos = this.start, startLoc = this.startLoc;
3619 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
3620 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3621 return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
3622};
3623
3624// Parse binary operators with the operator precedence parsing
3625// algorithm. `left` is the left-hand side of the operator.
3626// `minPrec` provides context that allows the function to stop and
3627// defer further parser to one of its callers when it encounters an
3628// operator that has a lower precedence than the set it is parsing.
3629
3630pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
3631 var prec = this.type.binop;
3632 if (prec != null && (!noIn || this.type !== types._in)) {
3633 if (prec > minPrec) {
3634 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
3635 var op = this.value;
3636 this.next();
3637 var startPos = this.start, startLoc = this.startLoc;
3638 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
3639 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
3640 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
3641 }
3642 }
3643 return left
3644};
3645
3646pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
3647 var node = this.startNodeAt(startPos, startLoc);
3648 node.left = left;
3649 node.operator = op;
3650 node.right = right;
3651 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
3652};
3653
3654// Parse unary operators, both prefix and postfix.
3655
3656pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
3657 var this$1 = this;
3658
3659 var startPos = this.start, startLoc = this.startLoc, expr;
3660 if (this.inAsync && this.isContextual("await")) {
3661 expr = this.parseAwait(refDestructuringErrors);
3662 sawUnary = true;
3663 } else if (this.type.prefix) {
3664 var node = this.startNode(), update = this.type === types.incDec;
3665 node.operator = this.value;
3666 node.prefix = true;
3667 this.next();
3668 node.argument = this.parseMaybeUnary(null, true);
3669 this.checkExpressionErrors(refDestructuringErrors, true);
3670 if (update) { this.checkLVal(node.argument); }
3671 else if (this.strict && node.operator === "delete" &&
3672 node.argument.type === "Identifier")
3673 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
3674 else { sawUnary = true; }
3675 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
3676 } else {
3677 expr = this.parseExprSubscripts(refDestructuringErrors);
3678 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
3679 while (this.type.postfix && !this.canInsertSemicolon()) {
3680 var node$1 = this$1.startNodeAt(startPos, startLoc);
3681 node$1.operator = this$1.value;
3682 node$1.prefix = false;
3683 node$1.argument = expr;
3684 this$1.checkLVal(expr);
3685 this$1.next();
3686 expr = this$1.finishNode(node$1, "UpdateExpression");
3687 }
3688 }
3689
3690 if (!sawUnary && this.eat(types.starstar))
3691 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
3692 else
3693 { return expr }
3694};
3695
3696// Parse call, dot, and `[]`-subscript expressions.
3697
3698pp$3.parseExprSubscripts = function(refDestructuringErrors) {
3699 var startPos = this.start, startLoc = this.startLoc;
3700 var expr = this.parseExprAtom(refDestructuringErrors);
3701 var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
3702 if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
3703 var result = this.parseSubscripts(expr, startPos, startLoc);
3704 if (refDestructuringErrors && result.type === "MemberExpression") {
3705 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
3706 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
3707 }
3708 return result
3709};
3710
3711pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
3712 var this$1 = this;
3713
3714 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
3715 this.lastTokEnd == base.end && !this.canInsertSemicolon();
3716 for (var computed = (void 0);;) {
3717 if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) {
3718 var node = this$1.startNodeAt(startPos, startLoc);
3719 node.object = base;
3720 node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true);
3721 node.computed = !!computed;
3722 if (computed) { this$1.expect(types.bracketR); }
3723 base = this$1.finishNode(node, "MemberExpression");
3724 } else if (!noCalls && this$1.eat(types.parenL)) {
3725 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos;
3726 this$1.yieldPos = 0;
3727 this$1.awaitPos = 0;
3728 var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors);
3729 if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) {
3730 this$1.checkPatternErrors(refDestructuringErrors, false);
3731 this$1.checkYieldAwaitInDefaultParams();
3732 this$1.yieldPos = oldYieldPos;
3733 this$1.awaitPos = oldAwaitPos;
3734 return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
3735 }
3736 this$1.checkExpressionErrors(refDestructuringErrors, true);
3737 this$1.yieldPos = oldYieldPos || this$1.yieldPos;
3738 this$1.awaitPos = oldAwaitPos || this$1.awaitPos;
3739 var node$1 = this$1.startNodeAt(startPos, startLoc);
3740 node$1.callee = base;
3741 node$1.arguments = exprList;
3742 base = this$1.finishNode(node$1, "CallExpression");
3743 } else if (this$1.type === types.backQuote) {
3744 var node$2 = this$1.startNodeAt(startPos, startLoc);
3745 node$2.tag = base;
3746 node$2.quasi = this$1.parseTemplate({isTagged: true});
3747 base = this$1.finishNode(node$2, "TaggedTemplateExpression");
3748 } else {
3749 return base
3750 }
3751 }
3752};
3753
3754// Parse an atomic expression — either a single token that is an
3755// expression, an expression started by a keyword like `function` or
3756// `new`, or an expression wrapped in punctuation like `()`, `[]`,
3757// or `{}`.
3758
3759pp$3.parseExprAtom = function(refDestructuringErrors) {
3760 var node, canBeArrow = this.potentialArrowAt == this.start;
3761 switch (this.type) {
3762 case types._super:
3763 if (!this.inFunction)
3764 { this.raise(this.start, "'super' outside of function or class"); }
3765
3766 case types._this:
3767 var type = this.type === types._this ? "ThisExpression" : "Super";
3768 node = this.startNode();
3769 this.next();
3770 return this.finishNode(node, type)
3771
3772 case types.name:
3773 var startPos = this.start, startLoc = this.startLoc;
3774 var id = this.parseIdent(this.type !== types.name);
3775 if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
3776 { return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) }
3777 if (canBeArrow && !this.canInsertSemicolon()) {
3778 if (this.eat(types.arrow))
3779 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
3780 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name) {
3781 id = this.parseIdent();
3782 if (this.canInsertSemicolon() || !this.eat(types.arrow))
3783 { this.unexpected(); }
3784 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
3785 }
3786 }
3787 return id
3788
3789 case types.regexp:
3790 var value = this.value;
3791 node = this.parseLiteral(value.value);
3792 node.regex = {pattern: value.pattern, flags: value.flags};
3793 return node
3794
3795 case types.num: case types.string:
3796 return this.parseLiteral(this.value)
3797
3798 case types._null: case types._true: case types._false:
3799 node = this.startNode();
3800 node.value = this.type === types._null ? null : this.type === types._true;
3801 node.raw = this.type.keyword;
3802 this.next();
3803 return this.finishNode(node, "Literal")
3804
3805 case types.parenL:
3806 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
3807 if (refDestructuringErrors) {
3808 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
3809 { refDestructuringErrors.parenthesizedAssign = start; }
3810 if (refDestructuringErrors.parenthesizedBind < 0)
3811 { refDestructuringErrors.parenthesizedBind = start; }
3812 }
3813 return expr
3814
3815 case types.bracketL:
3816 node = this.startNode();
3817 this.next();
3818 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
3819 return this.finishNode(node, "ArrayExpression")
3820
3821 case types.braceL:
3822 return this.parseObj(false, refDestructuringErrors)
3823
3824 case types._function:
3825 node = this.startNode();
3826 this.next();
3827 return this.parseFunction(node, false)
3828
3829 case types._class:
3830 return this.parseClass(this.startNode(), false)
3831
3832 case types._new:
3833 return this.parseNew()
3834
3835 case types.backQuote:
3836 return this.parseTemplate()
3837
3838 default:
3839 this.unexpected();
3840 }
3841};
3842
3843pp$3.parseLiteral = function(value) {
3844 var node = this.startNode();
3845 node.value = value;
3846 node.raw = this.input.slice(this.start, this.end);
3847 this.next();
3848 return this.finishNode(node, "Literal")
3849};
3850
3851pp$3.parseParenExpression = function() {
3852 this.expect(types.parenL);
3853 var val = this.parseExpression();
3854 this.expect(types.parenR);
3855 return val
3856};
3857
3858pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
3859 var this$1 = this;
3860
3861 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
3862 if (this.options.ecmaVersion >= 6) {
3863 this.next();
3864
3865 var innerStartPos = this.start, innerStartLoc = this.startLoc;
3866 var exprList = [], first = true, lastIsComma = false;
3867 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart;
3868 this.yieldPos = 0;
3869 this.awaitPos = 0;
3870 while (this.type !== types.parenR) {
3871 first ? first = false : this$1.expect(types.comma);
3872 if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) {
3873 lastIsComma = true;
3874 break
3875 } else if (this$1.type === types.ellipsis) {
3876 spreadStart = this$1.start;
3877 exprList.push(this$1.parseParenItem(this$1.parseRestBinding()));
3878 if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
3879 break
3880 } else {
3881 if (this$1.type === types.parenL && !innerParenStart) {
3882 innerParenStart = this$1.start;
3883 }
3884 exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem));
3885 }
3886 }
3887 var innerEndPos = this.start, innerEndLoc = this.startLoc;
3888 this.expect(types.parenR);
3889
3890 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
3891 this.checkPatternErrors(refDestructuringErrors, false);
3892 this.checkYieldAwaitInDefaultParams();
3893 if (innerParenStart) { this.unexpected(innerParenStart); }
3894 this.yieldPos = oldYieldPos;
3895 this.awaitPos = oldAwaitPos;
3896 return this.parseParenArrowList(startPos, startLoc, exprList)
3897 }
3898
3899 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
3900 if (spreadStart) { this.unexpected(spreadStart); }
3901 this.checkExpressionErrors(refDestructuringErrors, true);
3902 this.yieldPos = oldYieldPos || this.yieldPos;
3903 this.awaitPos = oldAwaitPos || this.awaitPos;
3904
3905 if (exprList.length > 1) {
3906 val = this.startNodeAt(innerStartPos, innerStartLoc);
3907 val.expressions = exprList;
3908 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
3909 } else {
3910 val = exprList[0];
3911 }
3912 } else {
3913 val = this.parseParenExpression();
3914 }
3915
3916 if (this.options.preserveParens) {
3917 var par = this.startNodeAt(startPos, startLoc);
3918 par.expression = val;
3919 return this.finishNode(par, "ParenthesizedExpression")
3920 } else {
3921 return val
3922 }
3923};
3924
3925pp$3.parseParenItem = function(item) {
3926 return item
3927};
3928
3929pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
3930 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
3931};
3932
3933// New's precedence is slightly tricky. It must allow its argument to
3934// be a `[]` or dot subscript expression, but not a call — at least,
3935// not without wrapping it in parentheses. Thus, it uses the noCalls
3936// argument to parseSubscripts to prevent it from consuming the
3937// argument list.
3938
3939var empty$1 = [];
3940
3941pp$3.parseNew = function() {
3942 var node = this.startNode();
3943 var meta = this.parseIdent(true);
3944 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
3945 node.meta = meta;
3946 node.property = this.parseIdent(true);
3947 if (node.property.name !== "target")
3948 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
3949 if (!this.inFunction)
3950 { this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
3951 return this.finishNode(node, "MetaProperty")
3952 }
3953 var startPos = this.start, startLoc = this.startLoc;
3954 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
3955 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
3956 else { node.arguments = empty$1; }
3957 return this.finishNode(node, "NewExpression")
3958};
3959
3960// Parse template expression.
3961
3962pp$3.parseTemplateElement = function(ref) {
3963 var isTagged = ref.isTagged;
3964
3965 var elem = this.startNode();
3966 if (this.type === types.invalidTemplate) {
3967 if (!isTagged) {
3968 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
3969 }
3970 elem.value = {
3971 raw: this.value,
3972 cooked: null
3973 };
3974 } else {
3975 elem.value = {
3976 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
3977 cooked: this.value
3978 };
3979 }
3980 this.next();
3981 elem.tail = this.type === types.backQuote;
3982 return this.finishNode(elem, "TemplateElement")
3983};
3984
3985pp$3.parseTemplate = function(ref) {
3986 var this$1 = this;
3987 if ( ref === void 0 ) { ref = {}; }
3988 var isTagged = ref.isTagged; if ( isTagged === void 0 ) { isTagged = false; }
3989
3990 var node = this.startNode();
3991 this.next();
3992 node.expressions = [];
3993 var curElt = this.parseTemplateElement({isTagged: isTagged});
3994 node.quasis = [curElt];
3995 while (!curElt.tail) {
3996 this$1.expect(types.dollarBraceL);
3997 node.expressions.push(this$1.parseExpression());
3998 this$1.expect(types.braceR);
3999 node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged}));
4000 }
4001 this.next();
4002 return this.finishNode(node, "TemplateLiteral")
4003};
4004
4005// Parse an object literal or binding pattern.
4006
4007pp$3.isAsyncProp = function(prop) {
4008 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
4009 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL) &&
4010 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
4011};
4012
4013pp$3.parseObj = function(isPattern, refDestructuringErrors) {
4014 var this$1 = this;
4015
4016 var node = this.startNode(), first = true, propHash = {};
4017 node.properties = [];
4018 this.next();
4019 while (!this.eat(types.braceR)) {
4020 if (!first) {
4021 this$1.expect(types.comma);
4022 if (this$1.afterTrailingComma(types.braceR)) { break }
4023 } else { first = false; }
4024
4025 var prop = this$1.startNode(), isGenerator = (void 0), isAsync = (void 0), startPos = (void 0), startLoc = (void 0);
4026 if (this$1.options.ecmaVersion >= 6) {
4027 prop.method = false;
4028 prop.shorthand = false;
4029 if (isPattern || refDestructuringErrors) {
4030 startPos = this$1.start;
4031 startLoc = this$1.startLoc;
4032 }
4033 if (!isPattern)
4034 { isGenerator = this$1.eat(types.star); }
4035 }
4036 this$1.parsePropertyName(prop);
4037 if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && this$1.isAsyncProp(prop)) {
4038 isAsync = true;
4039 this$1.parsePropertyName(prop, refDestructuringErrors);
4040 } else {
4041 isAsync = false;
4042 }
4043 this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors);
4044 this$1.checkPropClash(prop, propHash);
4045 node.properties.push(this$1.finishNode(prop, "Property"));
4046 }
4047 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
4048};
4049
4050pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
4051 if ((isGenerator || isAsync) && this.type === types.colon)
4052 { this.unexpected(); }
4053
4054 if (this.eat(types.colon)) {
4055 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
4056 prop.kind = "init";
4057 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
4058 if (isPattern) { this.unexpected(); }
4059 prop.kind = "init";
4060 prop.method = true;
4061 prop.value = this.parseMethod(isGenerator, isAsync);
4062 } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
4063 (prop.key.name === "get" || prop.key.name === "set") &&
4064 (this.type != types.comma && this.type != types.braceR)) {
4065 if (isGenerator || isAsync || isPattern) { this.unexpected(); }
4066 prop.kind = prop.key.name;
4067 this.parsePropertyName(prop);
4068 prop.value = this.parseMethod(false);
4069 var paramCount = prop.kind === "get" ? 0 : 1;
4070 if (prop.value.params.length !== paramCount) {
4071 var start = prop.value.start;
4072 if (prop.kind === "get")
4073 { this.raiseRecoverable(start, "getter should have no params"); }
4074 else
4075 { this.raiseRecoverable(start, "setter should have exactly one param"); }
4076 } else {
4077 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
4078 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
4079 }
4080 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
4081 this.checkUnreserved(prop.key);
4082 prop.kind = "init";
4083 if (isPattern) {
4084 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4085 } else if (this.type === types.eq && refDestructuringErrors) {
4086 if (refDestructuringErrors.shorthandAssign < 0)
4087 { refDestructuringErrors.shorthandAssign = this.start; }
4088 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4089 } else {
4090 prop.value = prop.key;
4091 }
4092 prop.shorthand = true;
4093 } else { this.unexpected(); }
4094};
4095
4096pp$3.parsePropertyName = function(prop) {
4097 if (this.options.ecmaVersion >= 6) {
4098 if (this.eat(types.bracketL)) {
4099 prop.computed = true;
4100 prop.key = this.parseMaybeAssign();
4101 this.expect(types.bracketR);
4102 return prop.key
4103 } else {
4104 prop.computed = false;
4105 }
4106 }
4107 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
4108};
4109
4110// Initialize empty function node.
4111
4112pp$3.initFunction = function(node) {
4113 node.id = null;
4114 if (this.options.ecmaVersion >= 6) {
4115 node.generator = false;
4116 node.expression = false;
4117 }
4118 if (this.options.ecmaVersion >= 8)
4119 { node.async = false; }
4120};
4121
4122// Parse object or class method.
4123
4124pp$3.parseMethod = function(isGenerator, isAsync) {
4125 var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
4126 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
4127
4128 this.initFunction(node);
4129 if (this.options.ecmaVersion >= 6)
4130 { node.generator = isGenerator; }
4131 if (this.options.ecmaVersion >= 8)
4132 { node.async = !!isAsync; }
4133
4134 this.inGenerator = node.generator;
4135 this.inAsync = node.async;
4136 this.yieldPos = 0;
4137 this.awaitPos = 0;
4138 this.inFunction = true;
4139 this.enterFunctionScope();
4140
4141 this.expect(types.parenL);
4142 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
4143 this.checkYieldAwaitInDefaultParams();
4144 this.parseFunctionBody(node, false);
4145
4146 this.inGenerator = oldInGen;
4147 this.inAsync = oldInAsync;
4148 this.yieldPos = oldYieldPos;
4149 this.awaitPos = oldAwaitPos;
4150 this.inFunction = oldInFunc;
4151 return this.finishNode(node, "FunctionExpression")
4152};
4153
4154// Parse arrow function expression with given parameters.
4155
4156pp$3.parseArrowExpression = function(node, params, isAsync) {
4157 var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
4158 oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
4159
4160 this.enterFunctionScope();
4161 this.initFunction(node);
4162 if (this.options.ecmaVersion >= 8)
4163 { node.async = !!isAsync; }
4164
4165 this.inGenerator = false;
4166 this.inAsync = node.async;
4167 this.yieldPos = 0;
4168 this.awaitPos = 0;
4169 this.inFunction = true;
4170
4171 node.params = this.toAssignableList(params, true);
4172 this.parseFunctionBody(node, true);
4173
4174 this.inGenerator = oldInGen;
4175 this.inAsync = oldInAsync;
4176 this.yieldPos = oldYieldPos;
4177 this.awaitPos = oldAwaitPos;
4178 this.inFunction = oldInFunc;
4179 return this.finishNode(node, "ArrowFunctionExpression")
4180};
4181
4182// Parse function body and check parameters.
4183
4184pp$3.parseFunctionBody = function(node, isArrowFunction) {
4185 var isExpression = isArrowFunction && this.type !== types.braceL;
4186 var oldStrict = this.strict, useStrict = false;
4187
4188 if (isExpression) {
4189 node.body = this.parseMaybeAssign();
4190 node.expression = true;
4191 this.checkParams(node, false);
4192 } else {
4193 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
4194 if (!oldStrict || nonSimple) {
4195 useStrict = this.strictDirective(this.end);
4196 // If this is a strict mode function, verify that argument names
4197 // are not repeated, and it does not try to bind the words `eval`
4198 // or `arguments`.
4199 if (useStrict && nonSimple)
4200 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
4201 }
4202 // Start a new scope with regard to labels and the `inFunction`
4203 // flag (restore them to their old value afterwards).
4204 var oldLabels = this.labels;
4205 this.labels = [];
4206 if (useStrict) { this.strict = true; }
4207
4208 // Add the params to varDeclaredNames to ensure that an error is thrown
4209 // if a let/const declaration in the function clashes with one of the params.
4210 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params));
4211 node.body = this.parseBlock(false);
4212 node.expression = false;
4213 this.labels = oldLabels;
4214 }
4215 this.exitFunctionScope();
4216
4217 if (this.strict && node.id) {
4218 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
4219 this.checkLVal(node.id, "none");
4220 }
4221 this.strict = oldStrict;
4222};
4223
4224pp$3.isSimpleParamList = function(params) {
4225 for (var i = 0, list = params; i < list.length; i += 1)
4226 {
4227 var param = list[i];
4228
4229 if (param.type !== "Identifier") { return false
4230 } }
4231 return true
4232};
4233
4234// Checks function params for various disallowed patterns such as using "eval"
4235// or "arguments" and duplicate parameters.
4236
4237pp$3.checkParams = function(node, allowDuplicates) {
4238 var this$1 = this;
4239
4240 var nameHash = {};
4241 for (var i = 0, list = node.params; i < list.length; i += 1)
4242 {
4243 var param = list[i];
4244
4245 this$1.checkLVal(param, "var", allowDuplicates ? null : nameHash);
4246 }
4247};
4248
4249// Parses a comma-separated list of expressions, and returns them as
4250// an array. `close` is the token type that ends the list, and
4251// `allowEmpty` can be turned on to allow subsequent commas with
4252// nothing in between them to be parsed as `null` (which is needed
4253// for array literals).
4254
4255pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
4256 var this$1 = this;
4257
4258 var elts = [], first = true;
4259 while (!this.eat(close)) {
4260 if (!first) {
4261 this$1.expect(types.comma);
4262 if (allowTrailingComma && this$1.afterTrailingComma(close)) { break }
4263 } else { first = false; }
4264
4265 var elt = (void 0);
4266 if (allowEmpty && this$1.type === types.comma)
4267 { elt = null; }
4268 else if (this$1.type === types.ellipsis) {
4269 elt = this$1.parseSpread(refDestructuringErrors);
4270 if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0)
4271 { refDestructuringErrors.trailingComma = this$1.start; }
4272 } else {
4273 elt = this$1.parseMaybeAssign(false, refDestructuringErrors);
4274 }
4275 elts.push(elt);
4276 }
4277 return elts
4278};
4279
4280// Parse the next token as an identifier. If `liberal` is true (used
4281// when parsing properties), it will also convert keywords into
4282// identifiers.
4283
4284pp$3.checkUnreserved = function(ref) {
4285 var start = ref.start;
4286 var end = ref.end;
4287 var name = ref.name;
4288
4289 if (this.inGenerator && name === "yield")
4290 { this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator"); }
4291 if (this.inAsync && name === "await")
4292 { this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function"); }
4293 if (this.isKeyword(name))
4294 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
4295 if (this.options.ecmaVersion < 6 &&
4296 this.input.slice(start, end).indexOf("\\") != -1) { return }
4297 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4298 if (re.test(name))
4299 { this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); }
4300};
4301
4302pp$3.parseIdent = function(liberal, isBinding) {
4303 var node = this.startNode();
4304 if (liberal && this.options.allowReserved == "never") { liberal = false; }
4305 if (this.type === types.name) {
4306 node.name = this.value;
4307 } else if (this.type.keyword) {
4308 node.name = this.type.keyword;
4309 } else {
4310 this.unexpected();
4311 }
4312 this.next();
4313 this.finishNode(node, "Identifier");
4314 if (!liberal) { this.checkUnreserved(node); }
4315 return node
4316};
4317
4318// Parses yield expression inside generator.
4319
4320pp$3.parseYield = function() {
4321 if (!this.yieldPos) { this.yieldPos = this.start; }
4322
4323 var node = this.startNode();
4324 this.next();
4325 if (this.type == types.semi || this.canInsertSemicolon() || (this.type != types.star && !this.type.startsExpr)) {
4326 node.delegate = false;
4327 node.argument = null;
4328 } else {
4329 node.delegate = this.eat(types.star);
4330 node.argument = this.parseMaybeAssign();
4331 }
4332 return this.finishNode(node, "YieldExpression")
4333};
4334
4335pp$3.parseAwait = function() {
4336 if (!this.awaitPos) { this.awaitPos = this.start; }
4337
4338 var node = this.startNode();
4339 this.next();
4340 node.argument = this.parseMaybeUnary(null, true);
4341 return this.finishNode(node, "AwaitExpression")
4342};
4343
4344var pp$4 = Parser.prototype;
4345
4346// This function is used to raise exceptions on parse errors. It
4347// takes an offset integer (into the current `input`) to indicate
4348// the location of the error, attaches the position to the end
4349// of the error message, and then raises a `SyntaxError` with that
4350// message.
4351
4352pp$4.raise = function(pos, message) {
4353 var loc = getLineInfo(this.input, pos);
4354 message += " (" + loc.line + ":" + loc.column + ")";
4355 var err = new SyntaxError(message);
4356 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
4357 throw err
4358};
4359
4360pp$4.raiseRecoverable = pp$4.raise;
4361
4362pp$4.curPosition = function() {
4363 if (this.options.locations) {
4364 return new Position(this.curLine, this.pos - this.lineStart)
4365 }
4366};
4367
4368var pp$5 = Parser.prototype;
4369
4370// Object.assign polyfill
4371var assign$1 = Object.assign || function(target) {
4372 var arguments$1 = arguments;
4373
4374 var sources = [], len = arguments.length - 1;
4375 while ( len-- > 0 ) { sources[ len ] = arguments$1[ len + 1 ]; }
4376
4377 for (var i = 0, list = sources; i < list.length; i += 1) {
4378 var source = list[i];
4379
4380 for (var key in source) {
4381 if (has(source, key)) {
4382 target[key] = source[key];
4383 }
4384 }
4385 }
4386 return target
4387};
4388
4389// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
4390
4391pp$5.enterFunctionScope = function() {
4392 // var: a hash of var-declared names in the current lexical scope
4393 // lexical: a hash of lexically-declared names in the current lexical scope
4394 // childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
4395 // parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
4396 this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}});
4397};
4398
4399pp$5.exitFunctionScope = function() {
4400 this.scopeStack.pop();
4401};
4402
4403pp$5.enterLexicalScope = function() {
4404 var parentScope = this.scopeStack[this.scopeStack.length - 1];
4405 var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}};
4406
4407 this.scopeStack.push(childScope);
4408 assign$1(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical);
4409};
4410
4411pp$5.exitLexicalScope = function() {
4412 var childScope = this.scopeStack.pop();
4413 var parentScope = this.scopeStack[this.scopeStack.length - 1];
4414
4415 assign$1(parentScope.childVar, childScope.var, childScope.childVar);
4416};
4417
4418/**
4419 * A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
4420 * in the current lexical scope or any of the parent lexical scopes in this function.
4421 */
4422pp$5.canDeclareVarName = function(name) {
4423 var currentScope = this.scopeStack[this.scopeStack.length - 1];
4424
4425 return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
4426};
4427
4428/**
4429 * A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
4430 * in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
4431 * any child lexical scopes in this function.
4432 */
4433pp$5.canDeclareLexicalName = function(name) {
4434 var currentScope = this.scopeStack[this.scopeStack.length - 1];
4435
4436 return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
4437};
4438
4439pp$5.declareVarName = function(name) {
4440 this.scopeStack[this.scopeStack.length - 1].var[name] = true;
4441};
4442
4443pp$5.declareLexicalName = function(name) {
4444 this.scopeStack[this.scopeStack.length - 1].lexical[name] = true;
4445};
4446
4447var Node = function Node(parser, pos, loc) {
4448 this.type = "";
4449 this.start = pos;
4450 this.end = 0;
4451 if (parser.options.locations)
4452 { this.loc = new SourceLocation(parser, loc); }
4453 if (parser.options.directSourceFile)
4454 { this.sourceFile = parser.options.directSourceFile; }
4455 if (parser.options.ranges)
4456 { this.range = [pos, 0]; }
4457};
4458
4459// Start an AST node, attaching a start offset.
4460
4461var pp$6 = Parser.prototype;
4462
4463pp$6.startNode = function() {
4464 return new Node(this, this.start, this.startLoc)
4465};
4466
4467pp$6.startNodeAt = function(pos, loc) {
4468 return new Node(this, pos, loc)
4469};
4470
4471// Finish an AST node, adding `type` and `end` properties.
4472
4473function finishNodeAt(node, type, pos, loc) {
4474 node.type = type;
4475 node.end = pos;
4476 if (this.options.locations)
4477 { node.loc.end = loc; }
4478 if (this.options.ranges)
4479 { node.range[1] = pos; }
4480 return node
4481}
4482
4483pp$6.finishNode = function(node, type) {
4484 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
4485};
4486
4487// Finish node at given position
4488
4489pp$6.finishNodeAt = function(node, type, pos, loc) {
4490 return finishNodeAt.call(this, node, type, pos, loc)
4491};
4492
4493// The algorithm used to determine whether a regexp can appear at a
4494// given point in the program is loosely based on sweet.js' approach.
4495// See https://github.com/mozilla/sweet.js/wiki/design
4496
4497var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
4498 this.token = token;
4499 this.isExpr = !!isExpr;
4500 this.preserveSpace = !!preserveSpace;
4501 this.override = override;
4502 this.generator = !!generator;
4503};
4504
4505var types$1 = {
4506 b_stat: new TokContext("{", false),
4507 b_expr: new TokContext("{", true),
4508 b_tmpl: new TokContext("${", false),
4509 p_stat: new TokContext("(", false),
4510 p_expr: new TokContext("(", true),
4511 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
4512 f_stat: new TokContext("function", false),
4513 f_expr: new TokContext("function", true),
4514 f_expr_gen: new TokContext("function", true, false, null, true),
4515 f_gen: new TokContext("function", false, false, null, true)
4516};
4517
4518var pp$7 = Parser.prototype;
4519
4520pp$7.initialContext = function() {
4521 return [types$1.b_stat]
4522};
4523
4524pp$7.braceIsBlock = function(prevType) {
4525 var parent = this.curContext();
4526 if (parent === types$1.f_expr || parent === types$1.f_stat)
4527 { return true }
4528 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
4529 { return !parent.isExpr }
4530
4531 // The check for `tt.name && exprAllowed` detects whether we are
4532 // after a `yield` or `of` construct. See the `updateContext` for
4533 // `tt.name`.
4534 if (prevType === types._return || prevType == types.name && this.exprAllowed)
4535 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
4536 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType == types.arrow)
4537 { return true }
4538 if (prevType == types.braceL)
4539 { return parent === types$1.b_stat }
4540 if (prevType == types._var || prevType == types.name)
4541 { return false }
4542 return !this.exprAllowed
4543};
4544
4545pp$7.inGeneratorContext = function() {
4546 var this$1 = this;
4547
4548 for (var i = this.context.length - 1; i >= 1; i--) {
4549 var context = this$1.context[i];
4550 if (context.token === "function")
4551 { return context.generator }
4552 }
4553 return false
4554};
4555
4556pp$7.updateContext = function(prevType) {
4557 var update, type = this.type;
4558 if (type.keyword && prevType == types.dot)
4559 { this.exprAllowed = false; }
4560 else if (update = type.updateContext)
4561 { update.call(this, prevType); }
4562 else
4563 { this.exprAllowed = type.beforeExpr; }
4564};
4565
4566// Token-specific context update code
4567
4568types.parenR.updateContext = types.braceR.updateContext = function() {
4569 if (this.context.length == 1) {
4570 this.exprAllowed = true;
4571 return
4572 }
4573 var out = this.context.pop();
4574 if (out === types$1.b_stat && this.curContext().token === "function") {
4575 out = this.context.pop();
4576 }
4577 this.exprAllowed = !out.isExpr;
4578};
4579
4580types.braceL.updateContext = function(prevType) {
4581 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
4582 this.exprAllowed = true;
4583};
4584
4585types.dollarBraceL.updateContext = function() {
4586 this.context.push(types$1.b_tmpl);
4587 this.exprAllowed = true;
4588};
4589
4590types.parenL.updateContext = function(prevType) {
4591 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
4592 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
4593 this.exprAllowed = true;
4594};
4595
4596types.incDec.updateContext = function() {
4597 // tokExprAllowed stays unchanged
4598};
4599
4600types._function.updateContext = types._class.updateContext = function(prevType) {
4601 if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&
4602 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
4603 { this.context.push(types$1.f_expr); }
4604 else
4605 { this.context.push(types$1.f_stat); }
4606 this.exprAllowed = false;
4607};
4608
4609types.backQuote.updateContext = function() {
4610 if (this.curContext() === types$1.q_tmpl)
4611 { this.context.pop(); }
4612 else
4613 { this.context.push(types$1.q_tmpl); }
4614 this.exprAllowed = false;
4615};
4616
4617types.star.updateContext = function(prevType) {
4618 if (prevType == types._function) {
4619 var index = this.context.length - 1;
4620 if (this.context[index] === types$1.f_expr)
4621 { this.context[index] = types$1.f_expr_gen; }
4622 else
4623 { this.context[index] = types$1.f_gen; }
4624 }
4625 this.exprAllowed = true;
4626};
4627
4628types.name.updateContext = function(prevType) {
4629 var allowed = false;
4630 if (this.options.ecmaVersion >= 6) {
4631 if (this.value == "of" && !this.exprAllowed ||
4632 this.value == "yield" && this.inGeneratorContext())
4633 { allowed = true; }
4634 }
4635 this.exprAllowed = allowed;
4636};
4637
4638// Object type used to represent tokens. Note that normally, tokens
4639// simply exist as properties on the parser object. This is only
4640// used for the onToken callback and the external tokenizer.
4641
4642var Token = function Token(p) {
4643 this.type = p.type;
4644 this.value = p.value;
4645 this.start = p.start;
4646 this.end = p.end;
4647 if (p.options.locations)
4648 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
4649 if (p.options.ranges)
4650 { this.range = [p.start, p.end]; }
4651};
4652
4653// ## Tokenizer
4654
4655var pp$8 = Parser.prototype;
4656
4657// Are we running under Rhino?
4658var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
4659
4660// Move to the next token
4661
4662pp$8.next = function() {
4663 if (this.options.onToken)
4664 { this.options.onToken(new Token(this)); }
4665
4666 this.lastTokEnd = this.end;
4667 this.lastTokStart = this.start;
4668 this.lastTokEndLoc = this.endLoc;
4669 this.lastTokStartLoc = this.startLoc;
4670 this.nextToken();
4671};
4672
4673pp$8.getToken = function() {
4674 this.next();
4675 return new Token(this)
4676};
4677
4678// If we're in an ES6 environment, make parsers iterable
4679if (typeof Symbol !== "undefined")
4680 { pp$8[Symbol.iterator] = function() {
4681 var this$1 = this;
4682
4683 return {
4684 next: function () {
4685 var token = this$1.getToken();
4686 return {
4687 done: token.type === types.eof,
4688 value: token
4689 }
4690 }
4691 }
4692 }; }
4693
4694// Toggle strict mode. Re-reads the next number or string to please
4695// pedantic tests (`"use strict"; 010;` should fail).
4696
4697pp$8.curContext = function() {
4698 return this.context[this.context.length - 1]
4699};
4700
4701// Read a single token, updating the parser object's token-related
4702// properties.
4703
4704pp$8.nextToken = function() {
4705 var curContext = this.curContext();
4706 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
4707
4708 this.start = this.pos;
4709 if (this.options.locations) { this.startLoc = this.curPosition(); }
4710 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
4711
4712 if (curContext.override) { return curContext.override(this) }
4713 else { this.readToken(this.fullCharCodeAtPos()); }
4714};
4715
4716pp$8.readToken = function(code) {
4717 // Identifier or keyword. '\uXXXX' sequences are allowed in
4718 // identifiers, so '\' also dispatches to that.
4719 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
4720 { return this.readWord() }
4721
4722 return this.getTokenFromCode(code)
4723};
4724
4725pp$8.fullCharCodeAtPos = function() {
4726 var code = this.input.charCodeAt(this.pos);
4727 if (code <= 0xd7ff || code >= 0xe000) { return code }
4728 var next = this.input.charCodeAt(this.pos + 1);
4729 return (code << 10) + next - 0x35fdc00
4730};
4731
4732pp$8.skipBlockComment = function() {
4733 var this$1 = this;
4734
4735 var startLoc = this.options.onComment && this.curPosition();
4736 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
4737 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
4738 this.pos = end + 2;
4739 if (this.options.locations) {
4740 lineBreakG.lastIndex = start;
4741 var match;
4742 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
4743 ++this$1.curLine;
4744 this$1.lineStart = match.index + match[0].length;
4745 }
4746 }
4747 if (this.options.onComment)
4748 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
4749 startLoc, this.curPosition()); }
4750};
4751
4752pp$8.skipLineComment = function(startSkip) {
4753 var this$1 = this;
4754
4755 var start = this.pos;
4756 var startLoc = this.options.onComment && this.curPosition();
4757 var ch = this.input.charCodeAt(this.pos += startSkip);
4758 while (this.pos < this.input.length && !isNewLine(ch)) {
4759 ch = this$1.input.charCodeAt(++this$1.pos);
4760 }
4761 if (this.options.onComment)
4762 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
4763 startLoc, this.curPosition()); }
4764};
4765
4766// Called at the start of the parse and after every token. Skips
4767// whitespace and comments, and.
4768
4769pp$8.skipSpace = function() {
4770 var this$1 = this;
4771
4772 loop: while (this.pos < this.input.length) {
4773 var ch = this$1.input.charCodeAt(this$1.pos);
4774 switch (ch) {
4775 case 32: case 160: // ' '
4776 ++this$1.pos;
4777 break
4778 case 13:
4779 if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
4780 ++this$1.pos;
4781 }
4782 case 10: case 8232: case 8233:
4783 ++this$1.pos;
4784 if (this$1.options.locations) {
4785 ++this$1.curLine;
4786 this$1.lineStart = this$1.pos;
4787 }
4788 break
4789 case 47: // '/'
4790 switch (this$1.input.charCodeAt(this$1.pos + 1)) {
4791 case 42: // '*'
4792 this$1.skipBlockComment();
4793 break
4794 case 47:
4795 this$1.skipLineComment(2);
4796 break
4797 default:
4798 break loop
4799 }
4800 break
4801 default:
4802 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
4803 ++this$1.pos;
4804 } else {
4805 break loop
4806 }
4807 }
4808 }
4809};
4810
4811// Called at the end of every token. Sets `end`, `val`, and
4812// maintains `context` and `exprAllowed`, and skips the space after
4813// the token, so that the next one's `start` will point at the
4814// right position.
4815
4816pp$8.finishToken = function(type, val) {
4817 this.end = this.pos;
4818 if (this.options.locations) { this.endLoc = this.curPosition(); }
4819 var prevType = this.type;
4820 this.type = type;
4821 this.value = val;
4822
4823 this.updateContext(prevType);
4824};
4825
4826// ### Token reading
4827
4828// This is the function that is called to fetch the next token. It
4829// is somewhat obscure, because it works in character codes rather
4830// than characters, and because operator parsing has been inlined
4831// into it.
4832//
4833// All in the name of speed.
4834//
4835pp$8.readToken_dot = function() {
4836 var next = this.input.charCodeAt(this.pos + 1);
4837 if (next >= 48 && next <= 57) { return this.readNumber(true) }
4838 var next2 = this.input.charCodeAt(this.pos + 2);
4839 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
4840 this.pos += 3;
4841 return this.finishToken(types.ellipsis)
4842 } else {
4843 ++this.pos;
4844 return this.finishToken(types.dot)
4845 }
4846};
4847
4848pp$8.readToken_slash = function() { // '/'
4849 var next = this.input.charCodeAt(this.pos + 1);
4850 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
4851 if (next === 61) { return this.finishOp(types.assign, 2) }
4852 return this.finishOp(types.slash, 1)
4853};
4854
4855pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
4856 var next = this.input.charCodeAt(this.pos + 1);
4857 var size = 1;
4858 var tokentype = code === 42 ? types.star : types.modulo;
4859
4860 // exponentiation operator ** and **=
4861 if (this.options.ecmaVersion >= 7 && next === 42) {
4862 ++size;
4863 tokentype = types.starstar;
4864 next = this.input.charCodeAt(this.pos + 2);
4865 }
4866
4867 if (next === 61) { return this.finishOp(types.assign, size + 1) }
4868 return this.finishOp(tokentype, size)
4869};
4870
4871pp$8.readToken_pipe_amp = function(code) { // '|&'
4872 var next = this.input.charCodeAt(this.pos + 1);
4873 if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) }
4874 if (next === 61) { return this.finishOp(types.assign, 2) }
4875 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
4876};
4877
4878pp$8.readToken_caret = function() { // '^'
4879 var next = this.input.charCodeAt(this.pos + 1);
4880 if (next === 61) { return this.finishOp(types.assign, 2) }
4881 return this.finishOp(types.bitwiseXOR, 1)
4882};
4883
4884pp$8.readToken_plus_min = function(code) { // '+-'
4885 var next = this.input.charCodeAt(this.pos + 1);
4886 if (next === code) {
4887 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
4888 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
4889 // A `-->` line comment
4890 this.skipLineComment(3);
4891 this.skipSpace();
4892 return this.nextToken()
4893 }
4894 return this.finishOp(types.incDec, 2)
4895 }
4896 if (next === 61) { return this.finishOp(types.assign, 2) }
4897 return this.finishOp(types.plusMin, 1)
4898};
4899
4900pp$8.readToken_lt_gt = function(code) { // '<>'
4901 var next = this.input.charCodeAt(this.pos + 1);
4902 var size = 1;
4903 if (next === code) {
4904 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
4905 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
4906 return this.finishOp(types.bitShift, size)
4907 }
4908 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
4909 this.input.charCodeAt(this.pos + 3) == 45) {
4910 if (this.inModule) { this.unexpected(); }
4911 // `<!--`, an XML-style comment that should be interpreted as a line comment
4912 this.skipLineComment(4);
4913 this.skipSpace();
4914 return this.nextToken()
4915 }
4916 if (next === 61) { size = 2; }
4917 return this.finishOp(types.relational, size)
4918};
4919
4920pp$8.readToken_eq_excl = function(code) { // '=!'
4921 var next = this.input.charCodeAt(this.pos + 1);
4922 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
4923 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
4924 this.pos += 2;
4925 return this.finishToken(types.arrow)
4926 }
4927 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
4928};
4929
4930pp$8.getTokenFromCode = function(code) {
4931 switch (code) {
4932 // The interpretation of a dot depends on whether it is followed
4933 // by a digit or another two dots.
4934 case 46: // '.'
4935 return this.readToken_dot()
4936
4937 // Punctuation tokens.
4938 case 40: ++this.pos; return this.finishToken(types.parenL)
4939 case 41: ++this.pos; return this.finishToken(types.parenR)
4940 case 59: ++this.pos; return this.finishToken(types.semi)
4941 case 44: ++this.pos; return this.finishToken(types.comma)
4942 case 91: ++this.pos; return this.finishToken(types.bracketL)
4943 case 93: ++this.pos; return this.finishToken(types.bracketR)
4944 case 123: ++this.pos; return this.finishToken(types.braceL)
4945 case 125: ++this.pos; return this.finishToken(types.braceR)
4946 case 58: ++this.pos; return this.finishToken(types.colon)
4947 case 63: ++this.pos; return this.finishToken(types.question)
4948
4949 case 96: // '`'
4950 if (this.options.ecmaVersion < 6) { break }
4951 ++this.pos;
4952 return this.finishToken(types.backQuote)
4953
4954 case 48: // '0'
4955 var next = this.input.charCodeAt(this.pos + 1);
4956 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
4957 if (this.options.ecmaVersion >= 6) {
4958 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
4959 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
4960 }
4961 // Anything else beginning with a digit is an integer, octal
4962 // number, or float.
4963 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
4964 return this.readNumber(false)
4965
4966 // Quotes produce strings.
4967 case 34: case 39: // '"', "'"
4968 return this.readString(code)
4969
4970 // Operators are parsed inline in tiny state machines. '=' (61) is
4971 // often referred to. `finishOp` simply skips the amount of
4972 // characters it is given as second argument, and returns a token
4973 // of the type given by its first argument.
4974
4975 case 47: // '/'
4976 return this.readToken_slash()
4977
4978 case 37: case 42: // '%*'
4979 return this.readToken_mult_modulo_exp(code)
4980
4981 case 124: case 38: // '|&'
4982 return this.readToken_pipe_amp(code)
4983
4984 case 94: // '^'
4985 return this.readToken_caret()
4986
4987 case 43: case 45: // '+-'
4988 return this.readToken_plus_min(code)
4989
4990 case 60: case 62: // '<>'
4991 return this.readToken_lt_gt(code)
4992
4993 case 61: case 33: // '=!'
4994 return this.readToken_eq_excl(code)
4995
4996 case 126: // '~'
4997 return this.finishOp(types.prefix, 1)
4998 }
4999
5000 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
5001};
5002
5003pp$8.finishOp = function(type, size) {
5004 var str = this.input.slice(this.pos, this.pos + size);
5005 this.pos += size;
5006 return this.finishToken(type, str)
5007};
5008
5009// Parse a regular expression. Some context-awareness is necessary,
5010// since a '/' inside a '[]' set does not end the expression.
5011
5012function tryCreateRegexp(src, flags, throwErrorAt, parser) {
5013 try {
5014 return new RegExp(src, flags)
5015 } catch (e) {
5016 if (throwErrorAt !== undefined) {
5017 if (e instanceof SyntaxError) { parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message); }
5018 throw e
5019 }
5020 }
5021}
5022
5023var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
5024
5025pp$8.readRegexp = function() {
5026 var this$1 = this;
5027
5028 var escaped, inClass, start = this.pos;
5029 for (;;) {
5030 if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression"); }
5031 var ch = this$1.input.charAt(this$1.pos);
5032 if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression"); }
5033 if (!escaped) {
5034 if (ch === "[") { inClass = true; }
5035 else if (ch === "]" && inClass) { inClass = false; }
5036 else if (ch === "/" && !inClass) { break }
5037 escaped = ch === "\\";
5038 } else { escaped = false; }
5039 ++this$1.pos;
5040 }
5041 var content = this.input.slice(start, this.pos);
5042 ++this.pos;
5043 // Need to use `readWord1` because '\uXXXX' sequences are allowed
5044 // here (don't ask).
5045 var mods = this.readWord1();
5046 var tmp = content, tmpFlags = "";
5047 if (mods) {
5048 var validFlags = /^[gim]*$/;
5049 if (this.options.ecmaVersion >= 6) { validFlags = /^[gimuy]*$/; }
5050 if (!validFlags.test(mods)) { this.raise(start, "Invalid regular expression flag"); }
5051 if (mods.indexOf("u") >= 0) {
5052 if (regexpUnicodeSupport) {
5053 tmpFlags = "u";
5054 } else {
5055 // Replace each astral symbol and every Unicode escape sequence that
5056 // possibly represents an astral symbol or a paired surrogate with a
5057 // single ASCII symbol to avoid throwing on regular expressions that
5058 // are only valid in combination with the `/u` flag.
5059 // Note: replacing with the ASCII symbol `x` might cause false
5060 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
5061 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
5062 // be replaced by `[x-b]` which throws an error.
5063 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
5064 code = Number("0x" + code);
5065 if (code > 0x10FFFF) { this$1.raise(start + offset + 3, "Code point out of bounds"); }
5066 return "x"
5067 });
5068 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
5069 tmpFlags = tmpFlags.replace("u", "");
5070 }
5071 }
5072 }
5073 // Detect invalid regular expressions.
5074 var value = null;
5075 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
5076 // so don't do detection if we are running under Rhino
5077 if (!isRhino) {
5078 tryCreateRegexp(tmp, tmpFlags, start, this);
5079 // Get a regular expression object for this pattern-flag pair, or `null` in
5080 // case the current environment doesn't support the flags it uses.
5081 value = tryCreateRegexp(content, mods);
5082 }
5083 return this.finishToken(types.regexp, {pattern: content, flags: mods, value: value})
5084};
5085
5086// Read an integer in the given radix. Return null if zero digits
5087// were read, the integer value otherwise. When `len` is given, this
5088// will return `null` unless the integer has exactly `len` digits.
5089
5090pp$8.readInt = function(radix, len) {
5091 var this$1 = this;
5092
5093 var start = this.pos, total = 0;
5094 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
5095 var code = this$1.input.charCodeAt(this$1.pos), val = (void 0);
5096 if (code >= 97) { val = code - 97 + 10; } // a
5097 else if (code >= 65) { val = code - 65 + 10; } // A
5098 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
5099 else { val = Infinity; }
5100 if (val >= radix) { break }
5101 ++this$1.pos;
5102 total = total * radix + val;
5103 }
5104 if (this.pos === start || len != null && this.pos - start !== len) { return null }
5105
5106 return total
5107};
5108
5109pp$8.readRadixNumber = function(radix) {
5110 this.pos += 2; // 0x
5111 var val = this.readInt(radix);
5112 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
5113 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5114 return this.finishToken(types.num, val)
5115};
5116
5117// Read an integer, octal integer, or floating-point number.
5118
5119pp$8.readNumber = function(startsWithDot) {
5120 var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48;
5121 if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
5122 if (octal && this.pos == start + 1) { octal = false; }
5123 var next = this.input.charCodeAt(this.pos);
5124 if (next === 46 && !octal) { // '.'
5125 ++this.pos;
5126 this.readInt(10);
5127 isFloat = true;
5128 next = this.input.charCodeAt(this.pos);
5129 }
5130 if ((next === 69 || next === 101) && !octal) { // 'eE'
5131 next = this.input.charCodeAt(++this.pos);
5132 if (next === 43 || next === 45) { ++this.pos; } // '+-'
5133 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
5134 isFloat = true;
5135 }
5136 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
5137
5138 var str = this.input.slice(start, this.pos), val;
5139 if (isFloat) { val = parseFloat(str); }
5140 else if (!octal || str.length === 1) { val = parseInt(str, 10); }
5141 else if (this.strict) { this.raise(start, "Invalid number"); }
5142 else if (/[89]/.test(str)) { val = parseInt(str, 10); }
5143 else { val = parseInt(str, 8); }
5144 return this.finishToken(types.num, val)
5145};
5146
5147// Read a string value, interpreting backslash-escapes.
5148
5149pp$8.readCodePoint = function() {
5150 var ch = this.input.charCodeAt(this.pos), code;
5151
5152 if (ch === 123) { // '{'
5153 if (this.options.ecmaVersion < 6) { this.unexpected(); }
5154 var codePos = ++this.pos;
5155 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
5156 ++this.pos;
5157 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
5158 } else {
5159 code = this.readHexChar(4);
5160 }
5161 return code
5162};
5163
5164function codePointToString(code) {
5165 // UTF-16 Decoding
5166 if (code <= 0xFFFF) { return String.fromCharCode(code) }
5167 code -= 0x10000;
5168 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
5169}
5170
5171pp$8.readString = function(quote) {
5172 var this$1 = this;
5173
5174 var out = "", chunkStart = ++this.pos;
5175 for (;;) {
5176 if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant"); }
5177 var ch = this$1.input.charCodeAt(this$1.pos);
5178 if (ch === quote) { break }
5179 if (ch === 92) { // '\'
5180 out += this$1.input.slice(chunkStart, this$1.pos);
5181 out += this$1.readEscapedChar(false);
5182 chunkStart = this$1.pos;
5183 } else {
5184 if (isNewLine(ch)) { this$1.raise(this$1.start, "Unterminated string constant"); }
5185 ++this$1.pos;
5186 }
5187 }
5188 out += this.input.slice(chunkStart, this.pos++);
5189 return this.finishToken(types.string, out)
5190};
5191
5192// Reads template string tokens.
5193
5194var INVALID_TEMPLATE_ESCAPE_ERROR = {};
5195
5196pp$8.tryReadTemplateToken = function() {
5197 this.inTemplateElement = true;
5198 try {
5199 this.readTmplToken();
5200 } catch (err) {
5201 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
5202 this.readInvalidTemplateToken();
5203 } else {
5204 throw err
5205 }
5206 }
5207
5208 this.inTemplateElement = false;
5209};
5210
5211pp$8.invalidStringToken = function(position, message) {
5212 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
5213 throw INVALID_TEMPLATE_ESCAPE_ERROR
5214 } else {
5215 this.raise(position, message);
5216 }
5217};
5218
5219pp$8.readTmplToken = function() {
5220 var this$1 = this;
5221
5222 var out = "", chunkStart = this.pos;
5223 for (;;) {
5224 if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template"); }
5225 var ch = this$1.input.charCodeAt(this$1.pos);
5226 if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
5227 if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) {
5228 if (ch === 36) {
5229 this$1.pos += 2;
5230 return this$1.finishToken(types.dollarBraceL)
5231 } else {
5232 ++this$1.pos;
5233 return this$1.finishToken(types.backQuote)
5234 }
5235 }
5236 out += this$1.input.slice(chunkStart, this$1.pos);
5237 return this$1.finishToken(types.template, out)
5238 }
5239 if (ch === 92) { // '\'
5240 out += this$1.input.slice(chunkStart, this$1.pos);
5241 out += this$1.readEscapedChar(true);
5242 chunkStart = this$1.pos;
5243 } else if (isNewLine(ch)) {
5244 out += this$1.input.slice(chunkStart, this$1.pos);
5245 ++this$1.pos;
5246 switch (ch) {
5247 case 13:
5248 if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos; }
5249 case 10:
5250 out += "\n";
5251 break
5252 default:
5253 out += String.fromCharCode(ch);
5254 break
5255 }
5256 if (this$1.options.locations) {
5257 ++this$1.curLine;
5258 this$1.lineStart = this$1.pos;
5259 }
5260 chunkStart = this$1.pos;
5261 } else {
5262 ++this$1.pos;
5263 }
5264 }
5265};
5266
5267// Reads a template token to search for the end, without validating any escape sequences
5268pp$8.readInvalidTemplateToken = function() {
5269 var this$1 = this;
5270
5271 for (; this.pos < this.input.length; this.pos++) {
5272 switch (this$1.input[this$1.pos]) {
5273 case "\\":
5274 ++this$1.pos;
5275 break
5276
5277 case "$":
5278 if (this$1.input[this$1.pos + 1] !== "{") {
5279 break
5280 }
5281 // falls through
5282
5283 case "`":
5284 return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos))
5285
5286 // no default
5287 }
5288 }
5289 this.raise(this.start, "Unterminated template");
5290};
5291
5292// Used to read escaped characters
5293
5294pp$8.readEscapedChar = function(inTemplate) {
5295 var ch = this.input.charCodeAt(++this.pos);
5296 ++this.pos;
5297 switch (ch) {
5298 case 110: return "\n" // 'n' -> '\n'
5299 case 114: return "\r" // 'r' -> '\r'
5300 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
5301 case 117: return codePointToString(this.readCodePoint()) // 'u'
5302 case 116: return "\t" // 't' -> '\t'
5303 case 98: return "\b" // 'b' -> '\b'
5304 case 118: return "\u000b" // 'v' -> '\u000b'
5305 case 102: return "\f" // 'f' -> '\f'
5306 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
5307 case 10: // ' \n'
5308 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
5309 return ""
5310 default:
5311 if (ch >= 48 && ch <= 55) {
5312 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
5313 var octal = parseInt(octalStr, 8);
5314 if (octal > 255) {
5315 octalStr = octalStr.slice(0, -1);
5316 octal = parseInt(octalStr, 8);
5317 }
5318 if (octalStr !== "0" && (this.strict || inTemplate)) {
5319 this.invalidStringToken(this.pos - 2, "Octal literal in strict mode");
5320 }
5321 this.pos += octalStr.length - 1;
5322 return String.fromCharCode(octal)
5323 }
5324 return String.fromCharCode(ch)
5325 }
5326};
5327
5328// Used to read character escape sequences ('\x', '\u', '\U').
5329
5330pp$8.readHexChar = function(len) {
5331 var codePos = this.pos;
5332 var n = this.readInt(16, len);
5333 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
5334 return n
5335};
5336
5337// Read an identifier, and return it as a string. Sets `this.containsEsc`
5338// to whether the word contained a '\u' escape.
5339//
5340// Incrementally adds only escaped chars, adding other chunks as-is
5341// as a micro-optimization.
5342
5343pp$8.readWord1 = function() {
5344 var this$1 = this;
5345
5346 this.containsEsc = false;
5347 var word = "", first = true, chunkStart = this.pos;
5348 var astral = this.options.ecmaVersion >= 6;
5349 while (this.pos < this.input.length) {
5350 var ch = this$1.fullCharCodeAtPos();
5351 if (isIdentifierChar(ch, astral)) {
5352 this$1.pos += ch <= 0xffff ? 1 : 2;
5353 } else if (ch === 92) { // "\"
5354 this$1.containsEsc = true;
5355 word += this$1.input.slice(chunkStart, this$1.pos);
5356 var escStart = this$1.pos;
5357 if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
5358 { this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX"); }
5359 ++this$1.pos;
5360 var esc = this$1.readCodePoint();
5361 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
5362 { this$1.invalidStringToken(escStart, "Invalid Unicode escape"); }
5363 word += codePointToString(esc);
5364 chunkStart = this$1.pos;
5365 } else {
5366 break
5367 }
5368 first = false;
5369 }
5370 return word + this.input.slice(chunkStart, this.pos)
5371};
5372
5373// Read an identifier or keyword token. Will check for reserved
5374// words when necessary.
5375
5376pp$8.readWord = function() {
5377 var word = this.readWord1();
5378 var type = types.name;
5379 if (this.keywords.test(word)) {
5380 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
5381 type = keywords$1[word];
5382 }
5383 return this.finishToken(type, word)
5384};
5385
5386// The main exported interface (under `self.acorn` when in the
5387// browser) is a `parse` function that takes a code string and
5388// returns an abstract syntax tree as specified by [Mozilla parser
5389// API][api].
5390//
5391// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
5392
5393function parse(input, options) {
5394 return new Parser(options, input).parse()
5395}
5396
5397function getLocator$1(source, options) {
5398 if (options === void 0) { options = {}; }
5399 var offsetLine = options.offsetLine || 0;
5400 var offsetColumn = options.offsetColumn || 0;
5401 var originalLines = source.split('\n');
5402 var start = 0;
5403 var lineRanges = originalLines.map(function (line, i) {
5404 var end = start + line.length + 1;
5405 var range = { start: start, end: end, line: i };
5406 start = end;
5407 return range;
5408 });
5409 var i = 0;
5410 function rangeContains(range, index) {
5411 return range.start <= index && index < range.end;
5412 }
5413 function getLocation(range, index) {
5414 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
5415 }
5416 function locate(search, startIndex) {
5417 if (typeof search === 'string') {
5418 search = source.indexOf(search, startIndex || 0);
5419 }
5420 var range = lineRanges[i];
5421 var d = search >= range.end ? 1 : -1;
5422 while (range) {
5423 if (rangeContains(range, search))
5424 return getLocation(range, search);
5425 i += d;
5426 range = lineRanges[i];
5427 }
5428 }
5429
5430 return locate;
5431}
5432function locate(source, search, options) {
5433 if (typeof options === 'number') {
5434 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
5435 }
5436 return getLocator$1(source, options)(search, options && options.startIndex);
5437}
5438
5439var 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( ' ' );
5440var 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( ' ' );
5441
5442var blacklisted = blank();
5443reservedWords$1.concat( builtins ).forEach( function (word) { return blacklisted[ word ] = true; } );
5444
5445var illegalCharacters = /[^$_a-zA-Z0-9]/g;
5446
5447var startsWithDigit = function (str) { return /\d/.test( str[0] ); };
5448
5449function isLegal ( str ) {
5450 if ( startsWithDigit(str) || blacklisted[ str ] ) {
5451 return false;
5452 }
5453 if ( illegalCharacters.test(str) ) {
5454 return false;
5455 }
5456 return true;
5457}
5458
5459function makeLegal ( str ) {
5460 str = str
5461 .replace( /-(\w)/g, function ( _, letter ) { return letter.toUpperCase(); } )
5462 .replace( illegalCharacters, '_' );
5463
5464 if ( startsWithDigit(str) || blacklisted[ str ] ) { str = "_" + str; }
5465
5466 return str;
5467}
5468
5469function spaces ( i ) {
5470 var result = '';
5471 while ( i-- ) { result += ' '; }
5472 return result;
5473}
5474
5475
5476function tabsToSpaces ( str ) {
5477 return str.replace( /^\t+/, function (match) { return match.split( '\t' ).join( ' ' ); } );
5478}
5479
5480function getCodeFrame ( source, line, column ) {
5481 var lines = source.split( '\n' );
5482
5483 var frameStart = Math.max( 0, line - 3 );
5484 var frameEnd = Math.min( line + 2, lines.length );
5485
5486 lines = lines.slice( frameStart, frameEnd );
5487 while ( !/\S/.test( lines[ lines.length - 1 ] ) ) {
5488 lines.pop();
5489 frameEnd -= 1;
5490 }
5491
5492 var digits = String( frameEnd ).length;
5493
5494 return lines
5495 .map( function ( str, i ) {
5496 var isErrorLine = frameStart + i + 1 === line;
5497
5498 var lineNum = String( i + frameStart + 1 );
5499 while ( lineNum.length < digits ) { lineNum = " " + lineNum; }
5500
5501 if ( isErrorLine ) {
5502 var indicator = spaces( digits + 2 + tabsToSpaces( str.slice( 0, column ) ).length ) + '^';
5503 return (lineNum + ": " + (tabsToSpaces( str )) + "\n" + indicator);
5504 }
5505
5506 return (lineNum + ": " + (tabsToSpaces( str )));
5507 })
5508 .join( '\n' );
5509}
5510
5511function relativeId ( id ) {
5512 if ( typeof process === 'undefined' || !isAbsolute( id ) ) { return id; }
5513 return relative( process.cwd(), id );
5514}
5515
5516// properties are for debugging purposes only
5517var ARRAY = { ARRAY: true, toString: function () { return '[[ARRAY]]'; } };
5518
5519
5520var NUMBER = { NUMBER: true, toString: function () { return '[[NUMBER]]'; } };
5521var OBJECT = { OBJECT: true, toString: function () { return '[[OBJECT]]'; } };
5522var STRING = { STRING: true, toString: function () { return '[[STRING]]'; } };
5523var UNKNOWN = { UNKNOWN: true, toString: function () { return '[[UNKNOWN]]'; } };
5524
5525var Declaration = function Declaration ( node, isParam ) {
5526 this.node = node;
5527
5528 this.name = node.id ? node.id.name : node.name;
5529 this.exportName = null;
5530 this.isParam = isParam;
5531
5532 this.isReassigned = false;
5533};
5534
5535Declaration.prototype.activate = function activate () {
5536 if ( this.activated ) { return; }
5537 this.activated = true;
5538
5539 if ( this.isParam ) { return; }
5540 this.node.activate();
5541};
5542
5543Declaration.prototype.addReference = function addReference ( reference ) {
5544 reference.declaration = this;
5545
5546 if ( reference.name !== this.name ) {
5547 this.name = makeLegal( reference.name ); // TODO handle differences of opinion
5548 }
5549
5550 if ( reference.isReassignment ) { this.isReassigned = true; }
5551};
5552
5553Declaration.prototype.render = function render ( es ) {
5554 if ( es ) { return this.name; }
5555 if ( !this.isReassigned || !this.exportName ) { return this.name; }
5556
5557 return ("exports." + (this.exportName));
5558};
5559
5560var SyntheticNamespaceDeclaration = function SyntheticNamespaceDeclaration ( module ) {
5561 var this$1 = this;
5562
5563 this.isNamespace = true;
5564 this.module = module;
5565 this.name = module.basename();
5566
5567 this.needsNamespaceBlock = false;
5568
5569 this.originals = blank();
5570 module.getExports().concat( module.getReexports() ).forEach( function (name) {
5571 this$1.originals[ name ] = module.traceExport( name );
5572 });
5573};
5574
5575SyntheticNamespaceDeclaration.prototype.activate = function activate () {
5576 this.needsNamespaceBlock = true;
5577
5578 // add synthetic references, in case of chained
5579 // namespace imports
5580 forOwn( this.originals, function (original) {
5581 original.activate();
5582 });
5583};
5584
5585SyntheticNamespaceDeclaration.prototype.addReference = function addReference ( node ) {
5586 this.name = node.name;
5587};
5588
5589SyntheticNamespaceDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5590 values.add( UNKNOWN );
5591};
5592
5593SyntheticNamespaceDeclaration.prototype.getName = function getName () {
5594 return this.name;
5595};
5596
5597SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock ( es, legacy, indentString ) {
5598 var this$1 = this;
5599
5600 var members = keys( this.originals ).map( function (name) {
5601 var original = this$1.originals[ name ];
5602
5603 if ( original.isReassigned && !legacy ) {
5604 return (indentString + "get " + name + " () { return " + (original.getName( es )) + "; }");
5605 }
5606
5607 if ( legacy && ~reservedWords$1.indexOf( name ) ) { name = "'" + name + "'"; }
5608 return ("" + indentString + name + ": " + (original.getName( es )));
5609 });
5610
5611 var callee = legacy ? "(Object.freeze || Object)" : "Object.freeze";
5612 return ((this.module.bundle.varOrConst) + " " + (this.getName( es )) + " = " + callee + "({\n" + (members.join( ',\n' )) + "\n});\n\n");
5613};
5614
5615var ExternalDeclaration = function ExternalDeclaration ( module, name ) {
5616 this.module = module;
5617 this.name = name;
5618 this.safeName = null;
5619 this.isExternal = true;
5620
5621 this.activated = false;
5622
5623 this.isNamespace = name === '*';
5624};
5625
5626ExternalDeclaration.prototype.activate = function activate () {
5627 this.module.used = true;
5628 this.activated = true;
5629};
5630
5631ExternalDeclaration.prototype.addReference = function addReference ( reference ) {
5632 reference.declaration = this;
5633
5634 if ( this.name === 'default' || this.name === '*' ) {
5635 this.module.suggestName( reference.name );
5636 }
5637};
5638
5639ExternalDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5640 values.add( UNKNOWN );
5641};
5642
5643ExternalDeclaration.prototype.getName = function getName ( es ) {
5644 if ( this.name === '*' ) {
5645 return this.module.name;
5646 }
5647
5648 if ( this.name === 'default' ) {
5649 return this.module.exportsNamespace || ( !es && this.module.exportsNames ) ?
5650 ((this.module.name) + "__default") :
5651 this.module.name;
5652 }
5653
5654 return es ? this.safeName : ((this.module.name) + "." + (this.name));
5655};
5656
5657ExternalDeclaration.prototype.setSafeName = function setSafeName ( name ) {
5658 this.safeName = name;
5659};
5660
5661function extractNames ( param ) {
5662 var names = [];
5663 extractors[ param.type ]( names, param );
5664 return names;
5665}
5666
5667var extractors = {
5668 Identifier: function Identifier ( names, param ) {
5669 names.push( param.name );
5670 },
5671
5672 ObjectPattern: function ObjectPattern ( names, param ) {
5673 param.properties.forEach( function (prop) {
5674 extractors[ prop.value.type ]( names, prop.value );
5675 });
5676 },
5677
5678 ArrayPattern: function ArrayPattern ( names, param ) {
5679 param.elements.forEach( function (element) {
5680 if ( element ) { extractors[ element.type ]( names, element ); }
5681 });
5682 },
5683
5684 RestElement: function RestElement ( names, param ) {
5685 extractors[ param.argument.type ]( names, param.argument );
5686 },
5687
5688 AssignmentPattern: function AssignmentPattern ( names, param ) {
5689 extractors[ param.left.type ]( names, param.left );
5690 }
5691};
5692
5693var Node$1 = function Node () {};
5694
5695Node$1.prototype.bind = function bind () {
5696 this.eachChild( function (child) { return child.bind(); } );
5697};
5698
5699Node$1.prototype.eachChild = function eachChild ( callback ) {
5700 var this$1 = this;
5701
5702 for ( var key of this$1.keys ) {
5703 if ( this$1.shorthand && key === 'key' ) { continue; } // key and value are the same
5704
5705 var value = this$1[ key ];
5706
5707 if ( value ) {
5708 if ( 'length' in value ) {
5709 for ( var child of value ) {
5710 if ( child ) { callback( child ); }
5711 }
5712 } else if ( value ) {
5713 callback( value );
5714 }
5715 }
5716 }
5717};
5718
5719Node$1.prototype.findParent = function findParent ( selector ) {
5720 return selector.test( this.type ) ? this : this.parent.findParent( selector );
5721};
5722
5723Node$1.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5724 //this.eachChild( child => child.gatherPossibleValues( values ) );
5725 values.add( UNKNOWN );
5726};
5727
5728Node$1.prototype.getValue = function getValue () {
5729 return UNKNOWN;
5730};
5731
5732Node$1.prototype.hasEffects = function hasEffects () {
5733 var this$1 = this;
5734
5735 for ( var key of this$1.keys ) {
5736 var value = this$1[ key ];
5737
5738 if ( value ) {
5739 if ( 'length' in value ) {
5740 for ( var child of value ) {
5741 if ( child && child.hasEffects() ) {
5742 return true;
5743 }
5744 }
5745 } else if ( value.hasEffects() ) {
5746 return true;
5747 }
5748 }
5749 }
5750};
5751
5752Node$1.prototype.initialise = function initialise ( parentScope ) {
5753 this.initialiseScope( parentScope );
5754 this.initialiseNode( parentScope );
5755 this.initialiseChildren( parentScope );
5756};
5757
5758// Override if e.g. some children need to be initialised with the parent scope
5759Node$1.prototype.initialiseChildren = function initialiseChildren () {
5760 var this$1 = this;
5761
5762 this.eachChild( function (child) { return child.initialise( this$1.scope ); } );
5763};
5764
5765// Override to perform special initialisation steps after the scope is initialised
5766Node$1.prototype.initialiseNode = function initialiseNode () {};
5767
5768// Overwrite to create a new scope
5769Node$1.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5770 this.scope = parentScope;
5771};
5772
5773Node$1.prototype.insertSemicolon = function insertSemicolon ( code ) {
5774 if ( code.original[ this.end - 1 ] !== ';' ) {
5775 code.appendLeft( this.end, ';' );
5776 }
5777};
5778
5779Node$1.prototype.locate = function locate$1 () {
5780 // useful for debugging
5781 var location = locate( this.module.code, this.start, { offsetLine: 1 } );
5782 location.file = this.module.id;
5783 location.toString = function () { return JSON.stringify( location ); };
5784
5785 return location;
5786};
5787
5788Node$1.prototype.render = function render ( code, es ) {
5789 this.eachChild( function (child) { return child.render( code, es ); } );
5790};
5791
5792Node$1.prototype.run = function run () {
5793 if ( this.ran ) { return; }
5794 this.ran = true;
5795
5796 this.eachChild( function (child) { return child.run(); } );
5797};
5798
5799Node$1.prototype.toString = function toString () {
5800 return this.module.code.slice( this.start, this.end );
5801};
5802
5803var ArrayExpression = (function (Node) {
5804 function ArrayExpression () {
5805 Node.apply(this, arguments);
5806 }
5807
5808 if ( Node ) ArrayExpression.__proto__ = Node;
5809 ArrayExpression.prototype = Object.create( Node && Node.prototype );
5810 ArrayExpression.prototype.constructor = ArrayExpression;
5811
5812 ArrayExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5813 values.add( ARRAY );
5814 };
5815
5816 return ArrayExpression;
5817}(Node$1));
5818
5819var Parameter = function Parameter ( name ) {
5820 this.name = name;
5821
5822 this.isParam = true;
5823 this.activated = true;
5824};
5825
5826Parameter.prototype.activate = function activate () {
5827 // noop
5828};
5829
5830Parameter.prototype.addReference = function addReference () {
5831 // noop?
5832};
5833
5834Parameter.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
5835 values.add( UNKNOWN ); // TODO populate this at call time
5836};
5837
5838Parameter.prototype.getName = function getName () {
5839 return this.name;
5840};
5841
5842var Scope = function Scope ( options ) {
5843 if ( options === void 0 ) options = {};
5844
5845 this.parent = options.parent;
5846 this.isBlockScope = !!options.isBlockScope;
5847 this.isLexicalBoundary = !!options.isLexicalBoundary;
5848 this.isModuleScope = !!options.isModuleScope;
5849
5850 this.children = [];
5851 if ( this.parent ) { this.parent.children.push( this ); }
5852
5853 this.declarations = blank();
5854
5855 if ( this.isLexicalBoundary && !this.isModuleScope ) {
5856 this.declarations.arguments = new Parameter( 'arguments' );
5857 }
5858};
5859
5860Scope.prototype.addDeclaration = function addDeclaration ( name, declaration, isVar, isParam ) {
5861 if ( isVar && this.isBlockScope ) {
5862 this.parent.addDeclaration( name, declaration, isVar, isParam );
5863 } else {
5864 var existingDeclaration = this.declarations[ name ];
5865
5866 if ( existingDeclaration && existingDeclaration.duplicates ) {
5867 // TODO warn/throw on duplicates?
5868 existingDeclaration.duplicates.push( declaration );
5869 } else {
5870 this.declarations[ name ] = isParam ? new Parameter( name ) : declaration;
5871 }
5872 }
5873};
5874
5875Scope.prototype.contains = function contains ( name ) {
5876 return !!this.declarations[ name ] ||
5877 ( this.parent ? this.parent.contains( name ) : false );
5878};
5879
5880Scope.prototype.deshadow = function deshadow ( names ) {
5881 var this$1 = this;
5882
5883 keys( this.declarations ).forEach( function (key) {
5884 var declaration = this$1.declarations[ key ];
5885
5886 // we can disregard exports.foo etc
5887 if ( declaration.exportName && declaration.isReassigned ) { return; }
5888
5889 var name = declaration.getName( true );
5890 var deshadowed = name;
5891
5892 var i = 1;
5893
5894 while ( names.has( deshadowed ) ) {
5895 deshadowed = name + "$$" + (i++);
5896 }
5897
5898 declaration.name = deshadowed;
5899 });
5900
5901 this.children.forEach( function (scope) { return scope.deshadow( names ); } );
5902};
5903
5904Scope.prototype.findDeclaration = function findDeclaration ( name ) {
5905 return this.declarations[ name ] ||
5906 ( this.parent && this.parent.findDeclaration( name ) );
5907};
5908
5909Scope.prototype.findLexicalBoundary = function findLexicalBoundary () {
5910 return this.isLexicalBoundary ? this : this.parent.findLexicalBoundary();
5911};
5912
5913var Function$1 = (function (Node) {
5914 function Function () {
5915 Node.apply(this, arguments);
5916 }
5917
5918 if ( Node ) Function.__proto__ = Node;
5919 Function.prototype = Object.create( Node && Node.prototype );
5920 Function.prototype.constructor = Function;
5921
5922 Function.prototype.bind = function bind () {
5923 if ( this.id ) { this.id.bind(); }
5924 this.params.forEach( function (param) { return param.bind(); } );
5925 this.body.bind();
5926 };
5927
5928 Function.prototype.hasEffects = function hasEffects () {
5929 return false;
5930 };
5931
5932 Function.prototype.initialiseChildren = function initialiseChildren () {
5933 var this$1 = this;
5934
5935 this.params.forEach( function (param) {
5936 param.initialise( this$1.scope );
5937 extractNames( param ).forEach( function (name) { return this$1.scope.addDeclaration( name, null, false, true ); } );
5938 } );
5939 this.body.initialiseAndReplaceScope ?
5940 this.body.initialiseAndReplaceScope( this.scope ) :
5941 this.body.initialise( this.scope );
5942 };
5943
5944 Function.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5945 this.scope = new Scope( {
5946 parent: parentScope,
5947 isBlockScope: false,
5948 isLexicalBoundary: true
5949 } );
5950 };
5951
5952 return Function;
5953}(Node$1));
5954
5955var ArrowFunctionExpression = (function (Function) {
5956 function ArrowFunctionExpression () {
5957 Function.apply(this, arguments);
5958 }
5959
5960 if ( Function ) ArrowFunctionExpression.__proto__ = Function;
5961 ArrowFunctionExpression.prototype = Object.create( Function && Function.prototype );
5962 ArrowFunctionExpression.prototype.constructor = ArrowFunctionExpression;
5963
5964 ArrowFunctionExpression.prototype.initialiseScope = function initialiseScope ( parentScope ) {
5965 this.scope = new Scope( {
5966 parent: parentScope,
5967 isBlockScope: false,
5968 isLexicalBoundary: false
5969 } );
5970 };
5971
5972 return ArrowFunctionExpression;
5973}(Function$1));
5974
5975// TODO tidy this up a bit (e.g. they can both use node.module.imports)
5976function disallowIllegalReassignment ( scope, node ) {
5977 if ( node.type === 'MemberExpression' && node.object.type === 'Identifier' ) {
5978 var declaration = scope.findDeclaration( node.object.name );
5979 if ( declaration.isNamespace ) {
5980 node.module.error({
5981 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
5982 message: ("Illegal reassignment to import '" + (node.object.name) + "'")
5983 }, node.start );
5984 }
5985 }
5986
5987 else if ( node.type === 'Identifier' ) {
5988 if ( node.module.imports[ node.name ] && !scope.contains( node.name ) ) {
5989 node.module.error({
5990 code: 'ILLEGAL_REASSIGNMENT',
5991 message: ("Illegal reassignment to import '" + (node.name) + "'")
5992 }, node.start );
5993 }
5994 }
5995}
5996
5997function isUsedByBundle ( scope, node ) {
5998 // const expression = node;
5999 while ( node.type === 'MemberExpression' ) { node = node.object; }
6000
6001 var declaration = scope.findDeclaration( node.name );
6002
6003 if ( declaration.isParam ) {
6004 return true;
6005
6006 // TODO if we mutate a parameter, assume the worst
6007 // return node !== expression;
6008 }
6009
6010 if ( declaration.activated ) { return true; }
6011
6012 var values = new Set();
6013 declaration.gatherPossibleValues( values );
6014 for ( var value of values ) {
6015 if ( value === UNKNOWN ) {
6016 return true;
6017 }
6018
6019 if ( value.type === 'Identifier' ) {
6020 if ( value.declaration.activated ) {
6021 return true;
6022 }
6023 value.declaration.gatherPossibleValues( values );
6024 }
6025
6026 else if ( value.gatherPossibleValues ) {
6027 value.gatherPossibleValues( values );
6028 }
6029 }
6030
6031 return false;
6032}
6033
6034function isProgramLevel ( node ) {
6035 do {
6036 if ( node.type === 'Program' ) {
6037 return true;
6038 }
6039 node = node.parent;
6040 } while ( node && !/Function/.test( node.type ) );
6041
6042 return false;
6043}
6044
6045var AssignmentExpression = (function (Node) {
6046 function AssignmentExpression () {
6047 Node.apply(this, arguments);
6048 }
6049
6050 if ( Node ) AssignmentExpression.__proto__ = Node;
6051 AssignmentExpression.prototype = Object.create( Node && Node.prototype );
6052 AssignmentExpression.prototype.constructor = AssignmentExpression;
6053
6054 AssignmentExpression.prototype.bind = function bind () {
6055 var subject = this.left;
6056
6057 this.subject = subject;
6058 disallowIllegalReassignment( this.scope, subject );
6059
6060 if ( subject.type === 'Identifier' ) {
6061 var declaration = this.scope.findDeclaration( subject.name );
6062 declaration.isReassigned = true;
6063
6064 if ( declaration.possibleValues ) { // TODO this feels hacky
6065 if ( this.operator === '=' ) {
6066 declaration.possibleValues.add( this.right );
6067 } else if ( this.operator === '+=' ) {
6068 declaration.possibleValues.add( STRING ).add( NUMBER );
6069 } else {
6070 declaration.possibleValues.add( NUMBER );
6071 }
6072 }
6073 }
6074
6075 Node.prototype.bind.call(this);
6076 };
6077
6078 AssignmentExpression.prototype.hasEffects = function hasEffects () {
6079 var hasEffects = this.isUsedByBundle() || this.right.hasEffects();
6080 return hasEffects;
6081 };
6082
6083 AssignmentExpression.prototype.initialiseNode = function initialiseNode () {
6084 if ( isProgramLevel( this ) ) {
6085 this.module.bundle.dependentExpressions.push( this );
6086 }
6087 };
6088
6089 AssignmentExpression.prototype.isUsedByBundle = function isUsedByBundle$1 () {
6090 return isUsedByBundle( this.scope, this.subject );
6091 };
6092
6093 return AssignmentExpression;
6094}(Node$1));
6095
6096var operators = {
6097 '==': function ( left, right ) { return left == right; },
6098 '!=': function ( left, right ) { return left != right; },
6099 '===': function ( left, right ) { return left === right; },
6100 '!==': function ( left, right ) { return left !== right; },
6101 '<': function ( left, right ) { return left < right; },
6102 '<=': function ( left, right ) { return left <= right; },
6103 '>': function ( left, right ) { return left > right; },
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 Math.pow( left, right ); },
6117 in: function ( left, right ) { return left in right; },
6118 instanceof: function ( left, right ) { return left instanceof right; }
6119};
6120
6121var BinaryExpression = (function (Node) {
6122 function BinaryExpression () {
6123 Node.apply(this, arguments);
6124 }
6125
6126 if ( Node ) BinaryExpression.__proto__ = Node;
6127 BinaryExpression.prototype = Object.create( Node && Node.prototype );
6128 BinaryExpression.prototype.constructor = BinaryExpression;
6129
6130 BinaryExpression.prototype.getValue = function getValue () {
6131 var leftValue = this.left.getValue();
6132 if ( leftValue === UNKNOWN ) { return UNKNOWN; }
6133
6134 var rightValue = this.right.getValue();
6135 if ( rightValue === UNKNOWN ) { return UNKNOWN; }
6136
6137 if ( !operators[ this.operator ] ) { return UNKNOWN; }
6138
6139 return operators[ this.operator ]( leftValue, rightValue );
6140 };
6141
6142 return BinaryExpression;
6143}(Node$1));
6144
6145var Statement = (function (Node) {
6146 function Statement () {
6147 Node.apply(this, arguments);
6148 }
6149
6150 if ( Node ) Statement.__proto__ = Node;
6151 Statement.prototype = Object.create( Node && Node.prototype );
6152 Statement.prototype.constructor = Statement;
6153
6154 Statement.prototype.render = function render ( code, es ) {
6155 if ( !this.module.bundle.treeshake || this.shouldInclude ) {
6156 Node.prototype.render.call( this, code, es );
6157 } else {
6158 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6159 }
6160 };
6161
6162 Statement.prototype.run = function run () {
6163 this.shouldInclude = true;
6164 Node.prototype.run.call(this);
6165 };
6166
6167 return Statement;
6168}(Node$1));
6169
6170var BlockStatement = (function (Statement$$1) {
6171 function BlockStatement () {
6172 Statement$$1.apply(this, arguments);
6173 }
6174
6175 if ( Statement$$1 ) BlockStatement.__proto__ = Statement$$1;
6176 BlockStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6177 BlockStatement.prototype.constructor = BlockStatement;
6178
6179 BlockStatement.prototype.bind = function bind () {
6180 this.body.forEach( function (node) { return node.bind(); } );
6181 };
6182
6183 BlockStatement.prototype.initialiseAndReplaceScope = function initialiseAndReplaceScope ( scope ) {
6184 this.scope = scope;
6185 this.initialiseNode();
6186 this.initialiseChildren( scope );
6187 };
6188
6189 BlockStatement.prototype.initialiseChildren = function initialiseChildren () {
6190 var this$1 = this;
6191
6192 var lastNode;
6193 for ( var node of this$1.body ) {
6194 node.initialise( this$1.scope );
6195
6196 if ( lastNode ) { lastNode.next = node.start; }
6197 lastNode = node;
6198 }
6199 };
6200
6201 BlockStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6202 this.scope = new Scope( {
6203 parent: parentScope,
6204 isBlockScope: true,
6205 isLexicalBoundary: false
6206 } );
6207 };
6208
6209 BlockStatement.prototype.render = function render ( code, es ) {
6210 var this$1 = this;
6211
6212 if ( this.body.length ) {
6213 for ( var node of this$1.body ) {
6214 node.render( code, es );
6215 }
6216 } else {
6217 Statement$$1.prototype.render.call( this, code, es );
6218 }
6219 };
6220
6221 return BlockStatement;
6222}(Statement));
6223
6224function isReference (node, parent) {
6225 if (node.type === 'MemberExpression') {
6226 return !node.computed && isReference(node.object, node);
6227 }
6228
6229 if (node.type === 'Identifier') {
6230 // the only time we could have an identifier node without a parent is
6231 // if it's the entire body of a function without a block statement –
6232 // i.e. an arrow function expression like `a => a`
6233 if (!parent) return true;
6234
6235 // TODO is this right?
6236 if (parent.type === 'MemberExpression' || parent.type === 'MethodDefinition') {
6237 return parent.computed || node === parent.object;
6238 }
6239
6240 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6241 if (parent.type === 'Property') return parent.computed || node === parent.value;
6242
6243 // disregard the `bar` in `class Foo { bar () {...} }`
6244 if (parent.type === 'MethodDefinition') return false;
6245
6246 // disregard the `bar` in `export { foo as bar }`
6247 if (parent.type === 'ExportSpecifier' && node !== parent.local) return false;
6248
6249 return true;
6250 }
6251
6252 return false;
6253}
6254
6255function flatten ( node ) {
6256 var parts = [];
6257 while ( node.type === 'MemberExpression' ) {
6258 if ( node.computed ) { return null; }
6259 parts.unshift( node.property.name );
6260
6261 node = node.object;
6262 }
6263
6264 if ( node.type !== 'Identifier' ) { return null; }
6265
6266 var name = node.name;
6267 parts.unshift( name );
6268
6269 return { name: name, keypath: parts.join( '.' ) };
6270}
6271
6272var pureFunctions = {};
6273
6274var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split( ' ' );
6275var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split( ' ' );
6276var 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( ' ' );
6277var allSimdMethods = [];
6278simdTypes.forEach( function (t) {
6279 simdMethods.forEach( function (m) {
6280 allSimdMethods.push( ("SIMD." + t + "." + m) );
6281 });
6282});
6283
6284[
6285 'Array.isArray',
6286 'Error', 'EvalError', 'InternalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',
6287 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'unescape',
6288 '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',
6289 'Function', 'Boolean',
6290 'Number', 'Number.isFinite', 'Number.isInteger', 'Number.isNaN', 'Number.isSafeInteger', 'Number.parseFloat', 'Number.parseInt',
6291 'Symbol', 'Symbol.for', 'Symbol.keyFor',
6292 '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',
6293 'Date', 'Date.UTC', 'Date.now', 'Date.parse',
6294 'String', 'String.fromCharCode', 'String.fromCodePoint', 'String.raw',
6295 'RegExp',
6296 'Map', 'Set', 'WeakMap', 'WeakSet',
6297 'ArrayBuffer', 'ArrayBuffer.isView',
6298 'DataView',
6299 'JSON.parse', 'JSON.stringify',
6300 'Promise', 'Promise.all', 'Promise.race', 'Promise.reject', 'Promise.resolve',
6301 'Intl.Collator', 'Intl.Collator.supportedLocalesOf', 'Intl.DateTimeFormat', 'Intl.DateTimeFormat.supportedLocalesOf', 'Intl.NumberFormat', 'Intl.NumberFormat.supportedLocalesOf'
6302
6303 // TODO properties of e.g. window...
6304].concat(
6305 arrayTypes,
6306 arrayTypes.map( function (t) { return (t + ".from"); } ),
6307 arrayTypes.map( function (t) { return (t + ".of"); } ),
6308 simdTypes.map( function (t) { return ("SIMD." + t); } ),
6309 allSimdMethods
6310).forEach( function (name) { return pureFunctions[ name ] = true; } );
6311
6312var currentlyCalling = new Set();
6313
6314function isES5Function ( node ) {
6315 return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
6316}
6317
6318function hasEffectsNew ( node ) {
6319 var inner = node;
6320
6321 if ( inner.type === 'ExpressionStatement' ) {
6322 inner = inner.expression;
6323
6324 if ( inner.type === 'AssignmentExpression' ) {
6325 if ( inner.right.hasEffects() ) {
6326 return true;
6327
6328 } else {
6329 inner = inner.left;
6330
6331 if ( inner.type === 'MemberExpression' ) {
6332 if ( inner.computed && inner.property.hasEffects() ) {
6333 return true;
6334
6335 } else {
6336 inner = inner.object;
6337
6338 if ( inner.type === 'ThisExpression' ) {
6339 return false;
6340 }
6341 }
6342 }
6343 }
6344 }
6345 }
6346
6347 return node.hasEffects();
6348}
6349
6350function fnHasEffects ( fn, isNew ) {
6351 if ( currentlyCalling.has( fn ) ) { return false; } // prevent infinite loops... TODO there must be a better way
6352 currentlyCalling.add( fn );
6353
6354 // handle body-less arrow functions
6355 var body = fn.body.type === 'BlockStatement' ? fn.body.body : [ fn.body ];
6356
6357 for ( var node of body ) {
6358 if ( isNew ? hasEffectsNew( node ) : node.hasEffects() ) {
6359 currentlyCalling.delete( fn );
6360 return true;
6361 }
6362 }
6363
6364 currentlyCalling.delete( fn );
6365 return false;
6366}
6367
6368function callHasEffects ( scope, callee, isNew ) {
6369 var values = new Set( [ callee ] );
6370
6371 for ( var node of values ) {
6372 if ( node === UNKNOWN ) { return true; } // err on side of caution
6373
6374 if ( /Function/.test( node.type ) ) {
6375 if ( fnHasEffects( node, isNew && isES5Function( node ) ) ) { return true; }
6376 }
6377
6378 else if ( /Class/.test( node.type ) ) {
6379 // TODO find constructor (may belong to a superclass)
6380 return true;
6381 }
6382
6383 else if ( isReference( node ) ) {
6384 var flattened = flatten( node );
6385 var declaration = scope.findDeclaration( flattened.name );
6386
6387 if ( declaration.isGlobal ) {
6388 if ( !pureFunctions[ flattened.keypath ] ) { return true; }
6389 }
6390
6391 else if ( declaration.isExternal ) {
6392 return true; // TODO make this configurable? e.g. `path.[whatever]`
6393 }
6394
6395 else {
6396 if ( node.declaration ) {
6397 node.declaration.gatherPossibleValues( values );
6398 } else {
6399 return true;
6400 }
6401 }
6402 }
6403
6404 else if ( node.gatherPossibleValues ) {
6405 node.gatherPossibleValues( values );
6406 }
6407
6408 else {
6409 // probably an error in the user's code — err on side of caution
6410 return true;
6411 }
6412 }
6413
6414 return false;
6415}
6416
6417var CallExpression = (function (Node) {
6418 function CallExpression () {
6419 Node.apply(this, arguments);
6420 }
6421
6422 if ( Node ) CallExpression.__proto__ = Node;
6423 CallExpression.prototype = Object.create( Node && Node.prototype );
6424 CallExpression.prototype.constructor = CallExpression;
6425
6426 CallExpression.prototype.bind = function bind () {
6427 if ( this.callee.type === 'Identifier' ) {
6428 var declaration = this.scope.findDeclaration( this.callee.name );
6429
6430 if ( declaration.isNamespace ) {
6431 this.module.error( {
6432 code: 'CANNOT_CALL_NAMESPACE',
6433 message: ("Cannot call a namespace ('" + (this.callee.name) + "')")
6434 }, this.start );
6435 }
6436
6437 if ( this.callee.name === 'eval' && declaration.isGlobal ) {
6438 this.module.warn( {
6439 code: 'EVAL',
6440 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
6441 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval'
6442 }, this.start );
6443 }
6444 }
6445
6446 Node.prototype.bind.call(this);
6447 };
6448
6449 CallExpression.prototype.hasEffects = function hasEffects () {
6450 return callHasEffects( this.scope, this.callee, false );
6451 };
6452
6453 CallExpression.prototype.initialiseNode = function initialiseNode () {
6454 if ( isProgramLevel( this ) ) {
6455 this.module.bundle.dependentExpressions.push( this );
6456 }
6457 };
6458
6459 CallExpression.prototype.isUsedByBundle = function isUsedByBundle () {
6460 return this.hasEffects();
6461 };
6462
6463 return CallExpression;
6464}(Node$1));
6465
6466var CatchClause = (function (Node) {
6467 function CatchClause () {
6468 Node.apply(this, arguments);
6469 }
6470
6471 if ( Node ) CatchClause.__proto__ = Node;
6472 CatchClause.prototype = Object.create( Node && Node.prototype );
6473 CatchClause.prototype.constructor = CatchClause;
6474
6475 CatchClause.prototype.initialiseChildren = function initialiseChildren () {
6476 var this$1 = this;
6477
6478 if ( this.param ) {
6479 this.param.initialise( this.scope );
6480 extractNames( this.param ).forEach( function (name) { return this$1.scope.addDeclaration( name, null, false, true ); } );
6481 }
6482 this.body.initialiseAndReplaceScope( this.scope );
6483 };
6484
6485 CatchClause.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6486 this.scope = new Scope( {
6487 parent: parentScope,
6488 isBlockScope: true,
6489 isLexicalBoundary: false
6490 } );
6491 };
6492
6493 return CatchClause;
6494}(Node$1));
6495
6496var ClassExpression = (function (Node) {
6497 function ClassExpression () {
6498 Node.apply(this, arguments);
6499 }
6500
6501 if ( Node ) ClassExpression.__proto__ = Node;
6502 ClassExpression.prototype = Object.create( Node && Node.prototype );
6503 ClassExpression.prototype.constructor = ClassExpression;
6504
6505 ClassExpression.prototype.activate = function activate () {
6506 if ( this.activated ) { return; }
6507 this.activated = true;
6508
6509 if ( this.superClass ) { this.superClass.run(); }
6510 this.body.run();
6511 };
6512
6513 ClassExpression.prototype.addReference = function addReference () {};
6514
6515 ClassExpression.prototype.getName = function getName () {
6516 return this.name;
6517 };
6518
6519 ClassExpression.prototype.initialiseChildren = function initialiseChildren () {
6520 if ( this.superClass ) {
6521 this.superClass.initialise( this.scope );
6522 }
6523 this.body.initialise( this.scope );
6524 };
6525
6526 ClassExpression.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6527 this.scope = new Scope( {
6528 parent: parentScope,
6529 isBlockScope: true
6530 } );
6531 };
6532
6533 return ClassExpression;
6534}(Node$1));
6535
6536var ClassDeclaration = (function (Class$$1) {
6537 function ClassDeclaration () {
6538 Class$$1.apply(this, arguments);
6539 }
6540
6541 if ( Class$$1 ) ClassDeclaration.__proto__ = Class$$1;
6542 ClassDeclaration.prototype = Object.create( Class$$1 && Class$$1.prototype );
6543 ClassDeclaration.prototype.constructor = ClassDeclaration;
6544
6545 ClassDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6546 values.add( this );
6547 };
6548
6549 ClassDeclaration.prototype.hasEffects = function hasEffects () {
6550 return false;
6551 };
6552
6553 ClassDeclaration.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
6554 if ( this.id ) {
6555 this.name = this.id.name;
6556 parentScope.addDeclaration( this.name, this, false, false );
6557 this.id.initialise( parentScope );
6558 }
6559 Class$$1.prototype.initialiseChildren.call( this, parentScope );
6560 };
6561
6562 ClassDeclaration.prototype.render = function render ( code, es ) {
6563 if ( !this.module.bundle.treeshake || this.activated ) {
6564 Class$$1.prototype.render.call( this, code, es );
6565 } else {
6566 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6567 }
6568 };
6569
6570 ClassDeclaration.prototype.run = function run () {
6571 if ( this.parent.type === 'ExportDefaultDeclaration' ) {
6572 Class$$1.prototype.run.call(this);
6573 }
6574 };
6575
6576 return ClassDeclaration;
6577}(ClassExpression));
6578
6579var ClassExpression$1 = (function (Class) {
6580 function ClassExpression$$1 () {
6581 Class.apply(this, arguments);
6582 }
6583
6584 if ( Class ) ClassExpression$$1.__proto__ = Class;
6585 ClassExpression$$1.prototype = Object.create( Class && Class.prototype );
6586 ClassExpression$$1.prototype.constructor = ClassExpression$$1;
6587
6588 ClassExpression$$1.prototype.initialiseChildren = function initialiseChildren (parentScope) {
6589 if ( this.id ) {
6590 this.name = this.id.name;
6591 this.scope.addDeclaration( this.name, this, false, false );
6592 this.id.initialise( this.scope );
6593 }
6594 Class.prototype.initialiseChildren.call(this, parentScope);
6595 };
6596
6597 return ClassExpression$$1;
6598}(ClassExpression));
6599
6600var ConditionalExpression = (function (Node) {
6601 function ConditionalExpression () {
6602 Node.apply(this, arguments);
6603 }
6604
6605 if ( Node ) ConditionalExpression.__proto__ = Node;
6606 ConditionalExpression.prototype = Object.create( Node && Node.prototype );
6607 ConditionalExpression.prototype.constructor = ConditionalExpression;
6608
6609 ConditionalExpression.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
6610 if ( this.module.bundle.treeshake ) {
6611 this.testValue = this.test.getValue();
6612
6613 if ( this.testValue === UNKNOWN ) {
6614 Node.prototype.initialiseChildren.call( this, parentScope );
6615 } else if ( this.testValue ) {
6616 this.consequent.initialise( this.scope );
6617 this.alternate = null;
6618 } else if ( this.alternate ) {
6619 this.alternate.initialise( this.scope );
6620 this.consequent = null;
6621 }
6622 } else {
6623 Node.prototype.initialiseChildren.call( this, parentScope );
6624 }
6625 };
6626
6627 ConditionalExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6628 var testValue = this.test.getValue();
6629
6630 if ( testValue === UNKNOWN ) {
6631 values.add( this.consequent ).add( this.alternate );
6632 } else {
6633 values.add( testValue ? this.consequent : this.alternate );
6634 }
6635 };
6636
6637 ConditionalExpression.prototype.getValue = function getValue () {
6638 var testValue = this.test.getValue();
6639 if ( testValue === UNKNOWN ) { return UNKNOWN; }
6640
6641 return testValue ? this.consequent.getValue() : this.alternate.getValue();
6642 };
6643
6644 ConditionalExpression.prototype.render = function render ( code, es ) {
6645 if ( !this.module.bundle.treeshake ) {
6646 Node.prototype.render.call( this, code, es );
6647 }
6648
6649 else {
6650 if ( this.testValue === UNKNOWN ) {
6651 Node.prototype.render.call( this, code, es );
6652 }
6653
6654 else if ( this.testValue ) {
6655 code.remove( this.start, this.consequent.start );
6656 code.remove( this.consequent.end, this.end );
6657 if ( this.consequent.type === 'SequenceExpression' ) {
6658 code.prependRight( this.consequent.start, '(' );
6659 code.appendLeft( this.consequent.end, ')' );
6660 }
6661 this.consequent.render( code, es );
6662 } else {
6663 code.remove( this.start, this.alternate.start );
6664 code.remove( this.alternate.end, this.end );
6665 if ( this.alternate.type === 'SequenceExpression' ) {
6666 code.prependRight( this.alternate.start, '(' );
6667 code.appendLeft( this.alternate.end, ')' );
6668 }
6669 this.alternate.render( code, es );
6670 }
6671 }
6672 };
6673
6674 return ConditionalExpression;
6675}(Node$1));
6676
6677var EmptyStatement = (function (Statement$$1) {
6678 function EmptyStatement () {
6679 Statement$$1.apply(this, arguments);
6680 }
6681
6682 if ( Statement$$1 ) EmptyStatement.__proto__ = Statement$$1;
6683 EmptyStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6684 EmptyStatement.prototype.constructor = EmptyStatement;
6685
6686 EmptyStatement.prototype.render = function render ( code ) {
6687 if ( this.parent.type === 'BlockStatement' || this.parent.type === 'Program' ) {
6688 code.remove( this.start, this.end );
6689 }
6690 };
6691
6692 return EmptyStatement;
6693}(Statement));
6694
6695var ExportAllDeclaration = (function (Node) {
6696 function ExportAllDeclaration () {
6697 Node.apply(this, arguments);
6698 }
6699
6700 if ( Node ) ExportAllDeclaration.__proto__ = Node;
6701 ExportAllDeclaration.prototype = Object.create( Node && Node.prototype );
6702 ExportAllDeclaration.prototype.constructor = ExportAllDeclaration;
6703
6704 ExportAllDeclaration.prototype.initialiseNode = function initialiseNode () {
6705 this.isExportDeclaration = true;
6706 };
6707
6708 ExportAllDeclaration.prototype.render = function render ( code ) {
6709 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6710 };
6711
6712 return ExportAllDeclaration;
6713}(Node$1));
6714
6715var functionOrClassDeclaration = /^(?:Function|Class)Declaration/;
6716
6717var ExportDefaultDeclaration = (function (Node) {
6718 function ExportDefaultDeclaration () {
6719 Node.apply(this, arguments);
6720 }
6721
6722 if ( Node ) ExportDefaultDeclaration.__proto__ = Node;
6723 ExportDefaultDeclaration.prototype = Object.create( Node && Node.prototype );
6724 ExportDefaultDeclaration.prototype.constructor = ExportDefaultDeclaration;
6725
6726 ExportDefaultDeclaration.prototype.activate = function activate () {
6727 if ( this.activated ) { return; }
6728 this.activated = true;
6729
6730 this.run();
6731 };
6732
6733 ExportDefaultDeclaration.prototype.addReference = function addReference ( reference ) {
6734 this.name = reference.name;
6735 if ( this.original ) { this.original.addReference( reference ); }
6736 };
6737
6738 ExportDefaultDeclaration.prototype.bind = function bind () {
6739 var name = ( this.declaration.id && this.declaration.id.name ) || this.declaration.name;
6740 if ( name ) { this.original = this.scope.findDeclaration( name ); }
6741
6742 this.declaration.bind();
6743 };
6744
6745 ExportDefaultDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
6746 this.declaration.gatherPossibleValues( values );
6747 };
6748
6749 ExportDefaultDeclaration.prototype.getName = function getName ( es ) {
6750 if ( this.original && !this.original.isReassigned ) {
6751 return this.original.getName( es );
6752 }
6753
6754 return this.name;
6755 };
6756
6757 ExportDefaultDeclaration.prototype.initialiseNode = function initialiseNode () {
6758 this.isExportDeclaration = true;
6759 this.isDefault = true;
6760
6761 this.name = ( this.declaration.id && this.declaration.id.name ) || this.declaration.name || this.module.basename();
6762 this.scope.declarations.default = this;
6763 };
6764
6765 // TODO this is total chaos, tidy it up
6766 ExportDefaultDeclaration.prototype.render = function render ( code, es ) {
6767 var treeshake = this.module.bundle.treeshake;
6768 var name = this.getName( es );
6769
6770 // paren workaround: find first non-whitespace character position after `export default`
6771 var declaration_start;
6772 if ( this.declaration ) {
6773 var statementStr = code.original.slice( this.start, this.end );
6774 declaration_start = this.start + statementStr.match( /^\s*export\s+default\s*/ )[ 0 ].length;
6775 }
6776
6777 if ( this.shouldInclude || this.declaration.activated ) {
6778 if ( this.activated ) {
6779 if ( functionOrClassDeclaration.test( this.declaration.type ) ) {
6780 if ( this.declaration.id ) {
6781 code.remove( this.start, declaration_start );
6782 } else {
6783 code.overwrite( this.start, declaration_start, ("var " + (this.name) + " = ") );
6784 if ( code.original[ this.end - 1 ] !== ';' ) { code.appendLeft( this.end, ';' ); }
6785 }
6786 }
6787
6788 else {
6789 if ( this.original && this.original.getName( es ) === name ) {
6790 // prevent `var foo = foo`
6791 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6792 return; // don't render children. TODO this seems like a bit of a hack
6793 } else {
6794 code.overwrite( this.start, declaration_start, ((this.module.bundle.varOrConst) + " " + name + " = ") );
6795 }
6796
6797 this.insertSemicolon( code );
6798 }
6799 } else {
6800 // remove `var foo` from `var foo = bar()`, if `foo` is unused
6801 code.remove( this.start, declaration_start );
6802 }
6803
6804 Node.prototype.render.call( this, code, es );
6805 } else {
6806 if ( treeshake ) {
6807 if ( functionOrClassDeclaration.test( this.declaration.type ) ) {
6808 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
6809 } else {
6810 var hasEffects = this.declaration.hasEffects();
6811 code.remove( this.start, hasEffects ? declaration_start : this.next || this.end );
6812 }
6813 } else if ( name === this.declaration.name ) {
6814 code.remove( this.start, this.next || this.end );
6815 } else {
6816 code.overwrite( this.start, declaration_start, ((this.module.bundle.varOrConst) + " " + name + " = ") );
6817 }
6818 // code.remove( this.start, this.next || this.end );
6819 }
6820 };
6821
6822 ExportDefaultDeclaration.prototype.run = function run () {
6823 this.shouldInclude = true;
6824 Node.prototype.run.call(this);
6825
6826 // special case (TODO is this correct?)
6827 if ( functionOrClassDeclaration.test( this.declaration.type ) && !this.declaration.id ) {
6828 this.declaration.activate();
6829 }
6830 };
6831
6832 return ExportDefaultDeclaration;
6833}(Node$1));
6834
6835var ExportNamedDeclaration = (function (Node) {
6836 function ExportNamedDeclaration () {
6837 Node.apply(this, arguments);
6838 }
6839
6840 if ( Node ) ExportNamedDeclaration.__proto__ = Node;
6841 ExportNamedDeclaration.prototype = Object.create( Node && Node.prototype );
6842 ExportNamedDeclaration.prototype.constructor = ExportNamedDeclaration;
6843
6844 ExportNamedDeclaration.prototype.bind = function bind () {
6845 if ( this.declaration ) { this.declaration.bind(); }
6846 };
6847
6848 ExportNamedDeclaration.prototype.initialiseNode = function initialiseNode () {
6849 this.isExportDeclaration = true;
6850 };
6851
6852 ExportNamedDeclaration.prototype.render = function render ( code, es ) {
6853 if ( this.declaration ) {
6854 code.remove( this.start, this.declaration.start );
6855 this.declaration.render( code, es );
6856 } else {
6857 var start = this.leadingCommentStart || this.start;
6858 var end = this.next || this.end;
6859
6860 if ( this.defaultExport ) {
6861 var name = this.defaultExport.getName( es );
6862 var originalName = this.defaultExport.original.getName( es );
6863
6864 if ( name !== originalName ) {
6865 code.overwrite( start, end, ("var " + name + " = " + originalName + ";") );
6866 return;
6867 }
6868 }
6869
6870 code.remove( start, end );
6871 }
6872 };
6873
6874 return ExportNamedDeclaration;
6875}(Node$1));
6876
6877var ExpressionStatement = (function (Statement$$1) {
6878 function ExpressionStatement () {
6879 Statement$$1.apply(this, arguments);
6880 }
6881
6882 if ( Statement$$1 ) ExpressionStatement.__proto__ = Statement$$1;
6883 ExpressionStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6884 ExpressionStatement.prototype.constructor = ExpressionStatement;
6885
6886 ExpressionStatement.prototype.render = function render ( code, es ) {
6887 Statement$$1.prototype.render.call( this, code, es );
6888 if ( this.shouldInclude ) { this.insertSemicolon( code ); }
6889 };
6890
6891 return ExpressionStatement;
6892}(Statement));
6893
6894var ForStatement = (function (Statement$$1) {
6895 function ForStatement () {
6896 Statement$$1.apply(this, arguments);
6897 }
6898
6899 if ( Statement$$1 ) ForStatement.__proto__ = Statement$$1;
6900 ForStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6901 ForStatement.prototype.constructor = ForStatement;
6902
6903 ForStatement.prototype.initialiseChildren = function initialiseChildren () {
6904 if ( this.init ) { this.init.initialise( this.scope ); }
6905 if ( this.test ) { this.test.initialise( this.scope ); }
6906 if ( this.update ) { this.update.initialise( this.scope ); }
6907
6908 if ( this.body.type === 'BlockStatement' ) {
6909 this.body.initialiseScope( this.scope );
6910 this.body.initialiseChildren();
6911 } else {
6912 this.body.initialise( this.scope );
6913 }
6914 };
6915
6916 ForStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6917 this.scope = new Scope( {
6918 parent: parentScope,
6919 isBlockScope: true,
6920 isLexicalBoundary: false
6921 } );
6922 };
6923
6924 return ForStatement;
6925}(Statement));
6926
6927function assignToForLoopLeft ( node, scope, value ) {
6928 if ( node.type === 'VariableDeclaration' ) {
6929 for ( var proxy of node.declarations[0].proxies.values() ) {
6930 proxy.possibleValues.add( value );
6931 }
6932 }
6933
6934 else {
6935 if ( node.type === 'MemberExpression' ) {
6936 // apparently this is legal JavaScript? Though I don't know what
6937 // kind of monster would write `for ( foo.bar of thing ) {...}`
6938
6939 // for now, do nothing, as I'm not sure anything needs to happen...
6940 }
6941
6942 else {
6943 for ( var name of extractNames( node ) ) {
6944 var declaration = scope.findDeclaration( name );
6945 if ( declaration.possibleValues ) {
6946 declaration.possibleValues.add( value );
6947 }
6948 }
6949 }
6950 }
6951}
6952
6953var ForInStatement = (function (Statement$$1) {
6954 function ForInStatement () {
6955 Statement$$1.apply(this, arguments);
6956 }
6957
6958 if ( Statement$$1 ) ForInStatement.__proto__ = Statement$$1;
6959 ForInStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6960 ForInStatement.prototype.constructor = ForInStatement;
6961
6962 ForInStatement.prototype.initialiseChildren = function initialiseChildren () {
6963 this.left.initialise( this.scope );
6964 this.right.initialise( this.scope.parent );
6965 this.body.initialiseAndReplaceScope ?
6966 this.body.initialiseAndReplaceScope( this.scope ) :
6967 this.body.initialise( this.scope );
6968 assignToForLoopLeft( this.left, this.scope, STRING );
6969 };
6970
6971 ForInStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
6972 this.scope = new Scope({
6973 parent: parentScope,
6974 isBlockScope: true,
6975 isLexicalBoundary: false
6976 });
6977 };
6978
6979 return ForInStatement;
6980}(Statement));
6981
6982var ForOfStatement = (function (Statement$$1) {
6983 function ForOfStatement () {
6984 Statement$$1.apply(this, arguments);
6985 }
6986
6987 if ( Statement$$1 ) ForOfStatement.__proto__ = Statement$$1;
6988 ForOfStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
6989 ForOfStatement.prototype.constructor = ForOfStatement;
6990
6991 ForOfStatement.prototype.initialiseChildren = function initialiseChildren () {
6992 this.left.initialise( this.scope );
6993 this.right.initialise( this.scope.parent );
6994 this.body.initialiseAndReplaceScope ?
6995 this.body.initialiseAndReplaceScope( this.scope ) :
6996 this.body.initialise( this.scope );
6997 assignToForLoopLeft( this.left, this.scope, UNKNOWN );
6998 };
6999
7000 ForOfStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
7001 this.scope = new Scope( {
7002 parent: parentScope,
7003 isBlockScope: true,
7004 isLexicalBoundary: false
7005 } );
7006 };
7007
7008 return ForOfStatement;
7009}(Statement));
7010
7011var FunctionDeclaration = (function (Function) {
7012 function FunctionDeclaration () {
7013 Function.apply(this, arguments);
7014 }
7015
7016 if ( Function ) FunctionDeclaration.__proto__ = Function;
7017 FunctionDeclaration.prototype = Object.create( Function && Function.prototype );
7018 FunctionDeclaration.prototype.constructor = FunctionDeclaration;
7019
7020 FunctionDeclaration.prototype.activate = function activate () {
7021 if ( this.activated ) { return; }
7022 this.activated = true;
7023
7024 this.params.forEach( function (param) { return param.run(); } ); // in case of assignment patterns
7025 this.body.run();
7026 };
7027
7028 FunctionDeclaration.prototype.addReference = function addReference () {};
7029
7030 FunctionDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7031 values.add( this );
7032 };
7033
7034 FunctionDeclaration.prototype.getName = function getName () {
7035 return this.name;
7036 };
7037
7038 FunctionDeclaration.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7039 if ( this.id ) {
7040 this.name = this.id.name; // may be overridden by bundle.deconflict
7041 parentScope.addDeclaration( this.name, this, false, false );
7042 this.id.initialise( parentScope );
7043 }
7044 Function.prototype.initialiseChildren.call( this, parentScope );
7045 };
7046
7047 FunctionDeclaration.prototype.render = function render ( code, es ) {
7048 if ( !this.module.bundle.treeshake || this.activated ) {
7049 Function.prototype.render.call( this, code, es );
7050 } else {
7051 code.remove( this.leadingCommentStart || this.start, this.next || this.end );
7052 }
7053 };
7054
7055 FunctionDeclaration.prototype.run = function run () {
7056 if ( this.parent.type === 'ExportDefaultDeclaration' ) {
7057 Function.prototype.run.call(this);
7058 }
7059 };
7060
7061 return FunctionDeclaration;
7062}(Function$1));
7063
7064var FunctionExpression = (function (Function) {
7065 function FunctionExpression () {
7066 Function.apply(this, arguments);
7067 }
7068
7069 if ( Function ) FunctionExpression.__proto__ = Function;
7070 FunctionExpression.prototype = Object.create( Function && Function.prototype );
7071 FunctionExpression.prototype.constructor = FunctionExpression;
7072
7073 FunctionExpression.prototype.activate = function activate () {
7074 if ( this.activated ) { return; }
7075 this.activated = true;
7076
7077 this.params.forEach( function (param) { return param.run(); } ); // in case of assignment patterns
7078 this.body.run();
7079 };
7080
7081 FunctionExpression.prototype.addReference = function addReference () {};
7082
7083 FunctionExpression.prototype.getName = function getName () {
7084 return this.name;
7085 };
7086
7087 FunctionExpression.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7088 if ( this.id ) {
7089 this.name = this.id.name; // may be overridden by bundle.deconflict
7090 this.scope.addDeclaration( this.name, this, false, false );
7091 this.id.initialise( this.scope );
7092 }
7093 Function.prototype.initialiseChildren.call( this, parentScope );
7094 };
7095
7096 return FunctionExpression;
7097}(Function$1));
7098
7099function isAssignmentPatternLhs (node, parent) {
7100 // special case: `({ foo = 42 }) => {...}`
7101 // `foo` actually has two different parents, the Property of the
7102 // ObjectPattern, and the AssignmentPattern. In one case it's a
7103 // reference, in one case it's not, because it's shorthand for
7104 // `({ foo: foo = 42 }) => {...}`. But unlike a regular shorthand
7105 // property, the `foo` node appears at different levels of the tree
7106 return (
7107 parent.type === "Property" &&
7108 parent.shorthand &&
7109 parent.value.type === "AssignmentPattern" &&
7110 parent.value.left === node
7111 );
7112}
7113
7114var Identifier = (function (Node) {
7115 function Identifier () {
7116 Node.apply(this, arguments);
7117 }
7118
7119 if ( Node ) Identifier.__proto__ = Node;
7120 Identifier.prototype = Object.create( Node && Node.prototype );
7121 Identifier.prototype.constructor = Identifier;
7122
7123 Identifier.prototype.bind = function bind () {
7124 if (isReference(this, this.parent) || isAssignmentPatternLhs(this, this.parent)) {
7125 this.declaration = this.scope.findDeclaration(this.name);
7126 this.declaration.addReference(this); // TODO necessary?
7127 }
7128 };
7129
7130 Identifier.prototype.gatherPossibleValues = function gatherPossibleValues (values) {
7131 if (isReference(this, this.parent)) {
7132 values.add(this);
7133 }
7134 };
7135
7136 Identifier.prototype.render = function render (code, es) {
7137 if (this.declaration) {
7138 var name = this.declaration.getName(es);
7139 if (name !== this.name) {
7140 code.overwrite(this.start, this.end, name, { storeName: true, contentOnly: false });
7141
7142 // special case
7143 if (this.parent.type === "Property" && this.parent.shorthand) {
7144 code.appendLeft(this.start, ((this.name) + ": "));
7145 }
7146 }
7147 }
7148 };
7149
7150 Identifier.prototype.run = function run () {
7151 if (this.declaration) { this.declaration.activate(); }
7152 };
7153
7154 return Identifier;
7155}(Node$1));
7156
7157// Statement types which may contain if-statements as direct children.
7158var statementsWithIfStatements = new Set( [
7159 'DoWhileStatement',
7160 'ForInStatement',
7161 'ForOfStatement',
7162 'ForStatement',
7163 'IfStatement',
7164 'WhileStatement'
7165] );
7166
7167function handleVarDeclarations ( node, scope ) {
7168 var hoistedVars = [];
7169
7170 function visit ( node ) {
7171 if ( node.type === 'VariableDeclaration' && node.kind === 'var' ) {
7172 node.declarations.forEach( function (declarator) {
7173 declarator.init = null;
7174 declarator.initialise( scope );
7175
7176 extractNames( declarator.id ).forEach( function (name) {
7177 if ( !~hoistedVars.indexOf( name ) ) { hoistedVars.push( name ); }
7178 } );
7179 } );
7180 }
7181
7182 else if ( !/Function/.test( node.type ) ) {
7183 node.eachChild( visit );
7184 }
7185 }
7186
7187 visit( node );
7188
7189 return hoistedVars;
7190}
7191
7192// TODO DRY this out
7193var IfStatement = (function (Statement$$1) {
7194 function IfStatement () {
7195 Statement$$1.apply(this, arguments);
7196 }
7197
7198 if ( Statement$$1 ) IfStatement.__proto__ = Statement$$1;
7199 IfStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
7200 IfStatement.prototype.constructor = IfStatement;
7201
7202 IfStatement.prototype.initialiseChildren = function initialiseChildren ( parentScope ) {
7203 if ( this.module.bundle.treeshake ) {
7204 this.testValue = this.test.getValue();
7205
7206 if ( this.testValue === UNKNOWN ) {
7207 Statement$$1.prototype.initialiseChildren.call( this, parentScope );
7208 } else if ( this.testValue ) {
7209 this.consequent.initialise( this.scope );
7210 if ( this.alternate ) {
7211 this.hoistedVars = handleVarDeclarations( this.alternate, this.scope );
7212 this.alternate = null;
7213 }
7214 } else {
7215 if ( this.alternate ) {
7216 this.alternate.initialise( this.scope );
7217 }
7218 this.hoistedVars = handleVarDeclarations( this.consequent, this.scope );
7219 this.consequent = null;
7220 }
7221 } else {
7222 Statement$$1.prototype.initialiseChildren.call( this, parentScope );
7223 }
7224 };
7225
7226 IfStatement.prototype.render = function render ( code, es ) {
7227 var this$1 = this;
7228
7229 if ( this.module.bundle.treeshake ) {
7230 if ( this.testValue === UNKNOWN ) {
7231 Statement$$1.prototype.render.call( this, code, es );
7232 }
7233
7234 else {
7235 code.overwrite( this.test.start, this.test.end, JSON.stringify( this.testValue ) );
7236
7237 // TODO if no block-scoped declarations, remove enclosing
7238 // curlies and dedent block (if there is a block)
7239
7240 if ( this.hoistedVars ) {
7241 var names = this.hoistedVars
7242 .map( function (name) {
7243 var declaration = this$1.scope.findDeclaration( name );
7244 return declaration.activated ? declaration.getName() : null;
7245 } )
7246 .filter( Boolean );
7247
7248 if ( names.length > 0 ) {
7249 code.appendLeft( this.start, ("var " + (names.join( ', ' )) + ";\n\n") );
7250 }
7251 }
7252
7253 if ( this.testValue ) {
7254 code.remove( this.start, this.consequent.start );
7255 code.remove( this.consequent.end, this.end );
7256 this.consequent.render( code, es );
7257 }
7258
7259 else {
7260 code.remove( this.start, this.alternate ? this.alternate.start : this.next || this.end );
7261
7262 if ( this.alternate ) {
7263 this.alternate.render( code, es );
7264 }
7265
7266 else if ( statementsWithIfStatements.has( this.parent.type ) ) {
7267 code.prependRight( this.start, '{}' );
7268 }
7269 }
7270 }
7271 }
7272
7273 else {
7274 Statement$$1.prototype.render.call( this, code, es );
7275 }
7276 };
7277
7278 return IfStatement;
7279}(Statement));
7280
7281var ImportDeclaration = (function (Node) {
7282 function ImportDeclaration () {
7283 Node.apply(this, arguments);
7284 }
7285
7286 if ( Node ) ImportDeclaration.__proto__ = Node;
7287 ImportDeclaration.prototype = Object.create( Node && Node.prototype );
7288 ImportDeclaration.prototype.constructor = ImportDeclaration;
7289
7290 ImportDeclaration.prototype.bind = function bind () {
7291 // noop
7292 // TODO do the inter-module binding setup here?
7293 };
7294
7295 ImportDeclaration.prototype.initialiseNode = function initialiseNode () {
7296 this.isImportDeclaration = true;
7297 };
7298
7299 ImportDeclaration.prototype.render = function render ( code ) {
7300 code.remove( this.start, this.next || this.end );
7301 };
7302
7303 return ImportDeclaration;
7304}(Node$1));
7305
7306var Literal = (function (Node) {
7307 function Literal () {
7308 Node.apply(this, arguments);
7309 }
7310
7311 if ( Node ) Literal.__proto__ = Node;
7312 Literal.prototype = Object.create( Node && Node.prototype );
7313 Literal.prototype.constructor = Literal;
7314
7315 Literal.prototype.getValue = function getValue () {
7316 return this.value;
7317 };
7318
7319 Literal.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7320 values.add( this );
7321 };
7322
7323 Literal.prototype.render = function render ( code ) {
7324 if ( typeof this.value === 'string' ) {
7325 code.indentExclusionRanges.push( [ this.start + 1, this.end - 1 ] );
7326 }
7327 };
7328
7329 return Literal;
7330}(Node$1));
7331
7332var operators$1 = {
7333 '&&': function ( left, right ) { return left && right; },
7334 '||': function ( left, right ) { return left || right; }
7335};
7336
7337var LogicalExpression = (function (Node) {
7338 function LogicalExpression () {
7339 Node.apply(this, arguments);
7340 }
7341
7342 if ( Node ) LogicalExpression.__proto__ = Node;
7343 LogicalExpression.prototype = Object.create( Node && Node.prototype );
7344 LogicalExpression.prototype.constructor = LogicalExpression;
7345
7346 LogicalExpression.prototype.getValue = function getValue () {
7347 var leftValue = this.left.getValue();
7348 if ( leftValue === UNKNOWN ) { return UNKNOWN; }
7349
7350 var rightValue = this.right.getValue();
7351 if ( rightValue === UNKNOWN ) { return UNKNOWN; }
7352
7353 return operators$1[ this.operator ]( leftValue, rightValue );
7354 };
7355
7356 return LogicalExpression;
7357}(Node$1));
7358
7359var validProp = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
7360
7361var Keypath = function Keypath ( node ) {
7362 var this$1 = this;
7363
7364 this.parts = [];
7365
7366 while ( node.type === 'MemberExpression' ) {
7367 var prop = node.property;
7368
7369 if ( node.computed ) {
7370 if ( prop.type !== 'Literal' || typeof prop.value !== 'string' || !validProp.test( prop.value ) ) {
7371 this$1.computed = true;
7372 return;
7373 }
7374 }
7375
7376 this$1.parts.unshift( prop );
7377 node = node.object;
7378 }
7379
7380 this.root = node;
7381};
7382
7383var MemberExpression = (function (Node) {
7384 function MemberExpression () {
7385 Node.apply(this, arguments);
7386 }
7387
7388 if ( Node ) MemberExpression.__proto__ = Node;
7389 MemberExpression.prototype = Object.create( Node && Node.prototype );
7390 MemberExpression.prototype.constructor = MemberExpression;
7391
7392 MemberExpression.prototype.bind = function bind () {
7393 var this$1 = this;
7394
7395 // if this resolves to a namespaced declaration, prepare
7396 // to replace it
7397 // TODO this code is a bit inefficient
7398 var keypath = new Keypath( this );
7399
7400 if ( !keypath.computed && keypath.root.type === 'Identifier' ) {
7401 var declaration = this.scope.findDeclaration( keypath.root.name );
7402
7403 while ( declaration.isNamespace && keypath.parts.length ) {
7404 var exporterId = declaration.module.id;
7405
7406 var part = keypath.parts[ 0 ];
7407 declaration = declaration.module.traceExport( part.name || part.value );
7408
7409 if ( !declaration ) {
7410 this$1.module.warn( {
7411 code: 'MISSING_EXPORT',
7412 missing: part.name || part.value,
7413 importer: relativeId( this$1.module.id ),
7414 exporter: relativeId( exporterId ),
7415 message: ("'" + (part.name || part.value) + "' is not exported by '" + (relativeId( exporterId )) + "'"),
7416 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
7417 }, part.start );
7418 this$1.replacement = 'undefined';
7419 return;
7420 }
7421
7422 keypath.parts.shift();
7423 }
7424
7425 if ( keypath.parts.length ) {
7426 Node.prototype.bind.call(this);
7427 return; // not a namespaced declaration
7428 }
7429
7430 this.declaration = declaration;
7431
7432 if ( declaration.isExternal ) {
7433 declaration.module.suggestName( keypath.root.name );
7434 }
7435 }
7436
7437 else {
7438 Node.prototype.bind.call(this);
7439 }
7440 };
7441
7442 MemberExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7443 values.add( UNKNOWN ); // TODO
7444 };
7445
7446 MemberExpression.prototype.render = function render ( code, es ) {
7447 if ( this.declaration ) {
7448 var name = this.declaration.getName( es );
7449 if ( name !== this.name ) { code.overwrite( this.start, this.end, name, { storeName: true, contentOnly: false } ); }
7450 }
7451
7452 else if ( this.replacement ) {
7453 code.overwrite( this.start, this.end, this.replacement, { storeName: true, contentOnly: false } );
7454 }
7455
7456 Node.prototype.render.call( this, code, es );
7457 };
7458
7459 MemberExpression.prototype.run = function run () {
7460 if ( this.declaration ) { this.declaration.activate(); }
7461 Node.prototype.run.call(this);
7462 };
7463
7464 return MemberExpression;
7465}(Node$1));
7466
7467var NewExpression = (function (Node) {
7468 function NewExpression () {
7469 Node.apply(this, arguments);
7470 }
7471
7472 if ( Node ) NewExpression.__proto__ = Node;
7473 NewExpression.prototype = Object.create( Node && Node.prototype );
7474 NewExpression.prototype.constructor = NewExpression;
7475
7476 NewExpression.prototype.hasEffects = function hasEffects () {
7477 return callHasEffects( this.scope, this.callee, true );
7478 };
7479
7480 return NewExpression;
7481}(Node$1));
7482
7483var ObjectExpression = (function (Node) {
7484 function ObjectExpression () {
7485 Node.apply(this, arguments);
7486 }
7487
7488 if ( Node ) ObjectExpression.__proto__ = Node;
7489 ObjectExpression.prototype = Object.create( Node && Node.prototype );
7490 ObjectExpression.prototype.constructor = ObjectExpression;
7491
7492 ObjectExpression.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7493 values.add( OBJECT );
7494 };
7495
7496 return ObjectExpression;
7497}(Node$1));
7498
7499var SwitchStatement = (function (Statement$$1) {
7500 function SwitchStatement () {
7501 Statement$$1.apply(this, arguments);
7502 }
7503
7504 if ( Statement$$1 ) SwitchStatement.__proto__ = Statement$$1;
7505 SwitchStatement.prototype = Object.create( Statement$$1 && Statement$$1.prototype );
7506 SwitchStatement.prototype.constructor = SwitchStatement;
7507
7508 SwitchStatement.prototype.initialiseScope = function initialiseScope ( parentScope ) {
7509 this.scope = new Scope( {
7510 parent: parentScope,
7511 isBlockScope: true,
7512 isLexicalBoundary: false
7513 } );
7514 };
7515
7516 return SwitchStatement;
7517}(Statement));
7518
7519var TaggedTemplateExpression = (function (Node) {
7520 function TaggedTemplateExpression () {
7521 Node.apply(this, arguments);
7522 }
7523
7524 if ( Node ) TaggedTemplateExpression.__proto__ = Node;
7525 TaggedTemplateExpression.prototype = Object.create( Node && Node.prototype );
7526 TaggedTemplateExpression.prototype.constructor = TaggedTemplateExpression;
7527
7528 TaggedTemplateExpression.prototype.bind = function bind () {
7529 if ( this.tag.type === 'Identifier' ) {
7530 var declaration = this.scope.findDeclaration( this.tag.name );
7531
7532 if ( declaration.isNamespace ) {
7533 this.module.error({
7534 code: 'CANNOT_CALL_NAMESPACE',
7535 message: ("Cannot call a namespace ('" + (this.tag.name) + "')")
7536 }, this.start );
7537 }
7538
7539 if ( this.tag.name === 'eval' && declaration.isGlobal ) {
7540 this.module.warn({
7541 code: 'EVAL',
7542 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
7543 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval'
7544 }, this.start );
7545 }
7546 }
7547
7548 Node.prototype.bind.call(this);
7549 };
7550
7551 TaggedTemplateExpression.prototype.hasEffects = function hasEffects () {
7552 return this.quasi.hasEffects() || callHasEffects( this.scope, this.tag, false );
7553 };
7554
7555 TaggedTemplateExpression.prototype.initialiseNode = function initialiseNode () {
7556 if ( isProgramLevel( this ) ) {
7557 this.module.bundle.dependentExpressions.push( this );
7558 }
7559 };
7560
7561 TaggedTemplateExpression.prototype.isUsedByBundle = function isUsedByBundle () {
7562 return this.hasEffects();
7563 };
7564
7565 return TaggedTemplateExpression;
7566}(Node$1));
7567
7568var TemplateLiteral = (function (Node) {
7569 function TemplateLiteral () {
7570 Node.apply(this, arguments);
7571 }
7572
7573 if ( Node ) TemplateLiteral.__proto__ = Node;
7574 TemplateLiteral.prototype = Object.create( Node && Node.prototype );
7575 TemplateLiteral.prototype.constructor = TemplateLiteral;
7576
7577 TemplateLiteral.prototype.render = function render ( code, es ) {
7578 code.indentExclusionRanges.push( [ this.start, this.end ] );
7579 Node.prototype.render.call( this, code, es );
7580 };
7581
7582 return TemplateLiteral;
7583}(Node$1));
7584
7585var ThisExpression = (function (Node) {
7586 function ThisExpression () {
7587 Node.apply(this, arguments);
7588 }
7589
7590 if ( Node ) ThisExpression.__proto__ = Node;
7591 ThisExpression.prototype = Object.create( Node && Node.prototype );
7592 ThisExpression.prototype.constructor = ThisExpression;
7593
7594 ThisExpression.prototype.initialiseNode = function initialiseNode () {
7595 var lexicalBoundary = this.scope.findLexicalBoundary();
7596
7597 if ( lexicalBoundary.isModuleScope ) {
7598 this.alias = this.module.context;
7599 if ( this.alias === 'undefined' ) {
7600 this.module.warn( {
7601 code: 'THIS_IS_UNDEFINED',
7602 message: "The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten",
7603 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined"
7604 }, this.start );
7605 }
7606 }
7607 };
7608
7609 ThisExpression.prototype.render = function render ( code ) {
7610 if ( this.alias ) {
7611 code.overwrite( this.start, this.end, this.alias, { storeName: true, contentOnly: false } );
7612 }
7613 };
7614
7615 return ThisExpression;
7616}(Node$1));
7617
7618var ThrowStatement = (function (Node) {
7619 function ThrowStatement () {
7620 Node.apply(this, arguments);
7621 }
7622
7623 if ( Node ) ThrowStatement.__proto__ = Node;
7624 ThrowStatement.prototype = Object.create( Node && Node.prototype );
7625 ThrowStatement.prototype.constructor = ThrowStatement;
7626
7627 ThrowStatement.prototype.hasEffects = function hasEffects () {
7628 return true;
7629 };
7630
7631 return ThrowStatement;
7632}(Node$1));
7633
7634var operators$2 = {
7635 '-': function (value) { return -value; },
7636 '+': function (value) { return +value; },
7637 '!': function (value) { return !value; },
7638 '~': function (value) { return ~value; },
7639 typeof: function (value) { return typeof value; },
7640 void: function () { return undefined; },
7641 delete: function () { return UNKNOWN; }
7642};
7643
7644var UnaryExpression = (function (Node) {
7645 function UnaryExpression () {
7646 Node.apply(this, arguments);
7647 }
7648
7649 if ( Node ) UnaryExpression.__proto__ = Node;
7650 UnaryExpression.prototype = Object.create( Node && Node.prototype );
7651 UnaryExpression.prototype.constructor = UnaryExpression;
7652
7653 UnaryExpression.prototype.bind = function bind () {
7654 if ( this.value === UNKNOWN ) { Node.prototype.bind.call(this); }
7655 };
7656
7657 UnaryExpression.prototype.getValue = function getValue () {
7658 var argumentValue = this.argument.getValue();
7659 if ( argumentValue === UNKNOWN ) { return UNKNOWN; }
7660
7661 return operators$2[ this.operator ]( argumentValue );
7662 };
7663
7664 UnaryExpression.prototype.hasEffects = function hasEffects () {
7665 return this.operator === 'delete' || this.argument.hasEffects();
7666 };
7667
7668 UnaryExpression.prototype.initialiseNode = function initialiseNode () {
7669 this.value = this.getValue();
7670 };
7671
7672 return UnaryExpression;
7673}(Node$1));
7674
7675var UpdateExpression = (function (Node) {
7676 function UpdateExpression () {
7677 Node.apply(this, arguments);
7678 }
7679
7680 if ( Node ) UpdateExpression.__proto__ = Node;
7681 UpdateExpression.prototype = Object.create( Node && Node.prototype );
7682 UpdateExpression.prototype.constructor = UpdateExpression;
7683
7684 UpdateExpression.prototype.bind = function bind () {
7685 var subject = this.argument;
7686
7687 this.subject = subject;
7688 disallowIllegalReassignment( this.scope, this.argument );
7689
7690 if ( subject.type === 'Identifier' ) {
7691 var declaration = this.scope.findDeclaration( subject.name );
7692 declaration.isReassigned = true;
7693
7694 if ( declaration.possibleValues ) {
7695 declaration.possibleValues.add( NUMBER );
7696 }
7697 }
7698
7699 Node.prototype.bind.call(this);
7700 };
7701
7702 UpdateExpression.prototype.hasEffects = function hasEffects () {
7703 return isUsedByBundle( this.scope, this.subject );
7704 };
7705
7706 UpdateExpression.prototype.initialiseNode = function initialiseNode () {
7707 this.module.bundle.dependentExpressions.push( this );
7708 };
7709
7710 UpdateExpression.prototype.isUsedByBundle = function isUsedByBundle$1 () {
7711 return isUsedByBundle( this.scope, this.subject );
7712 };
7713
7714 return UpdateExpression;
7715}(Node$1));
7716
7717var DeclaratorProxy = function DeclaratorProxy ( name, declarator, isTopLevel, init ) {
7718 this.name = name;
7719 this.declarator = declarator;
7720
7721 this.activated = false;
7722 this.isReassigned = false;
7723 this.exportName = null;
7724
7725 this.duplicates = [];
7726 this.possibleValues = new Set( init ? [ init ] : null );
7727};
7728
7729DeclaratorProxy.prototype.activate = function activate () {
7730 this.activated = true;
7731 this.declarator.activate();
7732 this.duplicates.forEach( function (dupe) { return dupe.activate(); } );
7733};
7734
7735DeclaratorProxy.prototype.addReference = function addReference () {
7736 /* noop? */
7737};
7738
7739DeclaratorProxy.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
7740 this.possibleValues.forEach( function (value) { return values.add( value ); } );
7741};
7742
7743DeclaratorProxy.prototype.getName = function getName ( es ) {
7744 // TODO desctructuring...
7745 if ( es ) { return this.name; }
7746 if ( !this.isReassigned || !this.exportName ) { return this.name; }
7747
7748 return ("exports." + (this.exportName));
7749};
7750
7751DeclaratorProxy.prototype.toString = function toString () {
7752 return this.name;
7753};
7754
7755var VariableDeclarator = (function (Node) {
7756 function VariableDeclarator () {
7757 Node.apply(this, arguments);
7758 }
7759
7760 if ( Node ) VariableDeclarator.__proto__ = Node;
7761 VariableDeclarator.prototype = Object.create( Node && Node.prototype );
7762 VariableDeclarator.prototype.constructor = VariableDeclarator;
7763
7764 VariableDeclarator.prototype.activate = function activate () {
7765 if ( this.activated ) { return; }
7766 this.activated = true;
7767
7768 this.run();
7769
7770 // if declaration is inside a block, ensure that the block
7771 // is marked for inclusion
7772 if ( this.parent.kind === 'var' ) {
7773 var node = this.parent.parent;
7774 while ( /Statement/.test( node.type ) ) {
7775 node.shouldInclude = true;
7776 node = node.parent;
7777 }
7778 }
7779 };
7780
7781 VariableDeclarator.prototype.hasEffects = function hasEffects () {
7782 return this.init && this.init.hasEffects();
7783 };
7784
7785 VariableDeclarator.prototype.initialiseNode = function initialiseNode () {
7786 var this$1 = this;
7787
7788 this.proxies = new Map();
7789 var lexicalBoundary = this.scope.findLexicalBoundary();
7790 var init = this.init ? ( this.id.type === 'Identifier' ? this.init : UNKNOWN ) : // TODO maybe UNKNOWN is unnecessary
7791 null;
7792
7793 extractNames( this.id ).forEach( function (name) {
7794 var proxy = new DeclaratorProxy( name, this$1, lexicalBoundary.isModuleScope, init );
7795
7796 this$1.proxies.set( name, proxy );
7797 this$1.scope.addDeclaration( name, proxy, this$1.parent.kind === 'var' );
7798 } );
7799 };
7800
7801 VariableDeclarator.prototype.render = function render ( code, es ) {
7802 var this$1 = this;
7803
7804 extractNames( this.id ).forEach( function (name) {
7805 var declaration = this$1.proxies.get( name );
7806
7807 if ( !es && declaration.exportName && declaration.isReassigned ) {
7808 if ( this$1.init ) {
7809 code.overwrite( this$1.start, this$1.id.end, declaration.getName( es ) );
7810 } else if ( this$1.module.bundle.treeshake ) {
7811 code.remove( this$1.start, this$1.end );
7812 }
7813 }
7814 } );
7815
7816 Node.prototype.render.call( this, code, es );
7817 };
7818
7819 return VariableDeclarator;
7820}(Node$1));
7821
7822function getSeparator (code, start) {
7823 var c = start;
7824
7825 while (c > 0 && code[c - 1] !== "\n") {
7826 c -= 1;
7827 if (code[c] === ";" || code[c] === "{") { return "; "; }
7828 }
7829
7830 var lineStart = code.slice(c, start).match(/^\s*/)[0];
7831
7832 return (";\n" + lineStart);
7833}
7834
7835var forStatement = /^For(?:Of|In)?Statement/;
7836
7837var VariableDeclaration = (function (Node) {
7838 function VariableDeclaration () {
7839 Node.apply(this, arguments);
7840 }
7841
7842 if ( Node ) VariableDeclaration.__proto__ = Node;
7843 VariableDeclaration.prototype = Object.create( Node && Node.prototype );
7844 VariableDeclaration.prototype.constructor = VariableDeclaration;
7845
7846 VariableDeclaration.prototype.render = function render (code, es) {
7847 var this$1 = this;
7848
7849 var treeshake = this.module.bundle.treeshake;
7850
7851 var shouldSeparate = false;
7852 var separator;
7853
7854 if (this.scope.isModuleScope && !forStatement.test(this.parent.type)) {
7855 shouldSeparate = true;
7856 separator = getSeparator(this.module.code, this.start);
7857 }
7858
7859 var c = this.start;
7860 var empty = true;
7861
7862 var loop = function ( i ) {
7863 var declarator = this$1.declarations[i];
7864
7865 var prefix = empty ? "" : separator; // TODO indentation
7866
7867 if (declarator.id.type === "Identifier") {
7868 var proxy = declarator.proxies.get(declarator.id.name);
7869 var isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned;
7870
7871 if (isExportedAndReassigned) {
7872 if (declarator.init) {
7873 if (shouldSeparate) { code.overwrite(c, declarator.start, prefix); }
7874 c = declarator.end;
7875 empty = false;
7876 }
7877 } else if (!treeshake || proxy.activated) {
7878 if (shouldSeparate) { code.overwrite(c, declarator.start, ("" + prefix + (this$1.kind) + " ")); } // TODO indentation
7879 c = declarator.end;
7880 empty = false;
7881 }
7882 } else {
7883 var exportAssignments = [];
7884 var activated = false;
7885
7886 extractNames(declarator.id).forEach(function (name) {
7887 var proxy = declarator.proxies.get(name);
7888 var isExportedAndReassigned = !es && proxy.exportName && proxy.isReassigned;
7889
7890 if (isExportedAndReassigned) {
7891 // code.overwrite( c, declarator.start, prefix );
7892 // c = declarator.end;
7893 // empty = false;
7894 exportAssignments.push("TODO");
7895 } else if (declarator.activated) {
7896 activated = true;
7897 }
7898 });
7899
7900 if (!treeshake || activated) {
7901 if (shouldSeparate) { code.overwrite(c, declarator.start, ("" + prefix + (this$1.kind) + " ")); } // TODO indentation
7902 c = declarator.end;
7903 empty = false;
7904 }
7905
7906 if (exportAssignments.length) {
7907 throw new Error("TODO");
7908 }
7909 }
7910
7911 declarator.render(code, es);
7912 };
7913
7914 for (var i = 0; i < this.declarations.length; i += 1) loop( i );
7915
7916 if (treeshake && empty) {
7917 code.remove(this.leadingCommentStart || this.start, this.next || this.end);
7918 } else {
7919 // always include a semi-colon (https://github.com/rollup/rollup/pull/1013),
7920 // unless it's a var declaration in a loop head
7921 var needsSemicolon = !forStatement.test( this.parent.type ) || this === this.parent.body;
7922
7923 if (this.end > c) {
7924 code.overwrite(c, this.end, needsSemicolon ? ";" : "");
7925 } else if (needsSemicolon) {
7926 this.insertSemicolon(code);
7927 }
7928 }
7929 };
7930
7931 return VariableDeclaration;
7932}(Node$1));
7933
7934var nodes = {
7935 ArrayExpression: ArrayExpression,
7936 ArrowFunctionExpression: ArrowFunctionExpression,
7937 AssignmentExpression: AssignmentExpression,
7938 BinaryExpression: BinaryExpression,
7939 BlockStatement: BlockStatement,
7940 CallExpression: CallExpression,
7941 CatchClause: CatchClause,
7942 ClassDeclaration: ClassDeclaration,
7943 ClassExpression: ClassExpression$1,
7944 ConditionalExpression: ConditionalExpression,
7945 DoWhileStatement: Statement,
7946 EmptyStatement: EmptyStatement,
7947 ExportAllDeclaration: ExportAllDeclaration,
7948 ExportDefaultDeclaration: ExportDefaultDeclaration,
7949 ExportNamedDeclaration: ExportNamedDeclaration,
7950 ExpressionStatement: ExpressionStatement,
7951 ForStatement: ForStatement,
7952 ForInStatement: ForInStatement,
7953 ForOfStatement: ForOfStatement,
7954 FunctionDeclaration: FunctionDeclaration,
7955 FunctionExpression: FunctionExpression,
7956 Identifier: Identifier,
7957 IfStatement: IfStatement,
7958 ImportDeclaration: ImportDeclaration,
7959 Literal: Literal,
7960 LogicalExpression: LogicalExpression,
7961 MemberExpression: MemberExpression,
7962 NewExpression: NewExpression,
7963 ObjectExpression: ObjectExpression,
7964 ReturnStatement: Statement,
7965 SwitchStatement: SwitchStatement,
7966 TaggedTemplateExpression: TaggedTemplateExpression,
7967 TemplateLiteral: TemplateLiteral,
7968 ThisExpression: ThisExpression,
7969 ThrowStatement: ThrowStatement,
7970 TryStatement: Statement,
7971 UnaryExpression: UnaryExpression,
7972 UpdateExpression: UpdateExpression,
7973 VariableDeclarator: VariableDeclarator,
7974 VariableDeclaration: VariableDeclaration,
7975 WhileStatement: Statement
7976};
7977
7978var keys$1 = {
7979 Program: [ 'body' ],
7980 Literal: []
7981};
7982
7983var newline = /\n/;
7984
7985function enhance ( ast, module, comments ) {
7986 enhanceNode( ast, module, module, module.magicString );
7987
7988 var comment = comments.shift();
7989
7990 for ( var node of ast.body ) {
7991 if ( comment && ( comment.start < node.start ) ) {
7992 node.leadingCommentStart = comment.start;
7993 }
7994
7995 while ( comment && comment.end < node.end ) { comment = comments.shift(); }
7996
7997 // if the next comment is on the same line as the end of the node,
7998 // treat is as a trailing comment
7999 if ( comment && !newline.test( module.code.slice( node.end, comment.start ) ) ) {
8000 node.trailingCommentEnd = comment.end; // TODO is node.trailingCommentEnd used anywhere?
8001 comment = comments.shift();
8002 }
8003
8004 node.initialise( module.scope );
8005 }
8006}
8007
8008function enhanceNode ( raw, parent, module, code ) {
8009 if ( !raw ) { return; }
8010
8011 if ( 'length' in raw ) {
8012 for ( var i = 0; i < raw.length; i += 1 ) {
8013 enhanceNode( raw[i], parent, module, code );
8014 }
8015
8016 return;
8017 }
8018
8019 // with e.g. shorthand properties, key and value are
8020 // the same node. We don't want to enhance an object twice
8021 if ( raw.__enhanced ) { return; }
8022 raw.__enhanced = true;
8023
8024 if ( !keys$1[ raw.type ] ) {
8025 keys$1[ raw.type ] = Object.keys( raw ).filter( function (key) { return typeof raw[ key ] === 'object'; } );
8026 }
8027
8028 raw.parent = parent;
8029 raw.module = module;
8030 raw.keys = keys$1[ raw.type ];
8031
8032 code.addSourcemapLocation( raw.start );
8033 code.addSourcemapLocation( raw.end );
8034
8035 for ( var key of keys$1[ raw.type ] ) {
8036 enhanceNode( raw[ key ], raw, module, code );
8037 }
8038
8039 var type = nodes[ raw.type ] || Node$1;
8040 raw.__proto__ = type.prototype;
8041}
8042
8043function clone ( node ) {
8044 if ( !node ) { return node; }
8045 if ( typeof node !== 'object' ) { return node; }
8046
8047 if ( Array.isArray( node ) ) {
8048 var cloned$1 = new Array( node.length );
8049 for ( var i = 0; i < node.length; i += 1 ) { cloned$1[i] = clone( node[i] ); }
8050 return cloned$1;
8051 }
8052
8053 var cloned = {};
8054 for ( var key in node ) {
8055 cloned[ key ] = clone( node[ key ] );
8056 }
8057
8058 return cloned;
8059}
8060
8061var ModuleScope = (function (Scope$$1) {
8062 function ModuleScope ( module ) {
8063 Scope$$1.call(this, {
8064 isBlockScope: false,
8065 isLexicalBoundary: true,
8066 isModuleScope: true,
8067 parent: module.bundle.scope
8068 });
8069
8070 this.module = module;
8071 }
8072
8073 if ( Scope$$1 ) ModuleScope.__proto__ = Scope$$1;
8074 ModuleScope.prototype = Object.create( Scope$$1 && Scope$$1.prototype );
8075 ModuleScope.prototype.constructor = ModuleScope;
8076
8077 ModuleScope.prototype.deshadow = function deshadow ( names ) {
8078 var this$1 = this;
8079
8080 names = new Set( names );
8081
8082 forOwn( this.module.imports, function (specifier) {
8083 if ( specifier.module.isExternal ) { return; }
8084
8085 var addDeclaration = function (declaration) {
8086 if ( declaration.isNamespace && !declaration.isExternal ) {
8087 declaration.module.getExports().forEach( function (name) {
8088 addDeclaration( declaration.module.traceExport(name) );
8089 });
8090 }
8091
8092 names.add( declaration.name );
8093 };
8094
8095 specifier.module.getExports().forEach( function (name) {
8096 addDeclaration( specifier.module.traceExport(name) );
8097 });
8098
8099 if ( specifier.name !== '*' ) {
8100 var declaration = specifier.module.traceExport( specifier.name );
8101 if ( !declaration ) {
8102 this$1.module.warn({
8103 code: 'NON_EXISTENT_EXPORT',
8104 name: specifier.name,
8105 source: specifier.module.id,
8106 message: ("Non-existent export '" + (specifier.name) + "' is imported from " + (relativeId( specifier.module.id )))
8107 }, specifier.specifier.start );
8108 return;
8109 }
8110
8111 var name = declaration.getName( true );
8112 if ( name !== specifier.name ) {
8113 names.add( declaration.getName( true ) );
8114 }
8115
8116 if ( specifier.name !== 'default' && specifier.specifier.imported.name !== specifier.specifier.local.name ) {
8117 names.add( specifier.specifier.imported.name );
8118 }
8119 }
8120 });
8121
8122 Scope$$1.prototype.deshadow.call( this, names );
8123 };
8124
8125 ModuleScope.prototype.findDeclaration = function findDeclaration ( name ) {
8126 if ( this.declarations[ name ] ) {
8127 return this.declarations[ name ];
8128 }
8129
8130 return this.module.trace( name ) || this.parent.findDeclaration( name );
8131 };
8132
8133 ModuleScope.prototype.findLexicalBoundary = function findLexicalBoundary () {
8134 return this;
8135 };
8136
8137 return ModuleScope;
8138}(Scope));
8139
8140function tryParse ( module, acornOptions ) {
8141 try {
8142 return parse( module.code, assign( {
8143 ecmaVersion: 8,
8144 sourceType: 'module',
8145 onComment: function ( block, text, start, end ) { return module.comments.push( { block: block, text: text, start: start, end: end } ); },
8146 preserveParens: false
8147 }, acornOptions ) );
8148 } catch ( err ) {
8149 module.error( {
8150 code: 'PARSE_ERROR',
8151 message: err.message.replace( / \(\d+:\d+\)$/, '' )
8152 }, err.pos );
8153 }
8154}
8155
8156var Module = function Module ( ref ) {
8157 var this$1 = this;
8158 var id = ref.id;
8159 var code = ref.code;
8160 var originalCode = ref.originalCode;
8161 var originalSourceMap = ref.originalSourceMap;
8162 var ast = ref.ast;
8163 var sourceMapChain = ref.sourceMapChain;
8164 var resolvedIds = ref.resolvedIds;
8165 var resolvedExternalIds = ref.resolvedExternalIds;
8166 var bundle = ref.bundle;
8167
8168 this.code = code;
8169 this.id = id;
8170 this.bundle = bundle;
8171 this.originalCode = originalCode;
8172 this.originalSourceMap = originalSourceMap;
8173 this.sourceMapChain = sourceMapChain;
8174
8175 this.comments = [];
8176
8177 timeStart( 'ast' );
8178
8179 if ( ast ) {
8180 // prevent mutating the provided AST, as it may be reused on
8181 // subsequent incremental rebuilds
8182 this.ast = clone( ast );
8183 this.astClone = ast;
8184 } else {
8185 this.ast = tryParse( this, bundle.acornOptions ); // TODO what happens to comments if AST is provided?
8186 this.astClone = clone( this.ast );
8187 }
8188
8189 timeEnd( 'ast' );
8190
8191 this.excludeFromSourcemap = /\0/.test( id );
8192 this.context = bundle.getModuleContext( id );
8193
8194 // all dependencies
8195 this.sources = [];
8196 this.dependencies = [];
8197 this.resolvedIds = resolvedIds || blank();
8198 this.resolvedExternalIds = resolvedExternalIds || blank();
8199
8200 // imports and exports, indexed by local name
8201 this.imports = blank();
8202 this.exports = blank();
8203 this.exportsAll = blank();
8204 this.reexports = blank();
8205
8206 this.exportAllSources = [];
8207 this.exportAllModules = null;
8208
8209 // By default, `id` is the filename. Custom resolvers and loaders
8210 // can change that, but it makes sense to use it for the source filename
8211 this.magicString = new MagicString$1( code, {
8212 filename: this.excludeFromSourcemap ? null : id, // don't include plugin helpers in sourcemap
8213 indentExclusionRanges: []
8214 } );
8215
8216 // remove existing sourceMappingURL comments
8217 this.comments = this.comments.filter( function (comment) {
8218 //only one line comment can contain source maps
8219 var isSourceMapComment = !comment.block && SOURCEMAPPING_URL_RE.test( comment.text );
8220 if ( isSourceMapComment ) {
8221 this$1.magicString.remove( comment.start, comment.end );
8222 }
8223 return !isSourceMapComment;
8224 } );
8225
8226 this.declarations = blank();
8227 this.type = 'Module'; // TODO only necessary so that Scope knows this should be treated as a function scope... messy
8228 this.scope = new ModuleScope( this );
8229
8230 timeStart( 'analyse' );
8231
8232 this.analyse();
8233
8234 timeEnd( 'analyse' );
8235
8236 this.strongDependencies = [];
8237};
8238
8239Module.prototype.addExport = function addExport ( node ) {
8240 var this$1 = this;
8241
8242 var source = node.source && node.source.value;
8243
8244 // export { name } from './other.js'
8245 if ( source ) {
8246 if ( !~this.sources.indexOf( source ) ) { this.sources.push( source ); }
8247
8248 if ( node.type === 'ExportAllDeclaration' ) {
8249 // Store `export * from '...'` statements in an array of delegates.
8250 // When an unknown import is encountered, we see if one of them can satisfy it.
8251 this.exportAllSources.push( source );
8252 }
8253
8254 else {
8255 node.specifiers.forEach( function (specifier) {
8256 var name = specifier.exported.name;
8257
8258 if ( this$1.exports[ name ] || this$1.reexports[ name ] ) {
8259 this$1.error( {
8260 code: 'DUPLICATE_EXPORT',
8261 message: ("A module cannot have multiple exports with the same name ('" + name + "')")
8262 }, specifier.start );
8263 }
8264
8265 this$1.reexports[ name ] = {
8266 start: specifier.start,
8267 source: source,
8268 localName: specifier.local.name,
8269 module: null // filled in later
8270 };
8271 } );
8272 }
8273 }
8274
8275 // export default function foo () {}
8276 // export default foo;
8277 // export default 42;
8278 else if ( node.type === 'ExportDefaultDeclaration' ) {
8279 var identifier = ( node.declaration.id && node.declaration.id.name ) || node.declaration.name;
8280
8281 if ( this.exports.default ) {
8282 this.error( {
8283 code: 'DUPLICATE_EXPORT',
8284 message: "A module can only have one default export"
8285 }, node.start );
8286 }
8287
8288 this.exports.default = {
8289 localName: 'default',
8290 identifier: identifier
8291 };
8292
8293 // create a synthetic declaration
8294 //this.declarations.default = new SyntheticDefaultDeclaration( node, identifier || this.basename() );
8295 }
8296
8297 // export var { foo, bar } = ...
8298 // export var foo = 42;
8299 // export var a = 1, b = 2, c = 3;
8300 // export function foo () {}
8301 else if ( node.declaration ) {
8302 var declaration = node.declaration;
8303
8304 if ( declaration.type === 'VariableDeclaration' ) {
8305 declaration.declarations.forEach( function (decl) {
8306 extractNames( decl.id ).forEach( function (localName) {
8307 this$1.exports[ localName ] = { localName: localName };
8308 } );
8309 } );
8310 } else {
8311 // export function foo () {}
8312 var localName = declaration.id.name;
8313 this.exports[ localName ] = { localName: localName };
8314 }
8315 }
8316
8317 // export { foo, bar, baz }
8318 else {
8319 node.specifiers.forEach( function (specifier) {
8320 var localName = specifier.local.name;
8321 var exportedName = specifier.exported.name;
8322
8323 if ( this$1.exports[ exportedName ] || this$1.reexports[ exportedName ] ) {
8324 this$1.error({
8325 code: 'DUPLICATE_EXPORT',
8326 message: ("A module cannot have multiple exports with the same name ('" + exportedName + "')")
8327 }, specifier.start );
8328 }
8329
8330 this$1.exports[ exportedName ] = { localName: localName };
8331 });
8332 }
8333};
8334
8335Module.prototype.addImport = function addImport ( node ) {
8336 var this$1 = this;
8337
8338 var source = node.source.value;
8339
8340 if ( !~this.sources.indexOf( source ) ) { this.sources.push( source ); }
8341
8342 node.specifiers.forEach( function (specifier) {
8343 var localName = specifier.local.name;
8344
8345 if ( this$1.imports[ localName ] ) {
8346 this$1.error( {
8347 code: 'DUPLICATE_IMPORT',
8348 message: ("Duplicated import '" + localName + "'")
8349 }, specifier.start );
8350 }
8351
8352 var isDefault = specifier.type === 'ImportDefaultSpecifier';
8353 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
8354
8355 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
8356 this$1.imports[ localName ] = { source: source, specifier: specifier, name: name, module: null };
8357 } );
8358};
8359
8360Module.prototype.analyse = function analyse () {
8361 var this$1 = this;
8362
8363 enhance( this.ast, this, this.comments );
8364
8365 // discover this module's imports and exports
8366 var lastNode;
8367
8368 for ( var node of this$1.ast.body ) {
8369 if ( node.isImportDeclaration ) {
8370 this$1.addImport( node );
8371 } else if ( node.isExportDeclaration ) {
8372 this$1.addExport( node );
8373 }
8374
8375 if ( lastNode ) { lastNode.next = node.leadingCommentStart || node.start; }
8376 lastNode = node;
8377 }
8378};
8379
8380Module.prototype.basename = function basename$1 () {
8381 var base = basename( this.id );
8382 var ext = extname( this.id );
8383
8384 return makeLegal( ext ? base.slice( 0, -ext.length ) : base );
8385};
8386
8387Module.prototype.bindImportSpecifiers = function bindImportSpecifiers () {
8388 var this$1 = this;
8389
8390 [ this.imports, this.reexports ].forEach( function (specifiers) {
8391 keys( specifiers ).forEach( function (name) {
8392 var specifier = specifiers[ name ];
8393
8394 var id = this$1.resolvedIds[ specifier.source ] || this$1.resolvedExternalIds[ specifier.source ];
8395 specifier.module = this$1.bundle.moduleById.get( id );
8396 } );
8397 } );
8398
8399 this.exportAllModules = this.exportAllSources.map( function (source) {
8400 var id = this$1.resolvedIds[ source ] || this$1.resolvedExternalIds[ source ];
8401 return this$1.bundle.moduleById.get( id );
8402 } );
8403
8404 this.sources.forEach( function (source) {
8405 var id = this$1.resolvedIds[ source ];
8406
8407 if ( id ) {
8408 var module = this$1.bundle.moduleById.get( id );
8409 this$1.dependencies.push( module );
8410 }
8411 } );
8412};
8413
8414Module.prototype.bindReferences = function bindReferences () {
8415 var this$1 = this;
8416
8417 for ( var node of this$1.ast.body ) {
8418 node.bind();
8419 }
8420
8421 // if ( this.declarations.default ) {
8422 // if ( this.exports.default.identifier ) {
8423 // const declaration = this.trace( this.exports.default.identifier );
8424 // if ( declaration ) this.declarations.default.bind( declaration );
8425 // }
8426 // }
8427};
8428
8429Module.prototype.error = function error$1 ( props, pos ) {
8430 if ( pos !== undefined ) {
8431 props.pos = pos;
8432
8433 var ref = locate( this.code, pos, { offsetLine: 1 } );
8434 var line = ref.line;
8435 var column = ref.column; // TODO trace sourcemaps
8436
8437 props.loc = { file: this.id, line: line, column: column };
8438 props.frame = getCodeFrame( this.code, line, column );
8439 }
8440
8441 error( props );
8442};
8443
8444Module.prototype.findParent = function findParent () {
8445 // TODO what does it mean if we're here?
8446 return null;
8447};
8448
8449Module.prototype.getExports = function getExports () {
8450 return keys( this.exports );
8451};
8452
8453Module.prototype.getReexports = function getReexports () {
8454 var reexports = blank();
8455
8456 keys( this.reexports ).forEach( function (name) {
8457 reexports[ name ] = true;
8458 } );
8459
8460 this.exportAllModules.forEach( function (module) {
8461 if ( module.isExternal ) {
8462 reexports[ ("*" + (module.id)) ] = true;
8463 return;
8464 }
8465
8466 module.getExports().concat( module.getReexports() ).forEach( function (name) {
8467 if ( name !== 'default' ) { reexports[ name ] = true; }
8468 } );
8469 } );
8470
8471 return keys( reexports );
8472};
8473
8474Module.prototype.namespace = function namespace () {
8475 if ( !this.declarations[ '*' ] ) {
8476 this.declarations[ '*' ] = new SyntheticNamespaceDeclaration( this );
8477 }
8478
8479 return this.declarations[ '*' ];
8480};
8481
8482Module.prototype.render = function render ( es, legacy ) {
8483 var this$1 = this;
8484
8485 var magicString = this.magicString.clone();
8486
8487 for ( var node of this$1.ast.body ) {
8488 node.render( magicString, es );
8489 }
8490
8491 if ( this.namespace().needsNamespaceBlock ) {
8492 magicString.append( '\n\n' + this.namespace().renderBlock( es, legacy, '\t' ) ); // TODO use correct indentation
8493 }
8494
8495 return magicString.trim();
8496};
8497
8498Module.prototype.run = function run () {
8499 var this$1 = this;
8500
8501 for ( var node of this$1.ast.body ) {
8502 if ( node.hasEffects() ) {
8503 node.run();
8504 }
8505 }
8506};
8507
8508Module.prototype.toJSON = function toJSON () {
8509 return {
8510 id: this.id,
8511 dependencies: this.dependencies.map( function (module) { return module.id; } ),
8512 code: this.code,
8513 originalCode: this.originalCode,
8514 originalSourceMap: this.originalSourceMap,
8515 ast: this.astClone,
8516 sourceMapChain: this.sourceMapChain,
8517 resolvedIds: this.resolvedIds,
8518 resolvedExternalIds: this.resolvedExternalIds
8519 };
8520};
8521
8522Module.prototype.trace = function trace ( name ) {
8523 // TODO this is slightly circular
8524 if ( name in this.scope.declarations ) {
8525 return this.scope.declarations[ name ];
8526 }
8527
8528 if ( name in this.imports ) {
8529 var importDeclaration = this.imports[ name ];
8530 var otherModule = importDeclaration.module;
8531
8532 if ( importDeclaration.name === '*' && !otherModule.isExternal ) {
8533 return otherModule.namespace();
8534 }
8535
8536 var declaration = otherModule.traceExport( importDeclaration.name );
8537
8538 if ( !declaration ) {
8539 this.error( {
8540 code: 'MISSING_EXPORT',
8541 message: ("'" + (importDeclaration.name) + "' is not exported by " + (relativeId( otherModule.id ))),
8542 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
8543 }, importDeclaration.specifier.start );
8544 }
8545
8546 return declaration;
8547 }
8548
8549 return null;
8550};
8551
8552Module.prototype.traceExport = function traceExport ( name ) {
8553 var this$1 = this;
8554
8555 // export * from 'external'
8556 if ( name[ 0 ] === '*' ) {
8557 var module = this.bundle.moduleById.get( name.slice( 1 ) );
8558 return module.traceExport( '*' );
8559 }
8560
8561 // export { foo } from './other.js'
8562 var reexportDeclaration = this.reexports[ name ];
8563 if ( reexportDeclaration ) {
8564 var declaration = reexportDeclaration.module.traceExport( reexportDeclaration.localName );
8565
8566 if ( !declaration ) {
8567 this.error( {
8568 code: 'MISSING_EXPORT',
8569 message: ("'" + (reexportDeclaration.localName) + "' is not exported by " + (relativeId( reexportDeclaration.module.id ))),
8570 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module"
8571 }, reexportDeclaration.start );
8572 }
8573
8574 return declaration;
8575 }
8576
8577 var exportDeclaration = this.exports[ name ];
8578 if ( exportDeclaration ) {
8579 var name$1 = exportDeclaration.localName;
8580 var declaration$1 = this.trace( name$1 );
8581
8582 return declaration$1 || this.bundle.scope.findDeclaration( name$1 );
8583 }
8584
8585 if ( name === 'default' ) { return; }
8586
8587 for ( var i = 0; i < this.exportAllModules.length; i += 1 ) {
8588 var module$1$$1 = this$1.exportAllModules[ i ];
8589 var declaration$2 = module$1$$1.traceExport( name );
8590
8591 if ( declaration$2 ) { return declaration$2; }
8592 }
8593};
8594
8595Module.prototype.warn = function warn ( warning, pos ) {
8596 if ( pos !== undefined ) {
8597 warning.pos = pos;
8598
8599 var ref = locate( this.code, pos, { offsetLine: 1 } );
8600 var line = ref.line;
8601 var column = ref.column; // TODO trace sourcemaps
8602
8603 warning.loc = { file: this.id, line: line, column: column };
8604 warning.frame = getCodeFrame( this.code, line, column );
8605 }
8606
8607 warning.id = this.id;
8608 this.bundle.warn( warning );
8609};
8610
8611var ExternalModule = function ExternalModule ( id, relativePath ) {
8612 this.id = id;
8613 this.path = relativePath;
8614
8615 this.name = makeLegal( relativePath );
8616
8617 this.nameSuggestions = blank();
8618 this.mostCommonSuggestion = 0;
8619
8620 this.isExternal = true;
8621 this.used = false;
8622 this.declarations = blank();
8623
8624 this.exportsNames = false;
8625};
8626
8627ExternalModule.prototype.suggestName = function suggestName ( name ) {
8628 if ( !this.nameSuggestions[ name ] ) { this.nameSuggestions[ name ] = 0; }
8629 this.nameSuggestions[ name ] += 1;
8630
8631 if ( this.nameSuggestions[ name ] > this.mostCommonSuggestion ) {
8632 this.mostCommonSuggestion = this.nameSuggestions[ name ];
8633 this.name = name;
8634 }
8635};
8636
8637ExternalModule.prototype.traceExport = function traceExport ( name ) {
8638 if ( name !== 'default' && name !== '*' ) { this.exportsNames = true; }
8639 if ( name === '*' ) { this.exportsNamespace = true; }
8640
8641 return this.declarations[ name ] || (
8642 this.declarations[ name ] = new ExternalDeclaration( this, name )
8643 );
8644};
8645
8646function getName ( x ) {
8647 return x.name;
8648}
8649
8650function quotePath ( x ) {
8651 return ("'" + (x.path) + "'");
8652}
8653
8654function req ( x ) {
8655 return ("require('" + (x.path) + "')");
8656}
8657
8658function getInteropBlock ( bundle, options ) {
8659 return bundle.externalModules
8660 .map( function (module) {
8661 if ( !module.declarations.default || options.interop === false ) { return null; }
8662
8663 if ( module.exportsNamespace ) {
8664 return ((bundle.varOrConst) + " " + (module.name) + "__default = " + (module.name) + "['default'];");
8665 }
8666
8667 if ( module.exportsNames ) {
8668 return ((bundle.varOrConst) + " " + (module.name) + "__default = 'default' in " + (module.name) + " ? " + (module.name) + "['default'] : " + (module.name) + ";");
8669 }
8670
8671 return ((module.name) + " = " + (module.name) + " && " + (module.name) + ".hasOwnProperty('default') ? " + (module.name) + "['default'] : " + (module.name) + ";");
8672 })
8673 .filter( Boolean )
8674 .join( '\n' );
8675}
8676
8677function getExportBlock ( bundle, exportMode, mechanism ) {
8678 if ( mechanism === void 0 ) mechanism = 'return';
8679
8680 var entryModule = bundle.entryModule;
8681
8682 if ( exportMode === 'default' ) {
8683 return (mechanism + " " + (entryModule.traceExport( 'default' ).getName( false )) + ";");
8684 }
8685
8686 var exports = entryModule.getExports().concat( entryModule.getReexports() )
8687 .map( function (name) {
8688 if ( name[0] === '*' ) {
8689 // export all from external
8690 var id = name.slice( 1 );
8691 var module = bundle.moduleById.get( id );
8692
8693 return ("Object.keys(" + (module.name) + ").forEach(function (key) { exports[key] = " + (module.name) + "[key]; });");
8694 }
8695
8696 var prop = name === 'default' ? "['default']" : ("." + name);
8697 var declaration = entryModule.traceExport( name );
8698
8699 var lhs = "exports" + prop;
8700 var rhs = declaration ?
8701 declaration.getName( false ) :
8702 name; // exporting a global
8703
8704 // prevent `exports.count = exports.count`
8705 if ( lhs === rhs ) { return null; }
8706
8707 return (lhs + " = " + rhs + ";");
8708 });
8709
8710 return exports
8711 .filter( Boolean )
8712 .join( '\n' );
8713}
8714
8715var esModuleExport = "Object.defineProperty(exports, '__esModule', { value: true });";
8716
8717var builtins$1 = {
8718 process: true,
8719 events: true,
8720 stream: true,
8721 util: true,
8722 path: true,
8723 buffer: true,
8724 querystring: true,
8725 url: true,
8726 string_decoder: true,
8727 punycode: true,
8728 http: true,
8729 https: true,
8730 os: true,
8731 assert: true,
8732 constants: true,
8733 timers: true,
8734 console: true,
8735 vm: true,
8736 zlib: true,
8737 tty: true,
8738 domain: true
8739};
8740
8741// 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
8742
8743function warnOnBuiltins ( bundle ) {
8744 var externalBuiltins = bundle.externalModules
8745 .filter( function (mod) { return mod.id in builtins$1; } )
8746 .map( function (mod) { return mod.id; } );
8747
8748 if ( !externalBuiltins.length ) { return; }
8749
8750 var detail = externalBuiltins.length === 1 ?
8751 ("module ('" + (externalBuiltins[0]) + "')") :
8752 ("modules (" + (externalBuiltins.slice( 0, -1 ).map( function (name) { return ("'" + name + "'"); } ).join( ', ' )) + " and '" + (externalBuiltins.slice( -1 )) + "')");
8753
8754 bundle.warn({
8755 code: 'MISSING_NODE_BUILTINS',
8756 modules: externalBuiltins,
8757 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")
8758 });
8759}
8760
8761function amd ( bundle, magicString, ref, options ) {
8762 var exportMode = ref.exportMode;
8763 var indentString = ref.indentString;
8764 var intro = ref.intro;
8765 var outro = ref.outro;
8766
8767 warnOnBuiltins( bundle );
8768 var deps = bundle.externalModules.map( quotePath );
8769 var args = bundle.externalModules.map( getName );
8770
8771 if ( exportMode === 'named' ) {
8772 args.unshift( "exports" );
8773 deps.unshift( "'exports'" );
8774 }
8775
8776 var amdOptions = options.amd || {};
8777
8778 var params =
8779 ( amdOptions.id ? ("'" + (amdOptions.id) + "', ") : "" ) +
8780 ( deps.length ? ("[" + (deps.join( ', ' )) + "], ") : "" );
8781
8782 var useStrict = options.useStrict !== false ? " 'use strict';" : "";
8783 var define = amdOptions.define || 'define';
8784 var wrapperStart = define + "(" + params + "function (" + (args.join( ', ' )) + ") {" + useStrict + "\n\n";
8785
8786 // var foo__default = 'default' in foo ? foo['default'] : foo;
8787 var interopBlock = getInteropBlock( bundle, options );
8788 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
8789
8790 if ( intro ) { magicString.prepend( intro ); }
8791
8792 var exportBlock = getExportBlock( bundle, exportMode );
8793 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
8794 if ( exportMode === 'named' && options.legacy !== true ) { magicString.append( ("\n\n" + esModuleExport) ); }
8795 if ( outro ) { magicString.append( outro ); }
8796
8797 return magicString
8798 .indent( indentString )
8799 .append( '\n\n});' )
8800 .prepend( wrapperStart );
8801}
8802
8803function cjs ( bundle, magicString, ref, options ) {
8804 var exportMode = ref.exportMode;
8805 var intro = ref.intro;
8806 var outro = ref.outro;
8807
8808 intro = ( options.useStrict === false ? intro : ("'use strict';\n\n" + intro) ) +
8809 ( exportMode === 'named' && options.legacy !== true ? (esModuleExport + "\n\n") : '' );
8810
8811 var needsInterop = false;
8812
8813 var varOrConst = bundle.varOrConst;
8814 var interop = options.interop !== false;
8815
8816 // TODO handle empty imports, once they're supported
8817 var importBlock = bundle.externalModules
8818 .map( function (module) {
8819 if ( interop && module.declarations.default ) {
8820 if ( module.exportsNamespace ) {
8821 return varOrConst + " " + (module.name) + " = require('" + (module.path) + "');" +
8822 "\n" + varOrConst + " " + (module.name) + "__default = " + (module.name) + "['default'];";
8823 }
8824
8825 needsInterop = true;
8826
8827 if ( module.exportsNames ) {
8828 return varOrConst + " " + (module.name) + " = require('" + (module.path) + "');" +
8829 "\n" + varOrConst + " " + (module.name) + "__default = _interopDefault(" + (module.name) + ");";
8830 }
8831
8832 return (varOrConst + " " + (module.name) + " = _interopDefault(require('" + (module.path) + "'));");
8833 } else {
8834 var activated = Object.keys( module.declarations )
8835 .filter( function (name) { return module.declarations[ name ].activated; } );
8836
8837 var needsVar = activated.length || module.reexported;
8838
8839 return needsVar ?
8840 (varOrConst + " " + (module.name) + " = require('" + (module.path) + "');") :
8841 ("require('" + (module.path) + "');");
8842 }
8843 })
8844 .join( '\n' );
8845
8846 if ( needsInterop ) {
8847 intro += "function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n";
8848 }
8849
8850 if ( importBlock ) {
8851 intro += importBlock + '\n\n';
8852 }
8853
8854 magicString.prepend( intro );
8855
8856 var exportBlock = getExportBlock( bundle, exportMode, 'module.exports =' );
8857 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
8858 if ( outro ) { magicString.append( outro ); }
8859
8860 return magicString;
8861}
8862
8863function notDefault ( name ) {
8864 return name !== 'default';
8865}
8866
8867function es ( bundle, magicString, ref ) {
8868 var intro = ref.intro;
8869 var outro = ref.outro;
8870
8871 var importBlock = bundle.externalModules
8872 .map( function (module) {
8873 var specifiers = [];
8874 var specifiersList = [specifiers];
8875 var importedNames = keys( module.declarations )
8876 .filter( function (name) { return name !== '*' && name !== 'default'; } )
8877 .filter( function (name) { return module.declarations[ name ].activated; } )
8878 .map( function (name) {
8879 if ( name[0] === '*' ) {
8880 return ("* as " + (module.name));
8881 }
8882
8883 var declaration = module.declarations[ name ];
8884
8885 if ( declaration.name === declaration.safeName ) { return declaration.name; }
8886 return ((declaration.name) + " as " + (declaration.safeName));
8887 })
8888 .filter( Boolean );
8889
8890 if ( module.declarations.default ) {
8891 if ( module.exportsNamespace ) {
8892 specifiersList.push([ ((module.name) + "__default") ]);
8893 } else {
8894 specifiers.push( module.name );
8895 }
8896 }
8897
8898 var namespaceSpecifier = module.declarations['*'] && module.declarations['*'].activated ? ("* as " + (module.name)) : null; // TODO prevent unnecessary namespace import, e.g form/external-imports
8899 var namedSpecifier = importedNames.length ? ("{ " + (importedNames.sort().join( ', ' )) + " }") : null;
8900
8901 if ( namespaceSpecifier && namedSpecifier ) {
8902 // Namespace and named specifiers cannot be combined.
8903 specifiersList.push( [namespaceSpecifier] );
8904 specifiers.push( namedSpecifier );
8905 } else if ( namedSpecifier ) {
8906 specifiers.push( namedSpecifier );
8907 } else if ( namespaceSpecifier ) {
8908 specifiers.push( namespaceSpecifier );
8909 }
8910
8911 return specifiersList
8912 .map( function (specifiers) {
8913 if ( specifiers.length ) {
8914 return ("import " + (specifiers.join( ', ' )) + " from '" + (module.path) + "';");
8915 }
8916
8917 return module.reexported ?
8918 null :
8919 ("import '" + (module.path) + "';");
8920 })
8921 .filter( Boolean )
8922 .join( '\n' );
8923 })
8924 .join( '\n' );
8925
8926 if ( importBlock ) { intro += importBlock + '\n\n'; }
8927 if ( intro ) { magicString.prepend( intro ); }
8928
8929 var module = bundle.entryModule;
8930
8931 var exportInternalSpecifiers = [];
8932 var exportExternalSpecifiers = new Map();
8933 var exportAllDeclarations = [];
8934
8935 module.getExports()
8936 .filter( notDefault )
8937 .forEach( function (name) {
8938 var declaration = module.traceExport( name );
8939 var rendered = declaration.getName( true );
8940 exportInternalSpecifiers.push( rendered === name ? name : (rendered + " as " + name) );
8941 });
8942
8943 module.getReexports()
8944 .filter( notDefault )
8945 .forEach( function (name) {
8946 var declaration = module.traceExport( name );
8947
8948 if ( declaration.isExternal ) {
8949 if ( name[0] === '*' ) {
8950 // export * from 'external'
8951 exportAllDeclarations.push( ("export * from '" + (name.slice( 1 )) + "';") );
8952 } else {
8953 if ( !exportExternalSpecifiers.has( declaration.module.id ) ) { exportExternalSpecifiers.set( declaration.module.id, [] ); }
8954 exportExternalSpecifiers.get( declaration.module.id ).push( name );
8955 }
8956
8957 return;
8958 }
8959
8960 var rendered = declaration.getName( true );
8961 exportInternalSpecifiers.push( rendered === name ? name : (rendered + " as " + name) );
8962 });
8963
8964 var exportBlock = [];
8965 if ( exportInternalSpecifiers.length ) { exportBlock.push( ("export { " + (exportInternalSpecifiers.join(', ')) + " };") ); }
8966 if ( module.exports.default || module.reexports.default ) { exportBlock.push( ("export default " + (module.traceExport( 'default' ).getName( true )) + ";") ); }
8967 if ( exportAllDeclarations.length ) { exportBlock.push( exportAllDeclarations.join( '\n' ) ); }
8968 if ( exportExternalSpecifiers.size ) {
8969 exportExternalSpecifiers.forEach( function ( specifiers, id ) {
8970 exportBlock.push( ("export { " + (specifiers.join( ', ' )) + " } from '" + id + "';") );
8971 });
8972 }
8973
8974 if ( exportBlock.length ) { magicString.append( '\n\n' + exportBlock.join( '\n' ).trim() ); }
8975
8976 if ( outro ) { magicString.append( outro ); }
8977
8978 return magicString.trim();
8979}
8980
8981function getGlobalNameMaker ( globals, bundle, fallback ) {
8982 if ( fallback === void 0 ) fallback = null;
8983
8984 var fn = typeof globals === 'function' ? globals : function (id) { return globals[ id ]; };
8985
8986 return function ( module ) {
8987 var name = fn( module.id );
8988 if ( name ) { return name; }
8989
8990 if ( Object.keys( module.declarations ).length > 0 ) {
8991 bundle.warn({
8992 code: 'MISSING_GLOBAL_NAME',
8993 source: module.id,
8994 guess: module.name,
8995 message: ("No name was provided for external module '" + (module.id) + "' in options.globals – guessing '" + (module.name) + "'")
8996 });
8997
8998 return module.name;
8999 }
9000
9001 return fallback;
9002 };
9003}
9004
9005// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
9006// if the property name isn't trivial
9007var shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
9008
9009function property ( prop ) {
9010 return shouldUseDot.test( prop ) ? ("." + prop) : ("['" + prop + "']");
9011}
9012
9013function keypath ( keypath ) {
9014 return keypath.split( '.' ).map( property ).join( '' );
9015}
9016
9017function trimEmptyImports ( modules ) {
9018 var i = modules.length;
9019
9020 while ( i-- ) {
9021 var module = modules[i];
9022 if ( Object.keys( module.declarations ).length > 0 ) {
9023 return modules.slice( 0, i + 1 );
9024 }
9025 }
9026
9027 return [];
9028}
9029
9030function setupNamespace ( keypath$$1 ) {
9031 var parts = keypath$$1.split( '.' );
9032
9033 parts.pop();
9034
9035 var acc = 'this';
9036
9037 return parts
9038 .map( function (part) { return ( acc += property( part ), (acc + " = " + acc + " || {};") ); } )
9039 .join( '\n' ) + '\n';
9040}
9041
9042var thisProp = function (name) { return ("this" + (keypath( name ))); };
9043
9044function iife ( bundle, magicString, ref, options ) {
9045 var exportMode = ref.exportMode;
9046 var indentString = ref.indentString;
9047 var intro = ref.intro;
9048 var outro = ref.outro;
9049
9050 var globalNameMaker = getGlobalNameMaker( options.globals || blank(), bundle, 'null' );
9051
9052 var extend = options.extend;
9053 var name = options.moduleName;
9054 var isNamespaced = name && name.indexOf( '.' ) !== -1;
9055 var possibleVariableAssignment = !extend && !isNamespaced;
9056
9057 if ( name && possibleVariableAssignment && !isLegal(name) ) {
9058 error({
9059 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
9060 message: ("Given moduleName (" + name + ") is not legal JS identifier. If you need this you can try --extend option")
9061 });
9062 }
9063
9064 warnOnBuiltins( bundle );
9065
9066 var external = trimEmptyImports( bundle.externalModules );
9067 var dependencies = external.map( globalNameMaker );
9068 var args = external.map( getName );
9069
9070 if ( exportMode !== 'none' && !name ) {
9071 error({
9072 code: 'INVALID_OPTION',
9073 message: "You must supply options.moduleName for IIFE bundles"
9074 });
9075 }
9076
9077 if ( extend ) {
9078 dependencies.unshift( ("(" + (thisProp(name)) + " = " + (thisProp(name)) + " || {})") );
9079 args.unshift( 'exports' );
9080 } else if ( exportMode === 'named' ) {
9081 dependencies.unshift( '{}' );
9082 args.unshift( 'exports' );
9083 }
9084
9085 var useStrict = options.useStrict !== false ? (indentString + "'use strict';\n\n") : "";
9086
9087 var wrapperIntro = "(function (" + args + ") {\n" + useStrict;
9088
9089 if ( exportMode !== 'none' && !extend) {
9090 wrapperIntro = ( isNamespaced ? thisProp(name) : ((bundle.varOrConst) + " " + name) ) + " = " + wrapperIntro;
9091 }
9092
9093 if ( isNamespaced ) {
9094 wrapperIntro = setupNamespace( name ) + wrapperIntro;
9095 }
9096
9097 var wrapperOutro = "\n\n}(" + dependencies + "));";
9098
9099 if (!extend && exportMode === 'named') {
9100 wrapperOutro = "\n\n" + indentString + "return exports;" + wrapperOutro;
9101 }
9102
9103 // var foo__default = 'default' in foo ? foo['default'] : foo;
9104 var interopBlock = getInteropBlock( bundle, options );
9105 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
9106
9107 if ( intro ) { magicString.prepend( intro ); }
9108
9109 var exportBlock = getExportBlock( bundle, exportMode );
9110 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
9111 if ( outro ) { magicString.append( outro ); }
9112
9113 return magicString
9114 .indent( indentString )
9115 .prepend( wrapperIntro )
9116 .append( wrapperOutro );
9117}
9118
9119function globalProp ( name ) {
9120 if ( !name ) { return 'null'; }
9121 return ("global" + (keypath( name )));
9122}
9123
9124function setupNamespace$1 ( name ) {
9125 var parts = name.split( '.' );
9126 var last = property( parts.pop() );
9127
9128 var acc = 'global';
9129 return parts
9130 .map( function (part) { return ( acc += property( part ), (acc + " = " + acc + " || {}") ); } )
9131 .concat( ("" + acc + last) )
9132 .join( ', ' );
9133}
9134
9135function safeAccess ( name ) {
9136 var parts = name.split( '.' );
9137
9138 var acc = 'global';
9139 return parts
9140 .map( function (part) { return ( acc += property( part ), acc ); } )
9141 .join( " && " );
9142}
9143
9144var wrapperOutro = '\n\n})));';
9145
9146function umd ( bundle, magicString, ref, options ) {
9147 var exportMode = ref.exportMode;
9148 var indentString = ref.indentString;
9149 var intro = ref.intro;
9150 var outro = ref.outro;
9151
9152 if ( exportMode !== 'none' && !options.moduleName ) {
9153 error({
9154 code: 'INVALID_OPTION',
9155 message: 'You must supply options.moduleName for UMD bundles'
9156 });
9157 }
9158
9159 warnOnBuiltins( bundle );
9160
9161 var globalNameMaker = getGlobalNameMaker( options.globals || blank(), bundle );
9162
9163 var amdDeps = bundle.externalModules.map( quotePath );
9164 var cjsDeps = bundle.externalModules.map( req );
9165
9166 var trimmed = trimEmptyImports( bundle.externalModules );
9167 var globalDeps = trimmed.map( function (module) { return globalProp( globalNameMaker( module ) ); } );
9168 var args = trimmed.map( getName );
9169
9170 if ( exportMode === 'named' ) {
9171 amdDeps.unshift( "'exports'" );
9172 cjsDeps.unshift( "exports" );
9173 globalDeps.unshift( ("(" + (setupNamespace$1(options.moduleName)) + " = " + (options.extend ? ((globalProp(options.moduleName)) + " || ") : '') + "{})") );
9174
9175 args.unshift( 'exports' );
9176 }
9177
9178 var amdOptions = options.amd || {};
9179
9180 var amdParams =
9181 ( amdOptions.id ? ("'" + (amdOptions.id) + "', ") : "" ) +
9182 ( amdDeps.length ? ("[" + (amdDeps.join( ', ' )) + "], ") : "" );
9183
9184 var define = amdOptions.define || 'define';
9185
9186 var cjsExport = exportMode === 'default' ? "module.exports = " : "";
9187 var defaultExport = exportMode === 'default' ? ((setupNamespace$1(options.moduleName)) + " = ") : '';
9188
9189 var useStrict = options.useStrict !== false ? " 'use strict';" : "";
9190
9191 var globalExport;
9192
9193 if (options.noConflict === true) {
9194 var factory;
9195
9196 if ( exportMode === 'default' ) {
9197 factory = "var exports = factory(" + globalDeps + ");";
9198 } else if ( exportMode === 'named' ) {
9199 var module = globalDeps.shift();
9200 factory = "var exports = " + module + ";\n\t\t\t\tfactory(" + (['exports'].concat(globalDeps)) + ");";
9201 }
9202 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})()";
9203 } else {
9204 globalExport = "(" + defaultExport + "factory(" + globalDeps + "))";
9205 }
9206
9207 var wrapperIntro =
9208 ("(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' );
9209
9210 // var foo__default = 'default' in foo ? foo['default'] : foo;
9211 var interopBlock = getInteropBlock( bundle, options );
9212 if ( interopBlock ) { magicString.prepend( interopBlock + '\n\n' ); }
9213
9214 if ( intro ) { magicString.prepend( intro ); }
9215
9216 var exportBlock = getExportBlock( bundle, exportMode );
9217 if ( exportBlock ) { magicString.append( '\n\n' + exportBlock ); }
9218 if ( exportMode === 'named' && options.legacy !== true ) { magicString.append( ("\n\n" + esModuleExport) ); }
9219 if ( outro ) { magicString.append( outro ); }
9220
9221 return magicString
9222 .trim()
9223 .indent( indentString )
9224 .append( wrapperOutro )
9225 .prepend( wrapperIntro );
9226}
9227
9228var finalisers = { amd: amd, cjs: cjs, es: es, iife: iife, umd: umd };
9229
9230function ensureArray ( thing ) {
9231 if ( Array.isArray( thing ) ) { return thing; }
9232 if ( thing == undefined ) { return []; }
9233 return [ thing ];
9234}
9235
9236function load ( id ) {
9237 return readFileSync( id, 'utf-8' );
9238}
9239
9240function findFile ( file ) {
9241 try {
9242 var stats = lstatSync( file );
9243 if ( stats.isSymbolicLink() ) { return findFile( realpathSync( file ) ); }
9244 if ( stats.isFile() ) {
9245 // check case
9246 var name = basename( file );
9247 var files = readdirSync( dirname( file ) );
9248
9249 if ( ~files.indexOf( name ) ) { return file; }
9250 }
9251 } catch ( err ) {
9252 // suppress
9253 }
9254}
9255
9256function addJsExtensionIfNecessary ( file ) {
9257 return findFile( file ) || findFile( file + '.js' );
9258}
9259
9260function resolveId ( importee, importer ) {
9261 if ( typeof process === 'undefined' ) {
9262 error({
9263 code: 'MISSING_PROCESS',
9264 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",
9265 url: 'https://github.com/rollup/rollup/wiki/Plugins'
9266 });
9267 }
9268
9269 // external modules (non-entry modules that start with neither '.' or '/')
9270 // are skipped at this stage.
9271 if ( importer !== undefined && !isAbsolute( importee ) && importee[0] !== '.' ) { return null; }
9272
9273 // `resolve` processes paths from right to left, prepending them until an
9274 // absolute path is created. Absolute importees therefore shortcircuit the
9275 // resolve call and require no special handing on our part.
9276 // See https://nodejs.org/api/path.html#path_path_resolve_paths
9277 return addJsExtensionIfNecessary(
9278 resolve( importer ? dirname( importer ) : resolve(), importee ) );
9279}
9280
9281
9282function makeOnwarn () {
9283 var warned = blank();
9284
9285 return function (warning) {
9286 var str = warning.toString();
9287 if ( str in warned ) { return; }
9288 console.error( str ); //eslint-disable-line no-console
9289 warned[ str ] = true;
9290 };
9291}
9292
9293function badExports ( option, keys$$1 ) {
9294 error({
9295 code: 'INVALID_EXPORT_OPTION',
9296 message: ("'" + option + "' was specified for options.exports, but entry module has following exports: " + (keys$$1.join(', ')))
9297 });
9298}
9299
9300function getExportMode ( bundle, ref ) {
9301 var exportMode = ref.exports;
9302 var moduleName = ref.moduleName;
9303 var format = ref.format;
9304
9305 var exportKeys = keys( bundle.entryModule.exports )
9306 .concat( keys( bundle.entryModule.reexports ) )
9307 .concat( bundle.entryModule.exportAllSources ); // not keys, but makes our job easier this way
9308
9309 if ( exportMode === 'default' ) {
9310 if ( exportKeys.length !== 1 || exportKeys[0] !== 'default' ) {
9311 badExports( 'default', exportKeys );
9312 }
9313 } else if ( exportMode === 'none' && exportKeys.length ) {
9314 badExports( 'none', exportKeys );
9315 }
9316
9317 if ( !exportMode || exportMode === 'auto' ) {
9318 if ( exportKeys.length === 0 ) {
9319 exportMode = 'none';
9320 } else if ( exportKeys.length === 1 && exportKeys[0] === 'default' ) {
9321 exportMode = 'default';
9322 } else {
9323 if ( bundle.entryModule.exports.default && format !== 'es') {
9324 bundle.warn({
9325 code: 'MIXED_EXPORTS',
9326 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"),
9327 url: "https://github.com/rollup/rollup/wiki/JavaScript-API#exports"
9328 });
9329 }
9330 exportMode = 'named';
9331 }
9332 }
9333
9334 if ( !/(?:default|named|none)/.test( exportMode ) ) {
9335 error({
9336 code: 'INVALID_EXPORT_OPTION',
9337 message: "options.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')"
9338 });
9339 }
9340
9341 return exportMode;
9342}
9343
9344function getIndentString ( magicString, options ) {
9345 if ( options.indent === true ) {
9346 return magicString.getIndentString();
9347 }
9348
9349 return options.indent || '';
9350}
9351
9352function transform ( bundle, source, id, plugins ) {
9353 var sourceMapChain = [];
9354
9355 var originalSourceMap = typeof source.map === 'string' ? JSON.parse( source.map ) : source.map;
9356
9357 if ( originalSourceMap && typeof originalSourceMap.mappings === 'string' ) {
9358 originalSourceMap.mappings = decode$$1( originalSourceMap.mappings );
9359 }
9360
9361 var originalCode = source.code;
9362 var ast = source.ast;
9363
9364 var promise = Promise.resolve( source.code );
9365
9366 plugins.forEach( function (plugin) {
9367 if ( !plugin.transform ) { return; }
9368
9369 promise = promise.then( function (previous) {
9370 function augment ( object, pos, code ) {
9371 if ( typeof object === 'string' ) {
9372 object = { message: object };
9373 }
9374
9375 if ( object.code ) { object.pluginCode = object.code; }
9376 object.code = code;
9377
9378 if ( pos !== undefined ) {
9379 if ( pos.line !== undefined && pos.column !== undefined ) {
9380 var line = pos.line;
9381 var column = pos.column;
9382 object.loc = { file: id, line: line, column: column };
9383 object.frame = getCodeFrame( previous, line, column );
9384 }
9385 else {
9386 object.pos = pos;
9387 var ref = locate( previous, pos, { offsetLine: 1 });
9388 var line$1 = ref.line;
9389 var column$1 = ref.column;
9390 object.loc = { file: id, line: line$1, column: column$1 };
9391 object.frame = getCodeFrame( previous, line$1, column$1 );
9392 }
9393 }
9394
9395 object.plugin = plugin.name;
9396 object.id = id;
9397
9398 return object;
9399 }
9400
9401 var throwing;
9402
9403 var context = {
9404 warn: function ( warning, pos ) {
9405 warning = augment( warning, pos, 'PLUGIN_WARNING' );
9406 bundle.warn( warning );
9407 },
9408
9409 error: function error$1 ( err, pos ) {
9410 err = augment( err, pos, 'PLUGIN_ERROR' );
9411 throwing = true;
9412 error( err );
9413 }
9414 };
9415
9416 var transformed;
9417
9418 try {
9419 transformed = plugin.transform.call( context, previous, id );
9420 } catch ( err ) {
9421 if ( !throwing ) { context.error( err ); }
9422 error( err );
9423 }
9424
9425 return Promise.resolve( transformed )
9426 .then( function (result) {
9427 if ( result == null ) { return previous; }
9428
9429 if ( typeof result === 'string' ) {
9430 result = {
9431 code: result,
9432 ast: null,
9433 map: null
9434 };
9435 }
9436
9437 // `result.map` can only be a string if `result` isn't
9438 else if ( typeof result.map === 'string' ) {
9439 result.map = JSON.parse( result.map );
9440 }
9441
9442 if ( result.map && typeof result.map.mappings === 'string' ) {
9443 result.map.mappings = decode$$1( result.map.mappings );
9444 }
9445
9446 sourceMapChain.push( result.map || { missing: true, plugin: plugin.name }); // lil' bit hacky but it works
9447 ast = result.ast;
9448
9449 return result.code;
9450 })
9451 .catch( function (err) {
9452 err = augment( err, undefined, 'PLUGIN_ERROR' );
9453 error( err );
9454 });
9455 });
9456 });
9457
9458 return promise.then( function (code) { return ({ code: code, originalCode: originalCode, originalSourceMap: originalSourceMap, ast: ast, sourceMapChain: sourceMapChain }); } );
9459}
9460
9461function transformBundle ( code, plugins, sourceMapChain, options ) {
9462 return plugins.reduce( function ( promise, plugin ) {
9463 if ( !plugin.transformBundle ) { return promise; }
9464
9465 return promise.then( function (code) {
9466 return Promise.resolve().then( function () {
9467 return plugin.transformBundle( code, { format : options.format } );
9468 }).then( function (result) {
9469 if ( result == null ) { return code; }
9470
9471 if ( typeof result === 'string' ) {
9472 result = {
9473 code: result,
9474 map: null
9475 };
9476 }
9477
9478 var map = typeof result.map === 'string' ? JSON.parse( result.map ) : result.map;
9479 if ( map && typeof map.mappings === 'string' ) {
9480 map.mappings = decode$$1( map.mappings );
9481 }
9482
9483 sourceMapChain.push( map );
9484
9485 return result.code;
9486 }).catch( function (err) {
9487 error({
9488 code: 'BAD_BUNDLE_TRANSFORMER',
9489 message: ("Error transforming bundle" + (plugin.name ? (" with '" + (plugin.name) + "' plugin") : '') + ": " + (err.message)),
9490 plugin: plugin.name
9491 });
9492 });
9493 });
9494
9495 }, Promise.resolve( code ) );
9496}
9497
9498var Source = function Source ( filename, content ) {
9499 this.isOriginal = true;
9500 this.filename = filename;
9501 this.content = content;
9502};
9503
9504Source.prototype.traceSegment = function traceSegment ( line, column, name ) {
9505 return { line: line, column: column, name: name, source: this };
9506};
9507
9508var Link = function Link ( map, sources ) {
9509 this.sources = sources;
9510 this.names = map.names;
9511 this.mappings = map.mappings;
9512};
9513
9514Link.prototype.traceMappings = function traceMappings () {
9515 var this$1 = this;
9516
9517 var sources = [];
9518 var sourcesContent = [];
9519 var names = [];
9520
9521 var mappings = this.mappings.map( function (line) {
9522 var tracedLine = [];
9523
9524 line.forEach( function (segment) {
9525 var source = this$1.sources[ segment[1] ];
9526
9527 if ( !source ) { return; }
9528
9529 var traced = source.traceSegment( segment[2], segment[3], this$1.names[ segment[4] ] );
9530
9531 if ( traced ) {
9532 var sourceIndex = null;
9533 var nameIndex = null;
9534 segment = [
9535 segment[0],
9536 null,
9537 traced.line,
9538 traced.column
9539 ];
9540
9541 // newer sources are more likely to be used, so search backwards.
9542 sourceIndex = sources.lastIndexOf( traced.source.filename );
9543 if ( sourceIndex === -1 ) {
9544 sourceIndex = sources.length;
9545 sources.push( traced.source.filename );
9546 sourcesContent[ sourceIndex ] = traced.source.content;
9547 } else if ( sourcesContent[ sourceIndex ] == null ) {
9548 sourcesContent[ sourceIndex ] = traced.source.content;
9549 } else if ( traced.source.content != null && sourcesContent[ sourceIndex ] !== traced.source.content ) {
9550 error({
9551 message: ("Multiple conflicting contents for sourcemap source " + (source.filename))
9552 });
9553 }
9554
9555 segment[1] = sourceIndex;
9556
9557 if ( traced.name ) {
9558 nameIndex = names.indexOf( traced.name );
9559 if ( nameIndex === -1 ) {
9560 nameIndex = names.length;
9561 names.push( traced.name );
9562 }
9563
9564 segment[4] = nameIndex;
9565 }
9566
9567 tracedLine.push( segment );
9568 }
9569 });
9570
9571 return tracedLine;
9572 });
9573
9574 return { sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings };
9575};
9576
9577Link.prototype.traceSegment = function traceSegment ( line, column, name ) {
9578 var this$1 = this;
9579
9580 var segments = this.mappings[ line ];
9581
9582 if ( !segments ) { return null; }
9583
9584 for ( var i = 0; i < segments.length; i += 1 ) {
9585 var segment = segments[i];
9586
9587 if ( segment[0] > column ) { return null; }
9588
9589 if ( segment[0] === column ) {
9590 var source = this$1.sources[ segment[1] ];
9591 if ( !source ) { return null; }
9592
9593 return source.traceSegment( segment[2], segment[3], this$1.names[ segment[4] ] || name );
9594 }
9595 }
9596
9597 return null;
9598};
9599
9600function collapseSourcemaps ( bundle, file, map, modules, bundleSourcemapChain ) {
9601 var moduleSources = modules.filter( function (module) { return !module.excludeFromSourcemap; } ).map( function (module) {
9602 var sourceMapChain = module.sourceMapChain;
9603
9604 var source;
9605 if ( module.originalSourceMap == null ) {
9606 source = new Source( module.id, module.originalCode );
9607 } else {
9608 var sources = module.originalSourceMap.sources;
9609 var sourcesContent = module.originalSourceMap.sourcesContent || [];
9610
9611 if ( sources == null || ( sources.length <= 1 && sources[0] == null ) ) {
9612 source = new Source( module.id, sourcesContent[0] );
9613 sourceMapChain = [ module.originalSourceMap ].concat( sourceMapChain );
9614 } else {
9615 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
9616 var directory = dirname( module.id ) || '.';
9617 var sourceRoot = module.originalSourceMap.sourceRoot || '.';
9618
9619 var baseSources = sources.map( function (source, i) {
9620 return new Source( resolve( directory, sourceRoot, source ), sourcesContent[i] );
9621 });
9622
9623 source = new Link( module.originalSourceMap, baseSources );
9624 }
9625 }
9626
9627 sourceMapChain.forEach( function (map) {
9628 if ( map.missing ) {
9629 bundle.warn({
9630 code: 'SOURCEMAP_BROKEN',
9631 plugin: map.plugin,
9632 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"),
9633 url: "https://github.com/rollup/rollup/wiki/Troubleshooting#sourcemap-is-likely-to-be-incorrect"
9634 });
9635
9636 map = {
9637 names: [],
9638 mappings: ''
9639 };
9640 }
9641
9642 source = new Link( map, [ source ]);
9643 });
9644
9645 return source;
9646 });
9647
9648 var source = new Link( map, moduleSources );
9649
9650 bundleSourcemapChain.forEach( function (map) {
9651 source = new Link( map, [ source ] );
9652 });
9653
9654 var ref = source.traceMappings();
9655 var sources = ref.sources;
9656 var sourcesContent = ref.sourcesContent;
9657 var names = ref.names;
9658 var mappings = ref.mappings;
9659
9660 if ( file ) {
9661 var directory = dirname( file );
9662 sources = sources.map( function (source) { return relative( directory, source ); } );
9663
9664 map.file = basename( file );
9665 }
9666
9667 // we re-use the `map` object because it has convenient toString/toURL methods
9668 map.sources = sources;
9669 map.sourcesContent = sourcesContent;
9670 map.names = names;
9671 map.mappings = encode$$1( mappings );
9672
9673 return map;
9674}
9675
9676function callIfFunction ( thing ) {
9677 return typeof thing === 'function' ? thing() : thing;
9678}
9679
9680var SyntheticGlobalDeclaration = function SyntheticGlobalDeclaration ( name ) {
9681 this.name = name;
9682 this.isExternal = true;
9683 this.isGlobal = true;
9684 this.isReassigned = false;
9685
9686 this.activated = true;
9687};
9688
9689SyntheticGlobalDeclaration.prototype.activate = function activate () {
9690 /* noop */
9691};
9692
9693SyntheticGlobalDeclaration.prototype.addReference = function addReference ( reference ) {
9694 reference.declaration = this;
9695 if ( reference.isReassignment ) { this.isReassigned = true; }
9696};
9697
9698SyntheticGlobalDeclaration.prototype.gatherPossibleValues = function gatherPossibleValues ( values ) {
9699 values.add( UNKNOWN );
9700};
9701
9702SyntheticGlobalDeclaration.prototype.getName = function getName () {
9703 return this.name;
9704};
9705
9706var BundleScope = (function (Scope$$1) {
9707 function BundleScope () {
9708 Scope$$1.apply(this, arguments);
9709 }
9710
9711 if ( Scope$$1 ) BundleScope.__proto__ = Scope$$1;
9712 BundleScope.prototype = Object.create( Scope$$1 && Scope$$1.prototype );
9713 BundleScope.prototype.constructor = BundleScope;
9714
9715 BundleScope.prototype.findDeclaration = function findDeclaration ( name ) {
9716 if ( !this.declarations[ name ] ) {
9717 this.declarations[ name ] = new SyntheticGlobalDeclaration( name );
9718 }
9719
9720 return this.declarations[ name ];
9721 };
9722
9723 return BundleScope;
9724}(Scope));
9725
9726var Bundle = function Bundle ( options ) {
9727 var this$1 = this;
9728
9729 this.cachedModules = new Map();
9730 if ( options.cache ) {
9731 options.cache.modules.forEach( function (module) {
9732 this$1.cachedModules.set( module.id, module );
9733 } );
9734 }
9735
9736 this.plugins = ensureArray( options.plugins );
9737
9738 options = this.plugins.reduce( function ( acc, plugin ) {
9739 if ( plugin.options ) { return plugin.options( acc ) || acc; }
9740 return acc;
9741 }, options );
9742
9743 if ( !options.entry ) {
9744 throw new Error( 'You must supply options.entry to rollup' );
9745 }
9746
9747 this.entry = options.entry;
9748 this.entryId = null;
9749 this.entryModule = null;
9750
9751 this.treeshake = options.treeshake !== false;
9752
9753 if ( options.pureExternalModules === true ) {
9754 this.isPureExternalModule = function () { return true; };
9755 } else if ( typeof options.pureExternalModules === 'function' ) {
9756 this.isPureExternalModule = options.pureExternalModules;
9757 } else if ( Array.isArray( options.pureExternalModules ) ) {
9758 var pureExternalModules = new Set( options.pureExternalModules );
9759 this.isPureExternalModule = function (id) { return pureExternalModules.has( id ); };
9760 } else {
9761 this.isPureExternalModule = function () { return false; };
9762 }
9763
9764 this.resolveId = first(
9765 [ function (id) { return this$1.isExternal( id ) ? false : null; } ]
9766 .concat( this.plugins.map( function (plugin) { return plugin.resolveId; } ).filter( Boolean ) )
9767 .concat( resolveId )
9768 );
9769
9770 var loaders = this.plugins
9771 .map( function (plugin) { return plugin.load; } )
9772 .filter( Boolean );
9773 this.hasLoaders = loaders.length !== 0;
9774 this.load = first( loaders.concat( load ) );
9775
9776 var optionsPaths = options.paths;
9777 this.getPath = typeof optionsPaths === 'function' ?
9778 ( function (id) { return optionsPaths( id ) || this$1.getPathRelativeToEntryDirname( id ); } ) :
9779 optionsPaths ?
9780 ( function (id) { return optionsPaths.hasOwnProperty( id ) ? optionsPaths[ id ] : this$1.getPathRelativeToEntryDirname( id ); } ) :
9781 function (id) { return this$1.getPathRelativeToEntryDirname( id ); };
9782
9783 this.scope = new BundleScope();
9784 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
9785 [ 'module', 'exports', '_interopDefault' ].forEach( function (name) {
9786 this$1.scope.findDeclaration( name ); // creates global declaration as side-effect
9787 } );
9788
9789 this.moduleById = new Map();
9790 this.modules = [];
9791 this.externalModules = [];
9792
9793 this.context = String( options.context );
9794
9795 var optionsModuleContext = options.moduleContext;
9796 if ( typeof optionsModuleContext === 'function' ) {
9797 this.getModuleContext = function (id) { return optionsModuleContext( id ) || this$1.context; };
9798 } else if ( typeof optionsModuleContext === 'object' ) {
9799 var moduleContext = new Map();
9800 Object.keys( optionsModuleContext ).forEach( function (key) {
9801 moduleContext.set( resolve( key ), optionsModuleContext[ key ] );
9802 } );
9803 this.getModuleContext = function (id) { return moduleContext.get( id ) || this$1.context; };
9804 } else {
9805 this.getModuleContext = function () { return this$1.context; };
9806 }
9807
9808 if ( typeof options.external === 'function' ) {
9809 this.isExternal = options.external;
9810 } else {
9811 var ids = ensureArray( options.external );
9812 this.isExternal = function (id) { return ids.indexOf( id ) !== -1; };
9813 }
9814
9815 this.onwarn = options.onwarn || makeOnwarn();
9816
9817 this.varOrConst = options.preferConst ? 'const' : 'var';
9818 this.legacy = options.legacy;
9819 this.acornOptions = options.acorn || {};
9820
9821 this.dependentExpressions = [];
9822};
9823
9824Bundle.prototype.build = function build () {
9825 var this$1 = this;
9826
9827 // Phase 1 – discovery. We load the entry module and find which
9828 // modules it imports, and import those, until we have all
9829 // of the entry module's dependencies
9830 return this.resolveId( this.entry, undefined )
9831 .then( function (id) {
9832 if ( id === false ) {
9833 error( {
9834 code: 'UNRESOLVED_ENTRY',
9835 message: "Entry module cannot be external"
9836 } );
9837 }
9838
9839 if ( id == null ) {
9840 error( {
9841 code: 'UNRESOLVED_ENTRY',
9842 message: ("Could not resolve entry (" + (this$1.entry) + ")")
9843 } );
9844 }
9845
9846 this$1.entryId = id;
9847 return this$1.fetchModule( id, undefined );
9848 } )
9849 .then( function (entryModule) {
9850 this$1.entryModule = entryModule;
9851
9852 // Phase 2 – binding. We link references to their declarations
9853 // to generate a complete picture of the bundle
9854
9855 timeStart( 'phase 2' );
9856
9857 this$1.modules.forEach( function (module) { return module.bindImportSpecifiers(); } );
9858 this$1.modules.forEach( function (module) { return module.bindReferences(); } );
9859
9860 timeEnd( 'phase 2' );
9861
9862 // Phase 3 – marking. We 'run' each statement to see which ones
9863 // need to be included in the generated bundle
9864
9865 timeStart( 'phase 3' );
9866
9867 // mark all export statements
9868 entryModule.getExports().forEach( function (name) {
9869 var declaration = entryModule.traceExport( name );
9870
9871 declaration.exportName = name;
9872 declaration.activate();
9873
9874 if ( declaration.isNamespace ) {
9875 declaration.needsNamespaceBlock = true;
9876 }
9877 });
9878
9879 entryModule.getReexports().forEach( function (name) {
9880 var declaration = entryModule.traceExport( name );
9881
9882 if ( declaration.isExternal ) {
9883 declaration.reexported = declaration.module.reexported = true;
9884 } else {
9885 declaration.exportName = name;
9886 declaration.activate();
9887 }
9888 });
9889
9890 // mark statements that should appear in the bundle
9891 if ( this$1.treeshake ) {
9892 this$1.modules.forEach( function (module) {
9893 module.run();
9894 } );
9895
9896 var settled = false;
9897 while ( !settled ) {
9898 settled = true;
9899
9900 var i = this$1.dependentExpressions.length;
9901 while ( i-- ) {
9902 var expression = this$1.dependentExpressions[ i ];
9903
9904 var statement = expression;
9905 while ( statement.parent && !/Function/.test( statement.parent.type ) ) { statement = statement.parent; }
9906
9907 if ( !statement || statement.ran ) {
9908 this$1.dependentExpressions.splice( i, 1 );
9909 } else if ( expression.isUsedByBundle() ) {
9910 settled = false;
9911 statement.run();
9912 this$1.dependentExpressions.splice( i, 1 );
9913 }
9914 }
9915 }
9916 }
9917
9918 timeEnd( 'phase 3' );
9919
9920 // Phase 4 – final preparation. We order the modules with an
9921 // enhanced topological sort that accounts for cycles, then
9922 // ensure that names are deconflicted throughout the bundle
9923
9924 timeStart( 'phase 4' );
9925
9926 // while we're here, check for unused external imports
9927 this$1.externalModules.forEach( function (module) {
9928 var unused = Object.keys( module.declarations )
9929 .filter( function (name) { return name !== '*'; } )
9930 .filter( function (name) { return !module.declarations[ name ].activated && !module.declarations[ name ].reexported; } );
9931
9932 if ( unused.length === 0 ) { return; }
9933
9934 var names = unused.length === 1 ?
9935 ("'" + (unused[0]) + "' is") :
9936 ((unused.slice( 0, -1 ).map( function (name) { return ("'" + name + "'"); } ).join( ', ' )) + " and '" + (unused.slice( -1 )) + "' are");
9937
9938 this$1.warn( {
9939 code: 'UNUSED_EXTERNAL_IMPORT',
9940 source: module.id,
9941 names: unused,
9942 message: (names + " imported from external module '" + (module.id) + "' but never used")
9943 } );
9944 } );
9945
9946 // prune unused external imports
9947 this$1.externalModules = this$1.externalModules.filter( function (module) {
9948 return module.used || !this$1.isPureExternalModule( module.id );
9949 } );
9950
9951 this$1.orderedModules = this$1.sort();
9952 this$1.deconflict();
9953
9954 timeEnd( 'phase 4' );
9955 } );
9956};
9957
9958Bundle.prototype.deconflict = function deconflict () {
9959 var used = blank();
9960
9961 // ensure no conflicts with globals
9962 keys( this.scope.declarations ).forEach( function (name) { return used[ name ] = 1; } );
9963
9964 function getSafeName ( name ) {
9965 while ( used[ name ] ) {
9966 name += "$" + (used[ name ]++);
9967 }
9968
9969 used[ name ] = 1;
9970 return name;
9971 }
9972
9973 var toDeshadow = new Set();
9974
9975 this.externalModules.forEach( function (module) {
9976 var safeName = getSafeName( module.name );
9977 toDeshadow.add( safeName );
9978 module.name = safeName;
9979
9980 // ensure we don't shadow named external imports, if
9981 // we're creating an ES6 bundle
9982 forOwn( module.declarations, function ( declaration, name ) {
9983 var safeName = getSafeName( name );
9984 toDeshadow.add( safeName );
9985 declaration.setSafeName( safeName );
9986 } );
9987 } );
9988
9989 this.modules.forEach( function (module) {
9990 forOwn( module.scope.declarations, function ( declaration ) {
9991 if ( declaration.isDefault && declaration.declaration.id ) {
9992 return;
9993 }
9994
9995 declaration.name = getSafeName( declaration.name );
9996 } );
9997
9998 // deconflict reified namespaces
9999 var namespace = module.namespace();
10000 if ( namespace.needsNamespaceBlock ) {
10001 namespace.name = getSafeName( namespace.name );
10002 }
10003 } );
10004
10005 this.scope.deshadow( toDeshadow );
10006};
10007
10008Bundle.prototype.fetchModule = function fetchModule ( id, importer ) {
10009 var this$1 = this;
10010
10011 // short-circuit cycles
10012 if ( this.moduleById.has( id ) ) { return null; }
10013 this.moduleById.set( id, null );
10014
10015 return this.load( id )
10016 .catch( function (err) {
10017 var msg = "Could not load " + id;
10018 if ( importer ) { msg += " (imported by " + importer + ")"; }
10019
10020 msg += ": " + (err.message);
10021 throw new Error( msg );
10022 } )
10023 .then( function (source) {
10024 if ( typeof source === 'string' ) { return source; }
10025 if ( source && typeof source === 'object' && source.code ) { return source; }
10026
10027 // TODO report which plugin failed
10028 error( {
10029 code: 'BAD_LOADER',
10030 message: ("Error loading " + (relativeId( id )) + ": plugin load hook should return a string, a { code, map } object, or nothing/null")
10031 } );
10032 } )
10033 .then( function (source) {
10034 if ( typeof source === 'string' ) {
10035 source = {
10036 code: source,
10037 ast: null
10038 };
10039 }
10040
10041 if ( this$1.cachedModules.has( id ) && this$1.cachedModules.get( id ).originalCode === source.code ) {
10042 return this$1.cachedModules.get( id );
10043 }
10044
10045 return transform( this$1, source, id, this$1.plugins );
10046 } )
10047 .then( function (source) {
10048 var code = source.code;
10049 var originalCode = source.originalCode;
10050 var originalSourceMap = source.originalSourceMap;
10051 var ast = source.ast;
10052 var sourceMapChain = source.sourceMapChain;
10053 var resolvedIds = source.resolvedIds;
10054
10055 var module = new Module( {
10056 id: id,
10057 code: code,
10058 originalCode: originalCode,
10059 originalSourceMap: originalSourceMap,
10060 ast: ast,
10061 sourceMapChain: sourceMapChain,
10062 resolvedIds: resolvedIds,
10063 bundle: this$1
10064 } );
10065
10066 this$1.modules.push( module );
10067 this$1.moduleById.set( id, module );
10068
10069 return this$1.fetchAllDependencies( module ).then( function () {
10070 keys( module.exports ).forEach( function (name) {
10071 if ( name !== 'default' ) {
10072 module.exportsAll[ name ] = module.id;
10073 }
10074 } );
10075 module.exportAllSources.forEach( function (source) {
10076 var id = module.resolvedIds[ source ] || module.resolvedExternalIds[ source ];
10077 var exportAllModule = this$1.moduleById.get( id );
10078 if ( exportAllModule.isExternal ) { return; }
10079
10080 keys( exportAllModule.exportsAll ).forEach( function (name) {
10081 if ( name in module.exportsAll ) {
10082 this$1.warn( {
10083 code: 'NAMESPACE_CONFLICT',
10084 reexporter: module.id,
10085 name: name,
10086 sources: [ module.exportsAll[ name ], exportAllModule.exportsAll[ name ] ],
10087 message: ("Conflicting namespaces: " + (relativeId( module.id )) + " re-exports '" + name + "' from both " + (relativeId( module.exportsAll[ name ] )) + " and " + (relativeId( exportAllModule.exportsAll[ name ] )) + " (will be ignored)")
10088 } );
10089 } else {
10090 module.exportsAll[ name ] = exportAllModule.exportsAll[ name ];
10091 }
10092 } );
10093 } );
10094 return module;
10095 } );
10096 } );
10097};
10098
10099Bundle.prototype.fetchAllDependencies = function fetchAllDependencies ( module ) {
10100 var this$1 = this;
10101
10102 return mapSequence( module.sources, function (source) {
10103 var resolvedId = module.resolvedIds[ source ];
10104 return ( resolvedId ? Promise.resolve( resolvedId ) : this$1.resolveId( source, module.id ) )
10105 .then( function (resolvedId) {
10106 var externalId = resolvedId || (
10107 isRelative( source ) ? resolve( module.id, '..', source ) : source
10108 );
10109
10110 var isExternal = this$1.isExternal( externalId );
10111
10112 if ( !resolvedId && !isExternal ) {
10113 if ( isRelative( source ) ) {
10114 error( {
10115 code: 'UNRESOLVED_IMPORT',
10116 message: ("Could not resolve '" + source + "' from " + (relativeId( module.id )))
10117 } );
10118 }
10119
10120 this$1.warn( {
10121 code: 'UNRESOLVED_IMPORT',
10122 source: source,
10123 importer: relativeId( module.id ),
10124 message: ("'" + source + "' is imported by " + (relativeId( module.id )) + ", but could not be resolved – treating it as an external dependency"),
10125 url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency'
10126 } );
10127 isExternal = true;
10128 }
10129
10130 if ( isExternal ) {
10131 module.resolvedExternalIds[ source ] = externalId;
10132
10133 if ( !this$1.moduleById.has( externalId ) ) {
10134 var module$1$$1 = new ExternalModule( externalId, this$1.getPath( externalId ) );
10135 this$1.externalModules.push( module$1$$1 );
10136 this$1.moduleById.set( externalId, module$1$$1 );
10137 }
10138
10139 var externalModule = this$1.moduleById.get( externalId );
10140
10141 // add external declarations so we can detect which are never used
10142 Object.keys( module.imports ).forEach( function (name) {
10143 var importDeclaration = module.imports[ name ];
10144 if ( importDeclaration.source !== source ) { return; }
10145
10146 externalModule.traceExport( importDeclaration.name );
10147 } );
10148 } else {
10149 if ( resolvedId === module.id ) {
10150 // need to find the actual import declaration, so we can provide
10151 // a useful error message. Bit hoop-jumpy but what can you do
10152 var declaration = module.ast.body.find( function (node) {
10153 return node.isImportDeclaration && node.source.value === source;
10154 } );
10155
10156 module.error( {
10157 code: 'CANNOT_IMPORT_SELF',
10158 message: "A module cannot import itself"
10159 }, declaration.start );
10160 }
10161
10162 module.resolvedIds[ source ] = resolvedId;
10163 return this$1.fetchModule( resolvedId, module.id );
10164 }
10165 } );
10166 } );
10167};
10168
10169Bundle.prototype.getPathRelativeToEntryDirname = function getPathRelativeToEntryDirname ( resolvedId ) {
10170 if ( isRelative( resolvedId ) || isAbsolute( resolvedId ) ) {
10171 var entryDirname = dirname( this.entryId );
10172 var relativeToEntry = normalize( relative( entryDirname, resolvedId ) );
10173
10174 return isRelative( relativeToEntry ) ? relativeToEntry : ("./" + relativeToEntry);
10175 }
10176
10177 return resolvedId;
10178};
10179
10180Bundle.prototype.render = function render ( options ) {
10181 var this$1 = this;
10182 if ( options === void 0 ) options = {};
10183
10184 return Promise.resolve().then( function () {
10185 // Determine export mode - 'default', 'named', 'none'
10186 var exportMode = getExportMode( this$1, options );
10187
10188 var magicString = new Bundle$2( { separator: '\n\n' } );
10189 var usedModules = [];
10190
10191 timeStart( 'render modules' );
10192
10193 this$1.orderedModules.forEach( function (module) {
10194 var source = module.render( options.format === 'es', this$1.legacy );
10195
10196 if ( source.toString().length ) {
10197 magicString.addSource( source );
10198 usedModules.push( module );
10199 }
10200 } );
10201
10202 if ( !magicString.toString().trim() && this$1.entryModule.getExports().length === 0 && this$1.entryModule.getReexports().length === 0 ) {
10203 this$1.warn( {
10204 code: 'EMPTY_BUNDLE',
10205 message: 'Generated an empty bundle'
10206 } );
10207 }
10208
10209 timeEnd( 'render modules' );
10210
10211 var intro = [ options.intro ]
10212 .concat(
10213 this$1.plugins.map( function (plugin) { return plugin.intro && plugin.intro(); } )
10214 )
10215 .filter( Boolean )
10216 .join( '\n\n' );
10217
10218 if ( intro ) { intro += '\n\n'; }
10219
10220 var outro = [ options.outro ]
10221 .concat(
10222 this$1.plugins.map( function (plugin) { return plugin.outro && plugin.outro(); } )
10223 )
10224 .filter( Boolean )
10225 .join( '\n\n' );
10226
10227 if ( outro ) { outro = "\n\n" + outro; }
10228
10229 var indentString = getIndentString( magicString, options );
10230
10231 var finalise = finalisers[ options.format ];
10232 if ( !finalise ) {
10233 error({
10234 code: 'INVALID_OPTION',
10235 message: ("Invalid format: " + (options.format) + " - valid options are " + (keys( finalisers ).join( ', ' )))
10236 });
10237 }
10238
10239 timeStart( 'render format' );
10240
10241 magicString = finalise( this$1, magicString.trim(), { exportMode: exportMode, indentString: indentString, intro: intro, outro: outro }, options );
10242
10243 timeEnd( 'render format' );
10244
10245 var banner = [ options.banner ]
10246 .concat( this$1.plugins.map( function (plugin) { return plugin.banner; } ) )
10247 .map( callIfFunction )
10248 .filter( Boolean )
10249 .join( '\n' );
10250
10251 var footer = [ options.footer ]
10252 .concat( this$1.plugins.map( function (plugin) { return plugin.footer; } ) )
10253 .map( callIfFunction )
10254 .filter( Boolean )
10255 .join( '\n' );
10256
10257 if ( banner ) { magicString.prepend( banner + '\n' ); }
10258 if ( footer ) { magicString.append( '\n' + footer ); }
10259
10260 var prevCode = magicString.toString();
10261 var map = null;
10262 var bundleSourcemapChain = [];
10263
10264 return transformBundle( prevCode, this$1.plugins, bundleSourcemapChain, options ).then( function (code) {
10265 if ( options.sourceMap ) {
10266 timeStart( 'sourceMap' );
10267
10268 var file = options.sourceMapFile || options.dest;
10269 if ( file ) { file = resolve( typeof process !== 'undefined' ? process.cwd() : '', file ); }
10270
10271 if ( this$1.hasLoaders || find( this$1.plugins, function (plugin) { return plugin.transform || plugin.transformBundle; } ) ) {
10272 map = magicString.generateMap( {} );
10273 if ( typeof map.mappings === 'string' ) {
10274 map.mappings = decode$$1( map.mappings );
10275 }
10276 map = collapseSourcemaps( this$1, file, map, usedModules, bundleSourcemapChain );
10277 } else {
10278 map = magicString.generateMap( { file: file, includeContent: true } );
10279 }
10280
10281 map.sources = map.sources.map( normalize );
10282
10283 timeEnd( 'sourceMap' );
10284 }
10285
10286 if ( code[ code.length - 1 ] !== '\n' ) { code += '\n'; }
10287 return { code: code, map: map };
10288 } );
10289 } );
10290};
10291
10292Bundle.prototype.sort = function sort () {
10293 var this$1 = this;
10294
10295 var hasCycles;
10296 var seen = {};
10297 var ordered = [];
10298
10299 var stronglyDependsOn = blank();
10300 var dependsOn = blank();
10301
10302 this.modules.forEach( function (module) {
10303 stronglyDependsOn[ module.id ] = blank();
10304 dependsOn[ module.id ] = blank();
10305 } );
10306
10307 this.modules.forEach( function (module) {
10308 function processStrongDependency ( dependency ) {
10309 if ( dependency === module || stronglyDependsOn[ module.id ][ dependency.id ] ) { return; }
10310
10311 stronglyDependsOn[ module.id ][ dependency.id ] = true;
10312 dependency.strongDependencies.forEach( processStrongDependency );
10313 }
10314
10315 function processDependency ( dependency ) {
10316 if ( dependency === module || dependsOn[ module.id ][ dependency.id ] ) { return; }
10317
10318 dependsOn[ module.id ][ dependency.id ] = true;
10319 dependency.dependencies.forEach( processDependency );
10320 }
10321
10322 module.strongDependencies.forEach( processStrongDependency );
10323 module.dependencies.forEach( processDependency );
10324 } );
10325
10326 var visit = function (module) {
10327 if ( seen[ module.id ] ) {
10328 hasCycles = true;
10329 return;
10330 }
10331
10332 seen[ module.id ] = true;
10333
10334 module.dependencies.forEach( visit );
10335 ordered.push( module );
10336 };
10337
10338 visit( this.entryModule );
10339
10340 if ( hasCycles ) {
10341 ordered.forEach( function ( a, i ) {
10342 var loop = function ( ) {
10343 var b = ordered[ i ];
10344
10345 // TODO reinstate this! it no longer works
10346 if ( stronglyDependsOn[ a.id ][ b.id ] ) {
10347 // somewhere, there is a module that imports b before a. Because
10348 // b imports a, a is placed before b. We need to find the module
10349 // in question, so we can provide a useful error message
10350 var parent = '[[unknown]]';
10351 var visited = {};
10352
10353 var findParent = function (module) {
10354 if ( dependsOn[ module.id ][ a.id ] && dependsOn[ module.id ][ b.id ] ) {
10355 parent = module.id;
10356 return true;
10357 }
10358 visited[ module.id ] = true;
10359 for ( var i = 0; i < module.dependencies.length; i += 1 ) {
10360 var dependency = module.dependencies[ i ];
10361 if ( !visited[ dependency.id ] && findParent( dependency ) ) { return true; }
10362 }
10363 };
10364
10365 findParent( this$1.entryModule );
10366
10367 this$1.onwarn(
10368 ("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")
10369 );
10370 }
10371 };
10372
10373 for ( i += 1; i < ordered.length; i += 1 ) loop( );
10374 } );
10375 }
10376
10377 return ordered;
10378};
10379
10380Bundle.prototype.warn = function warn ( warning ) {
10381 warning.toString = function () {
10382 var str = '';
10383
10384 if ( warning.plugin ) { str += "(" + (warning.plugin) + " plugin) "; }
10385 if ( warning.loc ) { str += (relativeId( warning.loc.file )) + " (" + (warning.loc.line) + ":" + (warning.loc.column) + ") "; }
10386 str += warning.message;
10387
10388 return str;
10389 };
10390
10391 this.onwarn( warning );
10392};
10393
10394var ALLOWED_KEYS = [
10395 'acorn',
10396 'amd',
10397 'banner',
10398 'cache',
10399 'context',
10400 'dest',
10401 'entry',
10402 'exports',
10403 'extend',
10404 'external',
10405 'footer',
10406 'format',
10407 'globals',
10408 'indent',
10409 'interop',
10410 'intro',
10411 'legacy',
10412 'moduleContext',
10413 'moduleName',
10414 'noConflict',
10415 'onwarn',
10416 'outro',
10417 'paths',
10418 'plugins',
10419 'preferConst',
10420 'pureExternalModules',
10421 'sourceMap',
10422 'sourceMapFile',
10423 'targets',
10424 'treeshake',
10425 'useStrict',
10426 'watch'
10427];
10428
10429function checkAmd ( options ) {
10430 if ( options.moduleId ) {
10431 if ( options.amd ) { throw new Error( 'Cannot have both options.amd and options.moduleId' ); }
10432
10433 options.amd = { id: options.moduleId };
10434 delete options.moduleId;
10435
10436 var msg = "options.moduleId is deprecated in favour of options.amd = { id: moduleId }";
10437 if ( options.onwarn ) {
10438 options.onwarn( msg );
10439 } else {
10440 console.warn( msg ); // eslint-disable-line no-console
10441 }
10442 }
10443}
10444
10445function checkOptions ( options ) {
10446 if ( !options ) {
10447 throw new Error( 'You must supply an options object to rollup' );
10448 }
10449
10450 if ( options.transform || options.load || options.resolveId || options.resolveExternal ) {
10451 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' );
10452 }
10453
10454 checkAmd (options);
10455
10456 var err = validateKeys( keys(options), ALLOWED_KEYS );
10457 if ( err ) { throw err; }
10458}
10459
10460var throwAsyncGenerateError = {
10461 get: function get () {
10462 throw new Error( "bundle.generate(...) now returns a Promise instead of a { code, map } object" );
10463 }
10464};
10465
10466function rollup ( options ) {
10467 try {
10468 checkOptions( options );
10469 var bundle = new Bundle( options );
10470
10471 timeStart( '--BUILD--' );
10472
10473 return bundle.build().then( function () {
10474 timeEnd( '--BUILD--' );
10475
10476 function generate ( options ) {
10477 if ( options === void 0 ) options = {};
10478
10479 if ( options.format === 'es6' ) {
10480 throw new Error( 'The `es6` output format is deprecated – use `es` instead' );
10481 }
10482
10483 if ( !options.format ) {
10484 error({
10485 code: 'MISSING_FORMAT',
10486 message: "You must supply an output format",
10487 url: "https://github.com/rollup/rollup/wiki/JavaScript-API#format"
10488 });
10489 }
10490
10491 checkAmd( options );
10492
10493 timeStart( '--GENERATE--' );
10494
10495 var promise = Promise.resolve()
10496 .then( function () { return bundle.render( options ); } )
10497 .then( function (rendered) {
10498 timeEnd( '--GENERATE--' );
10499
10500 bundle.plugins.forEach( function (plugin) {
10501 if ( plugin.ongenerate ) {
10502 plugin.ongenerate( assign({
10503 bundle: result
10504 }, options ), rendered);
10505 }
10506 });
10507
10508 flushTime();
10509
10510 return rendered;
10511 });
10512
10513 Object.defineProperty( promise, 'code', throwAsyncGenerateError );
10514 Object.defineProperty( promise, 'map', throwAsyncGenerateError );
10515
10516 return promise;
10517 }
10518
10519 var result = {
10520 imports: bundle.externalModules.map( function (module) { return module.id; } ),
10521 exports: keys( bundle.entryModule.exports ),
10522 modules: bundle.orderedModules.map( function (module) { return module.toJSON(); } ),
10523
10524 generate: generate,
10525 write: function (options) {
10526 if ( !options || !options.dest ) {
10527 error({
10528 code: 'MISSING_OPTION',
10529 message: 'You must supply options.dest to bundle.write'
10530 });
10531 }
10532
10533 var dest = options.dest;
10534 return generate( options ).then( function (output) {
10535 var code = output.code;
10536 var map = output.map;
10537
10538 var promises = [];
10539
10540 if ( options.sourceMap ) {
10541 var url;
10542
10543 if ( options.sourceMap === 'inline' ) {
10544 url = map.toUrl();
10545 } else {
10546 url = (basename( dest )) + ".map";
10547 promises.push( writeFile$1( dest + '.map', map.toString() ) );
10548 }
10549
10550 code += "//# " + SOURCEMAPPING_URL + "=" + url + "\n";
10551 }
10552
10553 promises.push( writeFile$1( dest, code ) );
10554 return Promise.all( promises ).then( function () {
10555 return mapSequence( bundle.plugins.filter( function (plugin) { return plugin.onwrite; } ), function (plugin) {
10556 return Promise.resolve( plugin.onwrite( assign({
10557 bundle: result
10558 }, options ), output));
10559 });
10560 });
10561 });
10562 }
10563 };
10564
10565 return result;
10566 });
10567 } catch ( err ) {
10568 return Promise.reject( err );
10569 }
10570}
10571
10572function createCommonjsModule(fn, module) {
10573 return module = { exports: {} }, fn(module, module.exports), module.exports;
10574}
10575
10576/*!
10577 * filename-regex <https://github.com/regexps/filename-regex>
10578 *
10579 * Copyright (c) 2014-2015, Jon Schlinkert
10580 * Licensed under the MIT license.
10581 */
10582
10583var index$2 = function filenameRegex() {
10584 return /([^\\\/]+)$/;
10585};
10586
10587/*!
10588 * arr-flatten <https://github.com/jonschlinkert/arr-flatten>
10589 *
10590 * Copyright (c) 2014-2017, Jon Schlinkert.
10591 * Released under the MIT License.
10592 */
10593
10594var index$6 = function (arr) {
10595 return flat(arr, []);
10596};
10597
10598function flat(arr, res) {
10599 var i = 0, cur;
10600 var len = arr.length;
10601 for (; i < len; i++) {
10602 cur = arr[i];
10603 Array.isArray(cur) ? flat(cur, res) : res.push(cur);
10604 }
10605 return res;
10606}
10607
10608var slice = [].slice;
10609
10610/**
10611 * Return the difference between the first array and
10612 * additional arrays.
10613 *
10614 * ```js
10615 * var diff = require('{%= name %}');
10616 *
10617 * var a = ['a', 'b', 'c', 'd'];
10618 * var b = ['b', 'c'];
10619 *
10620 * console.log(diff(a, b))
10621 * //=> ['a', 'd']
10622 * ```
10623 *
10624 * @param {Array} `a`
10625 * @param {Array} `b`
10626 * @return {Array}
10627 * @api public
10628 */
10629
10630function diff(arr, arrays) {
10631 var argsLen = arguments.length;
10632 var len = arr.length, i = -1;
10633 var res = [], arrays;
10634
10635 if (argsLen === 1) {
10636 return arr;
10637 }
10638
10639 if (argsLen > 2) {
10640 arrays = index$6(slice.call(arguments, 1));
10641 }
10642
10643 while (++i < len) {
10644 if (!~arrays.indexOf(arr[i])) {
10645 res.push(arr[i]);
10646 }
10647 }
10648 return res;
10649}
10650
10651/**
10652 * Expose `diff`
10653 */
10654
10655var index$4 = diff;
10656
10657/*!
10658 * array-unique <https://github.com/jonschlinkert/array-unique>
10659 *
10660 * Copyright (c) 2014-2015, Jon Schlinkert.
10661 * Licensed under the MIT License.
10662 */
10663
10664var index$8 = function unique(arr) {
10665 if (!Array.isArray(arr)) {
10666 throw new TypeError('array-unique expects an array.');
10667 }
10668
10669 var len = arr.length;
10670 var i = -1;
10671
10672 while (i++ < len) {
10673 var j = i + 1;
10674
10675 for (; j < arr.length; ++j) {
10676 if (arr[i] === arr[j]) {
10677 arr.splice(j--, 1);
10678 }
10679 }
10680 }
10681 return arr;
10682};
10683
10684var toString$1$1 = {}.toString;
10685
10686var index$18 = Array.isArray || function (arr) {
10687 return toString$1$1.call(arr) == '[object Array]';
10688};
10689
10690var index$16 = function isObject(val) {
10691 return val != null && typeof val === 'object' && index$18(val) === false;
10692};
10693
10694/*!
10695 * Determine if an object is a Buffer
10696 *
10697 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
10698 * @license MIT
10699 */
10700
10701// The _isBuffer check is for Safari 5-7 support, because it's missing
10702// Object.prototype.constructor. Remove this eventually
10703var index$24 = function (obj) {
10704 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
10705};
10706
10707function isBuffer (obj) {
10708 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
10709}
10710
10711// For Node v0.10 support. Remove this eventually.
10712function isSlowBuffer (obj) {
10713 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
10714}
10715
10716var toString$2 = Object.prototype.toString;
10717
10718/**
10719 * Get the native `typeof` a value.
10720 *
10721 * @param {*} `val`
10722 * @return {*} Native javascript type
10723 */
10724
10725var index$22 = function kindOf(val) {
10726 // primitivies
10727 if (typeof val === 'undefined') {
10728 return 'undefined';
10729 }
10730 if (val === null) {
10731 return 'null';
10732 }
10733 if (val === true || val === false || val instanceof Boolean) {
10734 return 'boolean';
10735 }
10736 if (typeof val === 'string' || val instanceof String) {
10737 return 'string';
10738 }
10739 if (typeof val === 'number' || val instanceof Number) {
10740 return 'number';
10741 }
10742
10743 // functions
10744 if (typeof val === 'function' || val instanceof Function) {
10745 return 'function';
10746 }
10747
10748 // array
10749 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
10750 return 'array';
10751 }
10752
10753 // check for instances of RegExp and Date before calling `toString`
10754 if (val instanceof RegExp) {
10755 return 'regexp';
10756 }
10757 if (val instanceof Date) {
10758 return 'date';
10759 }
10760
10761 // other objects
10762 var type = toString$2.call(val);
10763
10764 if (type === '[object RegExp]') {
10765 return 'regexp';
10766 }
10767 if (type === '[object Date]') {
10768 return 'date';
10769 }
10770 if (type === '[object Arguments]') {
10771 return 'arguments';
10772 }
10773 if (type === '[object Error]') {
10774 return 'error';
10775 }
10776
10777 // buffer
10778 if (index$24(val)) {
10779 return 'buffer';
10780 }
10781
10782 // es6: Map, WeakMap, Set, WeakSet
10783 if (type === '[object Set]') {
10784 return 'set';
10785 }
10786 if (type === '[object WeakSet]') {
10787 return 'weakset';
10788 }
10789 if (type === '[object Map]') {
10790 return 'map';
10791 }
10792 if (type === '[object WeakMap]') {
10793 return 'weakmap';
10794 }
10795 if (type === '[object Symbol]') {
10796 return 'symbol';
10797 }
10798
10799 // typed arrays
10800 if (type === '[object Int8Array]') {
10801 return 'int8array';
10802 }
10803 if (type === '[object Uint8Array]') {
10804 return 'uint8array';
10805 }
10806 if (type === '[object Uint8ClampedArray]') {
10807 return 'uint8clampedarray';
10808 }
10809 if (type === '[object Int16Array]') {
10810 return 'int16array';
10811 }
10812 if (type === '[object Uint16Array]') {
10813 return 'uint16array';
10814 }
10815 if (type === '[object Int32Array]') {
10816 return 'int32array';
10817 }
10818 if (type === '[object Uint32Array]') {
10819 return 'uint32array';
10820 }
10821 if (type === '[object Float32Array]') {
10822 return 'float32array';
10823 }
10824 if (type === '[object Float64Array]') {
10825 return 'float64array';
10826 }
10827
10828 // must be a plain object
10829 return 'object';
10830};
10831
10832var index$20 = function isNumber(num) {
10833 var type = index$22(num);
10834 if (type !== 'number' && type !== 'string') {
10835 return false;
10836 }
10837 var n = +num;
10838 return (n - n + 1) >= 0 && num !== '';
10839};
10840
10841var toString$3 = Object.prototype.toString;
10842
10843/**
10844 * Get the native `typeof` a value.
10845 *
10846 * @param {*} `val`
10847 * @return {*} Native javascript type
10848 */
10849
10850var index$30 = function kindOf(val) {
10851 // primitivies
10852 if (typeof val === 'undefined') {
10853 return 'undefined';
10854 }
10855 if (val === null) {
10856 return 'null';
10857 }
10858 if (val === true || val === false || val instanceof Boolean) {
10859 return 'boolean';
10860 }
10861 if (typeof val === 'string' || val instanceof String) {
10862 return 'string';
10863 }
10864 if (typeof val === 'number' || val instanceof Number) {
10865 return 'number';
10866 }
10867
10868 // functions
10869 if (typeof val === 'function' || val instanceof Function) {
10870 return 'function';
10871 }
10872
10873 // array
10874 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
10875 return 'array';
10876 }
10877
10878 // check for instances of RegExp and Date before calling `toString`
10879 if (val instanceof RegExp) {
10880 return 'regexp';
10881 }
10882 if (val instanceof Date) {
10883 return 'date';
10884 }
10885
10886 // other objects
10887 var type = toString$3.call(val);
10888
10889 if (type === '[object RegExp]') {
10890 return 'regexp';
10891 }
10892 if (type === '[object Date]') {
10893 return 'date';
10894 }
10895 if (type === '[object Arguments]') {
10896 return 'arguments';
10897 }
10898 if (type === '[object Error]') {
10899 return 'error';
10900 }
10901
10902 // buffer
10903 if (index$24(val)) {
10904 return 'buffer';
10905 }
10906
10907 // es6: Map, WeakMap, Set, WeakSet
10908 if (type === '[object Set]') {
10909 return 'set';
10910 }
10911 if (type === '[object WeakSet]') {
10912 return 'weakset';
10913 }
10914 if (type === '[object Map]') {
10915 return 'map';
10916 }
10917 if (type === '[object WeakMap]') {
10918 return 'weakmap';
10919 }
10920 if (type === '[object Symbol]') {
10921 return 'symbol';
10922 }
10923
10924 // typed arrays
10925 if (type === '[object Int8Array]') {
10926 return 'int8array';
10927 }
10928 if (type === '[object Uint8Array]') {
10929 return 'uint8array';
10930 }
10931 if (type === '[object Uint8ClampedArray]') {
10932 return 'uint8clampedarray';
10933 }
10934 if (type === '[object Int16Array]') {
10935 return 'int16array';
10936 }
10937 if (type === '[object Uint16Array]') {
10938 return 'uint16array';
10939 }
10940 if (type === '[object Int32Array]') {
10941 return 'int32array';
10942 }
10943 if (type === '[object Uint32Array]') {
10944 return 'uint32array';
10945 }
10946 if (type === '[object Float32Array]') {
10947 return 'float32array';
10948 }
10949 if (type === '[object Float64Array]') {
10950 return 'float64array';
10951 }
10952
10953 // must be a plain object
10954 return 'object';
10955};
10956
10957var index$28 = function isNumber(num) {
10958 var type = index$30(num);
10959
10960 if (type === 'string') {
10961 if (!num.trim()) return false;
10962 } else if (type !== 'number') {
10963 return false;
10964 }
10965
10966 return (num - num + 1) >= 0;
10967};
10968
10969var toString$4 = Object.prototype.toString;
10970
10971/**
10972 * Get the native `typeof` a value.
10973 *
10974 * @param {*} `val`
10975 * @return {*} Native javascript type
10976 */
10977
10978var index$32 = function kindOf(val) {
10979 // primitivies
10980 if (typeof val === 'undefined') {
10981 return 'undefined';
10982 }
10983 if (val === null) {
10984 return 'null';
10985 }
10986 if (val === true || val === false || val instanceof Boolean) {
10987 return 'boolean';
10988 }
10989 if (typeof val === 'string' || val instanceof String) {
10990 return 'string';
10991 }
10992 if (typeof val === 'number' || val instanceof Number) {
10993 return 'number';
10994 }
10995
10996 // functions
10997 if (typeof val === 'function' || val instanceof Function) {
10998 return 'function';
10999 }
11000
11001 // array
11002 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
11003 return 'array';
11004 }
11005
11006 // check for instances of RegExp and Date before calling `toString`
11007 if (val instanceof RegExp) {
11008 return 'regexp';
11009 }
11010 if (val instanceof Date) {
11011 return 'date';
11012 }
11013
11014 // other objects
11015 var type = toString$4.call(val);
11016
11017 if (type === '[object RegExp]') {
11018 return 'regexp';
11019 }
11020 if (type === '[object Date]') {
11021 return 'date';
11022 }
11023 if (type === '[object Arguments]') {
11024 return 'arguments';
11025 }
11026 if (type === '[object Error]') {
11027 return 'error';
11028 }
11029 if (type === '[object Promise]') {
11030 return 'promise';
11031 }
11032
11033 // buffer
11034 if (index$24(val)) {
11035 return 'buffer';
11036 }
11037
11038 // es6: Map, WeakMap, Set, WeakSet
11039 if (type === '[object Set]') {
11040 return 'set';
11041 }
11042 if (type === '[object WeakSet]') {
11043 return 'weakset';
11044 }
11045 if (type === '[object Map]') {
11046 return 'map';
11047 }
11048 if (type === '[object WeakMap]') {
11049 return 'weakmap';
11050 }
11051 if (type === '[object Symbol]') {
11052 return 'symbol';
11053 }
11054
11055 // typed arrays
11056 if (type === '[object Int8Array]') {
11057 return 'int8array';
11058 }
11059 if (type === '[object Uint8Array]') {
11060 return 'uint8array';
11061 }
11062 if (type === '[object Uint8ClampedArray]') {
11063 return 'uint8clampedarray';
11064 }
11065 if (type === '[object Int16Array]') {
11066 return 'int16array';
11067 }
11068 if (type === '[object Uint16Array]') {
11069 return 'uint16array';
11070 }
11071 if (type === '[object Int32Array]') {
11072 return 'int32array';
11073 }
11074 if (type === '[object Uint32Array]') {
11075 return 'uint32array';
11076 }
11077 if (type === '[object Float32Array]') {
11078 return 'float32array';
11079 }
11080 if (type === '[object Float64Array]') {
11081 return 'float64array';
11082 }
11083
11084 // must be a plain object
11085 return 'object';
11086};
11087
11088/**
11089 * Expose `randomatic`
11090 */
11091
11092var index$26 = randomatic;
11093
11094/**
11095 * Available mask characters
11096 */
11097
11098var type = {
11099 lower: 'abcdefghijklmnopqrstuvwxyz',
11100 upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
11101 number: '0123456789',
11102 special: '~!@#$%^&()_+-={}[];\',.'
11103};
11104
11105type.all = type.lower + type.upper + type.number + type.special;
11106
11107/**
11108 * Generate random character sequences of a specified `length`,
11109 * based on the given `pattern`.
11110 *
11111 * @param {String} `pattern` The pattern to use for generating the random string.
11112 * @param {String} `length` The length of the string to generate.
11113 * @param {String} `options`
11114 * @return {String}
11115 * @api public
11116 */
11117
11118function randomatic(pattern, length, options) {
11119 if (typeof pattern === 'undefined') {
11120 throw new Error('randomatic expects a string or number.');
11121 }
11122
11123 var custom = false;
11124 if (arguments.length === 1) {
11125 if (typeof pattern === 'string') {
11126 length = pattern.length;
11127
11128 } else if (index$28(pattern)) {
11129 options = {}; length = pattern; pattern = '*';
11130 }
11131 }
11132
11133 if (index$32(length) === 'object' && length.hasOwnProperty('chars')) {
11134 options = length;
11135 pattern = options.chars;
11136 length = pattern.length;
11137 custom = true;
11138 }
11139
11140 var opts = options || {};
11141 var mask = '';
11142 var res = '';
11143
11144 // Characters to be used
11145 if (pattern.indexOf('?') !== -1) mask += opts.chars;
11146 if (pattern.indexOf('a') !== -1) mask += type.lower;
11147 if (pattern.indexOf('A') !== -1) mask += type.upper;
11148 if (pattern.indexOf('0') !== -1) mask += type.number;
11149 if (pattern.indexOf('!') !== -1) mask += type.special;
11150 if (pattern.indexOf('*') !== -1) mask += type.all;
11151 if (custom) mask += pattern;
11152
11153 while (length--) {
11154 res += mask.charAt(parseInt(Math.random() * mask.length, 10));
11155 }
11156 return res;
11157}
11158
11159/*!
11160 * repeat-string <https://github.com/jonschlinkert/repeat-string>
11161 *
11162 * Copyright (c) 2014-2015, Jon Schlinkert.
11163 * Licensed under the MIT License.
11164 */
11165
11166/**
11167 * Results cache
11168 */
11169
11170var res = '';
11171var cache;
11172
11173/**
11174 * Expose `repeat`
11175 */
11176
11177var index$34 = repeat;
11178
11179/**
11180 * Repeat the given `string` the specified `number`
11181 * of times.
11182 *
11183 * **Example:**
11184 *
11185 * ```js
11186 * var repeat = require('repeat-string');
11187 * repeat('A', 5);
11188 * //=> AAAAA
11189 * ```
11190 *
11191 * @param {String} `string` The string to repeat
11192 * @param {Number} `number` The number of times to repeat the string
11193 * @return {String} Repeated string
11194 * @api public
11195 */
11196
11197function repeat(str, num) {
11198 if (typeof str !== 'string') {
11199 throw new TypeError('expected a string');
11200 }
11201
11202 // cover common, quick use cases
11203 if (num === 1) return str;
11204 if (num === 2) return str + str;
11205
11206 var max = str.length * num;
11207 if (cache !== str || typeof cache === 'undefined') {
11208 cache = str;
11209 res = '';
11210 } else if (res.length >= max) {
11211 return res.substr(0, max);
11212 }
11213
11214 while (max > res.length && num > 1) {
11215 if (num & 1) {
11216 res += str;
11217 }
11218
11219 num >>= 1;
11220 str += str;
11221 }
11222
11223 res += str;
11224 res = res.substr(0, max);
11225 return res;
11226}
11227
11228/*!
11229 * repeat-element <https://github.com/jonschlinkert/repeat-element>
11230 *
11231 * Copyright (c) 2015 Jon Schlinkert.
11232 * Licensed under the MIT license.
11233 */
11234
11235var index$36 = function repeat(ele, num) {
11236 var arr = new Array(num);
11237
11238 for (var i = 0; i < num; i++) {
11239 arr[i] = ele;
11240 }
11241
11242 return arr;
11243};
11244
11245/**
11246 * Expose `fillRange`
11247 */
11248
11249var index$14 = fillRange;
11250
11251/**
11252 * Return a range of numbers or letters.
11253 *
11254 * @param {String} `a` Start of the range
11255 * @param {String} `b` End of the range
11256 * @param {String} `step` Increment or decrement to use.
11257 * @param {Function} `fn` Custom function to modify each element in the range.
11258 * @return {Array}
11259 */
11260
11261function fillRange(a, b, step, options, fn) {
11262 if (a == null || b == null) {
11263 throw new Error('fill-range expects the first and second args to be strings.');
11264 }
11265
11266 if (typeof step === 'function') {
11267 fn = step; options = {}; step = null;
11268 }
11269
11270 if (typeof options === 'function') {
11271 fn = options; options = {};
11272 }
11273
11274 if (index$16(step)) {
11275 options = step; step = '';
11276 }
11277
11278 var expand, regex = false, sep$$1 = '';
11279 var opts = options || {};
11280
11281 if (typeof opts.silent === 'undefined') {
11282 opts.silent = true;
11283 }
11284
11285 step = step || opts.step;
11286
11287 // store a ref to unmodified arg
11288 var origA = a, origB = b;
11289
11290 b = (b.toString() === '-0') ? 0 : b;
11291
11292 if (opts.optimize || opts.makeRe) {
11293 step = step ? (step += '~') : step;
11294 expand = true;
11295 regex = true;
11296 sep$$1 = '~';
11297 }
11298
11299 // handle special step characters
11300 if (typeof step === 'string') {
11301 var match = stepRe().exec(step);
11302
11303 if (match) {
11304 var i = match.index;
11305 var m = match[0];
11306
11307 // repeat string
11308 if (m === '+') {
11309 return index$36(a, b);
11310
11311 // randomize a, `b` times
11312 } else if (m === '?') {
11313 return [index$26(a, b)];
11314
11315 // expand right, no regex reduction
11316 } else if (m === '>') {
11317 step = step.substr(0, i) + step.substr(i + 1);
11318 expand = true;
11319
11320 // expand to an array, or if valid create a reduced
11321 // string for a regex logic `or`
11322 } else if (m === '|') {
11323 step = step.substr(0, i) + step.substr(i + 1);
11324 expand = true;
11325 regex = true;
11326 sep$$1 = m;
11327
11328 // expand to an array, or if valid create a reduced
11329 // string for a regex range
11330 } else if (m === '~') {
11331 step = step.substr(0, i) + step.substr(i + 1);
11332 expand = true;
11333 regex = true;
11334 sep$$1 = m;
11335 }
11336 } else if (!index$20(step)) {
11337 if (!opts.silent) {
11338 throw new TypeError('fill-range: invalid step.');
11339 }
11340 return null;
11341 }
11342 }
11343
11344 if (/[.&*()[\]^%$#@!]/.test(a) || /[.&*()[\]^%$#@!]/.test(b)) {
11345 if (!opts.silent) {
11346 throw new RangeError('fill-range: invalid range arguments.');
11347 }
11348 return null;
11349 }
11350
11351 // has neither a letter nor number, or has both letters and numbers
11352 // this needs to be after the step logic
11353 if (!noAlphaNum(a) || !noAlphaNum(b) || hasBoth(a) || hasBoth(b)) {
11354 if (!opts.silent) {
11355 throw new RangeError('fill-range: invalid range arguments.');
11356 }
11357 return null;
11358 }
11359
11360 // validate arguments
11361 var isNumA = index$20(zeros(a));
11362 var isNumB = index$20(zeros(b));
11363
11364 if ((!isNumA && isNumB) || (isNumA && !isNumB)) {
11365 if (!opts.silent) {
11366 throw new TypeError('fill-range: first range argument is incompatible with second.');
11367 }
11368 return null;
11369 }
11370
11371 // by this point both are the same, so we
11372 // can use A to check going forward.
11373 var isNum = isNumA;
11374 var num = formatStep(step);
11375
11376 // is the range alphabetical? or numeric?
11377 if (isNum) {
11378 // if numeric, coerce to an integer
11379 a = +a; b = +b;
11380 } else {
11381 // otherwise, get the charCode to expand alpha ranges
11382 a = a.charCodeAt(0);
11383 b = b.charCodeAt(0);
11384 }
11385
11386 // is the pattern descending?
11387 var isDescending = a > b;
11388
11389 // don't create a character class if the args are < 0
11390 if (a < 0 || b < 0) {
11391 expand = false;
11392 regex = false;
11393 }
11394
11395 // detect padding
11396 var padding = isPadded(origA, origB);
11397 var res, pad, arr = [];
11398 var ii = 0;
11399
11400 // character classes, ranges and logical `or`
11401 if (regex) {
11402 if (shouldExpand(a, b, num, isNum, padding, opts)) {
11403 // make sure the correct separator is used
11404 if (sep$$1 === '|' || sep$$1 === '~') {
11405 sep$$1 = detectSeparator(a, b, num, isNum, isDescending);
11406 }
11407 return wrap$1([origA, origB], sep$$1, opts);
11408 }
11409 }
11410
11411 while (isDescending ? (a >= b) : (a <= b)) {
11412 if (padding && isNum) {
11413 pad = padding(a);
11414 }
11415
11416 // custom function
11417 if (typeof fn === 'function') {
11418 res = fn(a, isNum, pad, ii++);
11419
11420 // letters
11421 } else if (!isNum) {
11422 if (regex && isInvalidChar(a)) {
11423 res = null;
11424 } else {
11425 res = String.fromCharCode(a);
11426 }
11427
11428 // numbers
11429 } else {
11430 res = formatPadding(a, pad);
11431 }
11432
11433 // add result to the array, filtering any nulled values
11434 if (res !== null) arr.push(res);
11435
11436 // increment or decrement
11437 if (isDescending) {
11438 a -= num;
11439 } else {
11440 a += num;
11441 }
11442 }
11443
11444 // now that the array is expanded, we need to handle regex
11445 // character classes, ranges or logical `or` that wasn't
11446 // already handled before the loop
11447 if ((regex || expand) && !opts.noexpand) {
11448 // make sure the correct separator is used
11449 if (sep$$1 === '|' || sep$$1 === '~') {
11450 sep$$1 = detectSeparator(a, b, num, isNum, isDescending);
11451 }
11452 if (arr.length === 1 || a < 0 || b < 0) { return arr; }
11453 return wrap$1(arr, sep$$1, opts);
11454 }
11455
11456 return arr;
11457}
11458
11459/**
11460 * Wrap the string with the correct regex
11461 * syntax.
11462 */
11463
11464function wrap$1(arr, sep$$1, opts) {
11465 if (sep$$1 === '~') { sep$$1 = '-'; }
11466 var str = arr.join(sep$$1);
11467 var pre = opts && opts.regexPrefix;
11468
11469 // regex logical `or`
11470 if (sep$$1 === '|') {
11471 str = pre ? pre + str : str;
11472 str = '(' + str + ')';
11473 }
11474
11475 // regex character class
11476 if (sep$$1 === '-') {
11477 str = (pre && pre === '^')
11478 ? pre + str
11479 : str;
11480 str = '[' + str + ']';
11481 }
11482 return [str];
11483}
11484
11485/**
11486 * Check for invalid characters
11487 */
11488
11489function isCharClass(a, b, step, isNum, isDescending) {
11490 if (isDescending) { return false; }
11491 if (isNum) { return a <= 9 && b <= 9; }
11492 if (a < b) { return step === 1; }
11493 return false;
11494}
11495
11496/**
11497 * Detect the correct separator to use
11498 */
11499
11500function shouldExpand(a, b, num, isNum, padding, opts) {
11501 if (isNum && (a > 9 || b > 9)) { return false; }
11502 return !padding && num === 1 && a < b;
11503}
11504
11505/**
11506 * Detect the correct separator to use
11507 */
11508
11509function detectSeparator(a, b, step, isNum, isDescending) {
11510 var isChar = isCharClass(a, b, step, isNum, isDescending);
11511 if (!isChar) {
11512 return '|';
11513 }
11514 return '~';
11515}
11516
11517/**
11518 * Correctly format the step based on type
11519 */
11520
11521function formatStep(step) {
11522 return Math.abs(step >> 0) || 1;
11523}
11524
11525/**
11526 * Format padding, taking leading `-` into account
11527 */
11528
11529function formatPadding(ch, pad) {
11530 var res = pad ? pad + ch : ch;
11531 if (pad && ch.toString().charAt(0) === '-') {
11532 res = '-' + pad + ch.toString().substr(1);
11533 }
11534 return res.toString();
11535}
11536
11537/**
11538 * Check for invalid characters
11539 */
11540
11541function isInvalidChar(str) {
11542 var ch = toStr(str);
11543 return ch === '\\'
11544 || ch === '['
11545 || ch === ']'
11546 || ch === '^'
11547 || ch === '('
11548 || ch === ')'
11549 || ch === '`';
11550}
11551
11552/**
11553 * Convert to a string from a charCode
11554 */
11555
11556function toStr(ch) {
11557 return String.fromCharCode(ch);
11558}
11559
11560
11561/**
11562 * Step regex
11563 */
11564
11565function stepRe() {
11566 return /\?|>|\||\+|\~/g;
11567}
11568
11569/**
11570 * Return true if `val` has either a letter
11571 * or a number
11572 */
11573
11574function noAlphaNum(val) {
11575 return /[a-z0-9]/i.test(val);
11576}
11577
11578/**
11579 * Return true if `val` has both a letter and
11580 * a number (invalid)
11581 */
11582
11583function hasBoth(val) {
11584 return /[a-z][0-9]|[0-9][a-z]/i.test(val);
11585}
11586
11587/**
11588 * Normalize zeros for checks
11589 */
11590
11591function zeros(val) {
11592 if (/^-*0+$/.test(val.toString())) {
11593 return '0';
11594 }
11595 return val;
11596}
11597
11598/**
11599 * Return true if `val` has leading zeros,
11600 * or a similar valid pattern.
11601 */
11602
11603function hasZeros(val) {
11604 return /[^.]\.|^-*0+[0-9]/.test(val);
11605}
11606
11607/**
11608 * If the string is padded, returns a curried function with
11609 * the a cached padding string, or `false` if no padding.
11610 *
11611 * @param {*} `origA` String or number.
11612 * @return {String|Boolean}
11613 */
11614
11615function isPadded(origA, origB) {
11616 if (hasZeros(origA) || hasZeros(origB)) {
11617 var alen = length(origA);
11618 var blen = length(origB);
11619
11620 var len = alen >= blen
11621 ? alen
11622 : blen;
11623
11624 return function (a) {
11625 return index$34('0', len - length(a));
11626 };
11627 }
11628 return false;
11629}
11630
11631/**
11632 * Get the string length of `val`
11633 */
11634
11635function length(val) {
11636 return val.toString().length;
11637}
11638
11639var index$12 = function expandRange(str, options, fn) {
11640 if (typeof str !== 'string') {
11641 throw new TypeError('expand-range expects a string.');
11642 }
11643
11644 if (typeof options === 'function') {
11645 fn = options;
11646 options = {};
11647 }
11648
11649 if (typeof options === 'boolean') {
11650 options = {};
11651 options.makeRe = true;
11652 }
11653
11654 // create arguments to pass to fill-range
11655 var opts = options || {};
11656 var args = str.split('..');
11657 var len = args.length;
11658 if (len > 3) { return str; }
11659
11660 // if only one argument, it can't expand so return it
11661 if (len === 1) { return args; }
11662
11663 // if `true`, tell fill-range to regexify the string
11664 if (typeof fn === 'boolean' && fn === true) {
11665 opts.makeRe = true;
11666 }
11667
11668 args.push(opts);
11669 return index$14.apply(null, args.concat(fn));
11670};
11671
11672/*!
11673 * preserve <https://github.com/jonschlinkert/preserve>
11674 *
11675 * Copyright (c) 2014-2015, Jon Schlinkert.
11676 * Licensed under the MIT license.
11677 */
11678
11679/**
11680 * Replace tokens in `str` with a temporary, heuristic placeholder.
11681 *
11682 * ```js
11683 * tokens.before('{a\\,b}');
11684 * //=> '{__ID1__}'
11685 * ```
11686 *
11687 * @param {String} `str`
11688 * @return {String} String with placeholders.
11689 * @api public
11690 */
11691
11692var before = function before(str, re) {
11693 return str.replace(re, function (match) {
11694 var id = randomize$1();
11695 cache$1[id] = match;
11696 return '__ID' + id + '__';
11697 });
11698};
11699
11700/**
11701 * Replace placeholders in `str` with original tokens.
11702 *
11703 * ```js
11704 * tokens.after('{__ID1__}');
11705 * //=> '{a\\,b}'
11706 * ```
11707 *
11708 * @param {String} `str` String with placeholders
11709 * @return {String} `str` String with original tokens.
11710 * @api public
11711 */
11712
11713var after = function after(str) {
11714 return str.replace(/__ID(.{5})__/g, function (_, id) {
11715 return cache$1[id];
11716 });
11717};
11718
11719function randomize$1() {
11720 return Math.random().toString().slice(2, 7);
11721}
11722
11723var cache$1 = {};
11724
11725var index$38 = {
11726 before: before,
11727 after: after
11728};
11729
11730/**
11731 * Module dependencies
11732 */
11733
11734
11735
11736
11737
11738/**
11739 * Expose `braces`
11740 */
11741
11742var index$10 = function(str, options) {
11743 if (typeof str !== 'string') {
11744 throw new Error('braces expects a string');
11745 }
11746 return braces(str, options);
11747};
11748
11749/**
11750 * Expand `{foo,bar}` or `{1..5}` braces in the
11751 * given `string`.
11752 *
11753 * @param {String} `str`
11754 * @param {Array} `arr`
11755 * @param {Object} `options`
11756 * @return {Array}
11757 */
11758
11759function braces(str, arr, options) {
11760 if (str === '') {
11761 return [];
11762 }
11763
11764 if (!Array.isArray(arr)) {
11765 options = arr;
11766 arr = [];
11767 }
11768
11769 var opts = options || {};
11770 arr = arr || [];
11771
11772 if (typeof opts.nodupes === 'undefined') {
11773 opts.nodupes = true;
11774 }
11775
11776 var fn = opts.fn;
11777 var es6;
11778
11779 if (typeof opts === 'function') {
11780 fn = opts;
11781 opts = {};
11782 }
11783
11784 if (!(patternRe instanceof RegExp)) {
11785 patternRe = patternRegex();
11786 }
11787
11788 var matches = str.match(patternRe) || [];
11789 var m = matches[0];
11790
11791 switch(m) {
11792 case '\\,':
11793 return escapeCommas(str, arr, opts);
11794 case '\\.':
11795 return escapeDots(str, arr, opts);
11796 case '\/.':
11797 return escapePaths(str, arr, opts);
11798 case ' ':
11799 return splitWhitespace(str);
11800 case '{,}':
11801 return exponential(str, opts, braces);
11802 case '{}':
11803 return emptyBraces(str, arr, opts);
11804 case '\\{':
11805 case '\\}':
11806 return escapeBraces(str, arr, opts);
11807 case '${':
11808 if (!/\{[^{]+\{/.test(str)) {
11809 return arr.concat(str);
11810 } else {
11811 es6 = true;
11812 str = index$38.before(str, es6Regex());
11813 }
11814 }
11815
11816 if (!(braceRe instanceof RegExp)) {
11817 braceRe = braceRegex();
11818 }
11819
11820 var match = braceRe.exec(str);
11821 if (match == null) {
11822 return [str];
11823 }
11824
11825 var outter = match[1];
11826 var inner = match[2];
11827 if (inner === '') { return [str]; }
11828
11829 var segs, segsLength;
11830
11831 if (inner.indexOf('..') !== -1) {
11832 segs = index$12(inner, opts, fn) || inner.split(',');
11833 segsLength = segs.length;
11834
11835 } else if (inner[0] === '"' || inner[0] === '\'') {
11836 return arr.concat(str.split(/['"]/).join(''));
11837
11838 } else {
11839 segs = inner.split(',');
11840 if (opts.makeRe) {
11841 return braces(str.replace(outter, wrap(segs, '|')), opts);
11842 }
11843
11844 segsLength = segs.length;
11845 if (segsLength === 1 && opts.bash) {
11846 segs[0] = wrap(segs[0], '\\');
11847 }
11848 }
11849
11850 var len = segs.length;
11851 var i = 0, val;
11852
11853 while (len--) {
11854 var path$$1 = segs[i++];
11855
11856 if (/(\.[^.\/])/.test(path$$1)) {
11857 if (segsLength > 1) {
11858 return segs;
11859 } else {
11860 return [str];
11861 }
11862 }
11863
11864 val = splice(str, outter, path$$1);
11865
11866 if (/\{[^{}]+?\}/.test(val)) {
11867 arr = braces(val, arr, opts);
11868 } else if (val !== '') {
11869 if (opts.nodupes && arr.indexOf(val) !== -1) { continue; }
11870 arr.push(es6 ? index$38.after(val) : val);
11871 }
11872 }
11873
11874 if (opts.strict) { return filter$1(arr, filterEmpty); }
11875 return arr;
11876}
11877
11878/**
11879 * Expand exponential ranges
11880 *
11881 * `a{,}{,}` => ['a', 'a', 'a', 'a']
11882 */
11883
11884function exponential(str, options, fn) {
11885 if (typeof options === 'function') {
11886 fn = options;
11887 options = null;
11888 }
11889
11890 var opts = options || {};
11891 var esc = '__ESC_EXP__';
11892 var exp = 0;
11893 var res;
11894
11895 var parts = str.split('{,}');
11896 if (opts.nodupes) {
11897 return fn(parts.join(''), opts);
11898 }
11899
11900 exp = parts.length - 1;
11901 res = fn(parts.join(esc), opts);
11902 var len = res.length;
11903 var arr = [];
11904 var i = 0;
11905
11906 while (len--) {
11907 var ele = res[i++];
11908 var idx = ele.indexOf(esc);
11909
11910 if (idx === -1) {
11911 arr.push(ele);
11912
11913 } else {
11914 ele = ele.split('__ESC_EXP__').join('');
11915 if (!!ele && opts.nodupes !== false) {
11916 arr.push(ele);
11917
11918 } else {
11919 var num = Math.pow(2, exp);
11920 arr.push.apply(arr, index$36(ele, num));
11921 }
11922 }
11923 }
11924 return arr;
11925}
11926
11927/**
11928 * Wrap a value with parens, brackets or braces,
11929 * based on the given character/separator.
11930 *
11931 * @param {String|Array} `val`
11932 * @param {String} `ch`
11933 * @return {String}
11934 */
11935
11936function wrap(val, ch) {
11937 if (ch === '|') {
11938 return '(' + val.join(ch) + ')';
11939 }
11940 if (ch === ',') {
11941 return '{' + val.join(ch) + '}';
11942 }
11943 if (ch === '-') {
11944 return '[' + val.join(ch) + ']';
11945 }
11946 if (ch === '\\') {
11947 return '\\{' + val + '\\}';
11948 }
11949}
11950
11951/**
11952 * Handle empty braces: `{}`
11953 */
11954
11955function emptyBraces(str, arr, opts) {
11956 return braces(str.split('{}').join('\\{\\}'), arr, opts);
11957}
11958
11959/**
11960 * Filter out empty-ish values
11961 */
11962
11963function filterEmpty(ele) {
11964 return !!ele && ele !== '\\';
11965}
11966
11967/**
11968 * Handle patterns with whitespace
11969 */
11970
11971function splitWhitespace(str) {
11972 var segs = str.split(' ');
11973 var len = segs.length;
11974 var res = [];
11975 var i = 0;
11976
11977 while (len--) {
11978 res.push.apply(res, braces(segs[i++]));
11979 }
11980 return res;
11981}
11982
11983/**
11984 * Handle escaped braces: `\\{foo,bar}`
11985 */
11986
11987function escapeBraces(str, arr, opts) {
11988 if (!/\{[^{]+\{/.test(str)) {
11989 return arr.concat(str.split('\\').join(''));
11990 } else {
11991 str = str.split('\\{').join('__LT_BRACE__');
11992 str = str.split('\\}').join('__RT_BRACE__');
11993 return map$1(braces(str, arr, opts), function(ele) {
11994 ele = ele.split('__LT_BRACE__').join('{');
11995 return ele.split('__RT_BRACE__').join('}');
11996 });
11997 }
11998}
11999
12000/**
12001 * Handle escaped dots: `{1\\.2}`
12002 */
12003
12004function escapeDots(str, arr, opts) {
12005 if (!/[^\\]\..+\\\./.test(str)) {
12006 return arr.concat(str.split('\\').join(''));
12007 } else {
12008 str = str.split('\\.').join('__ESC_DOT__');
12009 return map$1(braces(str, arr, opts), function(ele) {
12010 return ele.split('__ESC_DOT__').join('.');
12011 });
12012 }
12013}
12014
12015/**
12016 * Handle escaped dots: `{1\\.2}`
12017 */
12018
12019function escapePaths(str, arr, opts) {
12020 str = str.split('\/.').join('__ESC_PATH__');
12021 return map$1(braces(str, arr, opts), function(ele) {
12022 return ele.split('__ESC_PATH__').join('\/.');
12023 });
12024}
12025
12026/**
12027 * Handle escaped commas: `{a\\,b}`
12028 */
12029
12030function escapeCommas(str, arr, opts) {
12031 if (!/\w,/.test(str)) {
12032 return arr.concat(str.split('\\').join(''));
12033 } else {
12034 str = str.split('\\,').join('__ESC_COMMA__');
12035 return map$1(braces(str, arr, opts), function(ele) {
12036 return ele.split('__ESC_COMMA__').join(',');
12037 });
12038 }
12039}
12040
12041/**
12042 * Regex for common patterns
12043 */
12044
12045function patternRegex() {
12046 return /\${|( (?=[{,}])|(?=[{,}]) )|{}|{,}|\\,(?=.*[{}])|\/\.(?=.*[{}])|\\\.(?={)|\\{|\\}/;
12047}
12048
12049/**
12050 * Braces regex.
12051 */
12052
12053function braceRegex() {
12054 return /.*(\\?\{([^}]+)\})/;
12055}
12056
12057/**
12058 * es6 delimiter regex.
12059 */
12060
12061function es6Regex() {
12062 return /\$\{([^}]+)\}/;
12063}
12064
12065var braceRe;
12066var patternRe;
12067
12068/**
12069 * Faster alternative to `String.replace()` when the
12070 * index of the token to be replaces can't be supplied
12071 */
12072
12073function splice(str, token, replacement) {
12074 var i = str.indexOf(token);
12075 return str.substr(0, i) + replacement
12076 + str.substr(i + token.length);
12077}
12078
12079/**
12080 * Fast array map
12081 */
12082
12083function map$1(arr, fn) {
12084 if (arr == null) {
12085 return [];
12086 }
12087
12088 var len = arr.length;
12089 var res = new Array(len);
12090 var i = -1;
12091
12092 while (++i < len) {
12093 res[i] = fn(arr[i], i, arr);
12094 }
12095
12096 return res;
12097}
12098
12099/**
12100 * Fast array filter
12101 */
12102
12103function filter$1(arr, cb) {
12104 if (arr == null) return [];
12105 if (typeof cb !== 'function') {
12106 throw new TypeError('braces: filter expects a callback function.');
12107 }
12108
12109 var len = arr.length;
12110 var res = arr.slice();
12111 var i = 0;
12112
12113 while (len--) {
12114 if (!cb(arr[len], i++)) {
12115 res.splice(len, 1);
12116 }
12117 }
12118 return res;
12119}
12120
12121/*!
12122 * is-posix-bracket <https://github.com/jonschlinkert/is-posix-bracket>
12123 *
12124 * Copyright (c) 2015-2016, Jon Schlinkert.
12125 * Licensed under the MIT License.
12126 */
12127
12128var index$42 = function isPosixBracket(str) {
12129 return typeof str === 'string' && /\[([:.=+])(?:[^\[\]]|)+\1\]/.test(str);
12130};
12131
12132/**
12133 * POSIX character classes
12134 */
12135
12136var POSIX = {
12137 alnum: 'a-zA-Z0-9',
12138 alpha: 'a-zA-Z',
12139 blank: ' \\t',
12140 cntrl: '\\x00-\\x1F\\x7F',
12141 digit: '0-9',
12142 graph: '\\x21-\\x7E',
12143 lower: 'a-z',
12144 print: '\\x20-\\x7E',
12145 punct: '-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
12146 space: ' \\t\\r\\n\\v\\f',
12147 upper: 'A-Z',
12148 word: 'A-Za-z0-9_',
12149 xdigit: 'A-Fa-f0-9',
12150};
12151
12152/**
12153 * Expose `brackets`
12154 */
12155
12156var index$40 = brackets;
12157
12158function brackets(str) {
12159 if (!index$42(str)) {
12160 return str;
12161 }
12162
12163 var negated = false;
12164 if (str.indexOf('[^') !== -1) {
12165 negated = true;
12166 str = str.split('[^').join('[');
12167 }
12168 if (str.indexOf('[!') !== -1) {
12169 negated = true;
12170 str = str.split('[!').join('[');
12171 }
12172
12173 var a = str.split('[');
12174 var b = str.split(']');
12175 var imbalanced = a.length !== b.length;
12176
12177 var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/);
12178 var len = parts.length, i = 0;
12179 var end = '', beg = '';
12180 var res = [];
12181
12182 // start at the end (innermost) first
12183 while (len--) {
12184 var inner = parts[i++];
12185 if (inner === '^[!' || inner === '[!') {
12186 inner = '';
12187 negated = true;
12188 }
12189
12190 var prefix = negated ? '^' : '';
12191 var ch = POSIX[inner];
12192
12193 if (ch) {
12194 res.push('[' + prefix + ch + ']');
12195 } else if (inner) {
12196 if (/^\[?\w-\w\]?$/.test(inner)) {
12197 if (i === parts.length) {
12198 res.push('[' + prefix + inner);
12199 } else if (i === 1) {
12200 res.push(prefix + inner + ']');
12201 } else {
12202 res.push(prefix + inner);
12203 }
12204 } else {
12205 if (i === 1) {
12206 beg += inner;
12207 } else if (i === parts.length) {
12208 end += inner;
12209 } else {
12210 res.push('[' + prefix + inner + ']');
12211 }
12212 }
12213 }
12214 }
12215
12216 var result = res.join('|');
12217 var rlen = res.length || 1;
12218 if (rlen > 1) {
12219 result = '(?:' + result + ')';
12220 rlen = 1;
12221 }
12222 if (beg) {
12223 rlen++;
12224 if (beg.charAt(0) === '[') {
12225 if (imbalanced) {
12226 beg = '\\[' + beg.slice(1);
12227 } else {
12228 beg += ']';
12229 }
12230 }
12231 result = beg + result;
12232 }
12233 if (end) {
12234 rlen++;
12235 if (end.slice(-1) === ']') {
12236 if (imbalanced) {
12237 end = end.slice(0, end.length - 1) + '\\]';
12238 } else {
12239 end = '[' + end;
12240 }
12241 }
12242 result += end;
12243 }
12244
12245 if (rlen > 1) {
12246 result = result.split('][').join(']|[');
12247 if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) {
12248 result = '(?:' + result + ')';
12249 }
12250 }
12251
12252 result = result.replace(/\[+=|=\]+/g, '\\b');
12253 return result;
12254}
12255
12256brackets.makeRe = function(pattern) {
12257 try {
12258 return new RegExp(brackets(pattern));
12259 } catch (err) {}
12260};
12261
12262brackets.isMatch = function(str, pattern) {
12263 try {
12264 return brackets.makeRe(pattern).test(str);
12265 } catch (err) {
12266 return false;
12267 }
12268};
12269
12270brackets.match = function(arr, pattern) {
12271 var len = arr.length, i = 0;
12272 var res = arr.slice();
12273
12274 var re = brackets.makeRe(pattern);
12275 while (i < len) {
12276 var ele = arr[i++];
12277 if (!re.test(ele)) {
12278 continue;
12279 }
12280 res.splice(i, 1);
12281 }
12282 return res;
12283};
12284
12285/*!
12286 * is-extglob <https://github.com/jonschlinkert/is-extglob>
12287 *
12288 * Copyright (c) 2014-2015, Jon Schlinkert.
12289 * Licensed under the MIT License.
12290 */
12291
12292var index$46 = function isExtglob(str) {
12293 return typeof str === 'string'
12294 && /[@?!+*]\(/.test(str);
12295};
12296
12297/**
12298 * Module dependencies
12299 */
12300
12301
12302var re;
12303var cache$2 = {};
12304
12305/**
12306 * Expose `extglob`
12307 */
12308
12309var index$44 = extglob;
12310
12311/**
12312 * Convert the given extglob `string` to a regex-compatible
12313 * string.
12314 *
12315 * ```js
12316 * var extglob = require('extglob');
12317 * extglob('!(a?(b))');
12318 * //=> '(?!a(?:b)?)[^/]*?'
12319 * ```
12320 *
12321 * @param {String} `str` The string to convert.
12322 * @param {Object} `options`
12323 * @option {Boolean} [options] `esc` If `false` special characters will not be escaped. Defaults to `true`.
12324 * @option {Boolean} [options] `regex` If `true` a regular expression is returned instead of a string.
12325 * @return {String}
12326 * @api public
12327 */
12328
12329
12330function extglob(str, opts) {
12331 opts = opts || {};
12332 var o = {}, i = 0;
12333
12334 // fix common character reversals
12335 // '*!(.js)' => '*.!(js)'
12336 str = str.replace(/!\(([^\w*()])/g, '$1!(');
12337
12338 // support file extension negation
12339 str = str.replace(/([*\/])\.!\([*]\)/g, function (m, ch) {
12340 if (ch === '/') {
12341 return escape('\\/[^.]+');
12342 }
12343 return escape('[^.]+');
12344 });
12345
12346 // create a unique key for caching by
12347 // combining the string and options
12348 var key = str
12349 + String(!!opts.regex)
12350 + String(!!opts.contains)
12351 + String(!!opts.escape);
12352
12353 if (cache$2.hasOwnProperty(key)) {
12354 return cache$2[key];
12355 }
12356
12357 if (!(re instanceof RegExp)) {
12358 re = regex();
12359 }
12360
12361 opts.negate = false;
12362 var m;
12363
12364 while (m = re.exec(str)) {
12365 var prefix = m[1];
12366 var inner = m[3];
12367 if (prefix === '!') {
12368 opts.negate = true;
12369 }
12370
12371 var id = '__EXTGLOB_' + (i++) + '__';
12372 // use the prefix of the _last_ (outtermost) pattern
12373 o[id] = wrap$2(inner, prefix, opts.escape);
12374 str = str.split(m[0]).join(id);
12375 }
12376
12377 var keys = Object.keys(o);
12378 var len = keys.length;
12379
12380 // we have to loop again to allow us to convert
12381 // patterns in reverse order (starting with the
12382 // innermost/last pattern first)
12383 while (len--) {
12384 var prop = keys[len];
12385 str = str.split(prop).join(o[prop]);
12386 }
12387
12388 var result = opts.regex
12389 ? toRegex$1(str, opts.contains, opts.negate)
12390 : str;
12391
12392 result = result.split('.').join('\\.');
12393
12394 // cache the result and return it
12395 return (cache$2[key] = result);
12396}
12397
12398/**
12399 * Convert `string` to a regex string.
12400 *
12401 * @param {String} `str`
12402 * @param {String} `prefix` Character that determines how to wrap the string.
12403 * @param {Boolean} `esc` If `false` special characters will not be escaped. Defaults to `true`.
12404 * @return {String}
12405 */
12406
12407function wrap$2(inner, prefix, esc) {
12408 if (esc) inner = escape(inner);
12409
12410 switch (prefix) {
12411 case '!':
12412 return '(?!' + inner + ')[^/]' + (esc ? '%%%~' : '*?');
12413 case '@':
12414 return '(?:' + inner + ')';
12415 case '+':
12416 return '(?:' + inner + ')+';
12417 case '*':
12418 return '(?:' + inner + ')' + (esc ? '%%' : '*')
12419 case '?':
12420 return '(?:' + inner + '|)';
12421 default:
12422 return inner;
12423 }
12424}
12425
12426function escape(str) {
12427 str = str.split('*').join('[^/]%%%~');
12428 str = str.split('.').join('\\.');
12429 return str;
12430}
12431
12432/**
12433 * extglob regex.
12434 */
12435
12436function regex() {
12437 return /(\\?[@?!+*$]\\?)(\(([^()]*?)\))/;
12438}
12439
12440/**
12441 * Negation regex
12442 */
12443
12444function negate(str) {
12445 return '(?!^' + str + ').*$';
12446}
12447
12448/**
12449 * Create the regex to do the matching. If
12450 * the leading character in the `pattern` is `!`
12451 * a negation regex is returned.
12452 *
12453 * @param {String} `pattern`
12454 * @param {Boolean} `contains` Allow loose matching.
12455 * @param {Boolean} `isNegated` True if the pattern is a negation pattern.
12456 */
12457
12458function toRegex$1(pattern, contains, isNegated) {
12459 var prefix = contains ? '^' : '';
12460 var after = contains ? '$' : '';
12461 pattern = ('(?:' + pattern + ')' + after);
12462 if (isNegated) {
12463 pattern = prefix + negate(pattern);
12464 }
12465 return new RegExp(prefix + pattern);
12466}
12467
12468/*!
12469 * is-glob <https://github.com/jonschlinkert/is-glob>
12470 *
12471 * Copyright (c) 2014-2015, Jon Schlinkert.
12472 * Licensed under the MIT License.
12473 */
12474
12475
12476
12477var index$48 = function isGlob(str) {
12478 return typeof str === 'string'
12479 && (/[*!?{}(|)[\]]/.test(str)
12480 || index$46(str));
12481};
12482
12483var isWin = process.platform === 'win32';
12484
12485var index$52 = function (str) {
12486 while (endsInSeparator(str)) {
12487 str = str.slice(0, -1);
12488 }
12489 return str;
12490};
12491
12492function endsInSeparator(str) {
12493 var last = str[str.length - 1];
12494 return str.length > 1 && (last === '/' || (isWin && last === '\\'));
12495}
12496
12497/*!
12498 * normalize-path <https://github.com/jonschlinkert/normalize-path>
12499 *
12500 * Copyright (c) 2014-2017, Jon Schlinkert.
12501 * Released under the MIT License.
12502 */
12503
12504
12505
12506var index$50 = function normalizePath(str, stripTrailing) {
12507 if (typeof str !== 'string') {
12508 throw new TypeError('expected a string');
12509 }
12510 str = str.replace(/[\\\/]+/g, '/');
12511 if (stripTrailing !== false) {
12512 str = index$52(str);
12513 }
12514 return str;
12515};
12516
12517/*!
12518 * is-extendable <https://github.com/jonschlinkert/is-extendable>
12519 *
12520 * Copyright (c) 2015, Jon Schlinkert.
12521 * Licensed under the MIT License.
12522 */
12523
12524var index$56 = function isExtendable(val) {
12525 return typeof val !== 'undefined' && val !== null
12526 && (typeof val === 'object' || typeof val === 'function');
12527};
12528
12529/*!
12530 * for-in <https://github.com/jonschlinkert/for-in>
12531 *
12532 * Copyright (c) 2014-2017, Jon Schlinkert.
12533 * Released under the MIT License.
12534 */
12535
12536var index$60 = function forIn(obj, fn, thisArg) {
12537 for (var key in obj) {
12538 if (fn.call(thisArg, obj[key], key, obj) === false) {
12539 break;
12540 }
12541 }
12542};
12543
12544var hasOwn = Object.prototype.hasOwnProperty;
12545
12546var index$58 = function forOwn(obj, fn, thisArg) {
12547 index$60(obj, function(val, key) {
12548 if (hasOwn.call(obj, key)) {
12549 return fn.call(thisArg, obj[key], key, obj);
12550 }
12551 });
12552};
12553
12554var index$54 = function omit(obj, keys) {
12555 if (!index$56(obj)) return {};
12556
12557 keys = [].concat.apply([], [].slice.call(arguments, 1));
12558 var last = keys[keys.length - 1];
12559 var res = {}, fn;
12560
12561 if (typeof last === 'function') {
12562 fn = keys.pop();
12563 }
12564
12565 var isFunction = typeof fn === 'function';
12566 if (!keys.length && !isFunction) {
12567 return obj;
12568 }
12569
12570 index$58(obj, function(value, key) {
12571 if (keys.indexOf(key) === -1) {
12572
12573 if (!isFunction) {
12574 res[key] = value;
12575 } else if (fn(value, key, obj)) {
12576 res[key] = value;
12577 }
12578 }
12579 });
12580 return res;
12581};
12582
12583var index$66 = function globParent(str) {
12584 str += 'a'; // preserves full path in case of trailing path separator
12585 do {str = path.dirname(str);} while (index$48(str));
12586 return str;
12587};
12588
12589var index$64 = function globBase(pattern) {
12590 if (typeof pattern !== 'string') {
12591 throw new TypeError('glob-base expects a string.');
12592 }
12593
12594 var res = {};
12595 res.base = index$66(pattern);
12596 res.isGlob = index$48(pattern);
12597
12598 if (res.base !== '.') {
12599 res.glob = pattern.substr(res.base.length);
12600 if (res.glob.charAt(0) === '/') {
12601 res.glob = res.glob.substr(1);
12602 }
12603 } else {
12604 res.glob = pattern;
12605 }
12606
12607 if (!res.isGlob) {
12608 res.base = dirname$1(pattern);
12609 res.glob = res.base !== '.'
12610 ? pattern.substr(res.base.length)
12611 : pattern;
12612 }
12613
12614 if (res.glob.substr(0, 2) === './') {
12615 res.glob = res.glob.substr(2);
12616 }
12617 if (res.glob.charAt(0) === '/') {
12618 res.glob = res.glob.substr(1);
12619 }
12620 return res;
12621};
12622
12623function dirname$1(glob) {
12624 if (glob.slice(-1) === '/') return glob;
12625 return path.dirname(glob);
12626}
12627
12628/*!
12629 * is-dotfile <https://github.com/jonschlinkert/is-dotfile>
12630 *
12631 * Copyright (c) 2015-2017, Jon Schlinkert.
12632 * Released under the MIT License.
12633 */
12634
12635var index$68 = function(str) {
12636 if (str.charCodeAt(0) === 46 /* . */ && str.indexOf('/', 1) === -1) {
12637 return true;
12638 }
12639 var slash = str.lastIndexOf('/');
12640 return slash !== -1 ? str.charCodeAt(slash + 1) === 46 /* . */ : false;
12641};
12642
12643var index$62 = createCommonjsModule(function (module) {
12644/*!
12645 * parse-glob <https://github.com/jonschlinkert/parse-glob>
12646 *
12647 * Copyright (c) 2015, Jon Schlinkert.
12648 * Licensed under the MIT License.
12649 */
12650
12651'use strict';
12652
12653
12654
12655
12656
12657
12658/**
12659 * Expose `cache`
12660 */
12661
12662var cache = module.exports.cache = {};
12663
12664/**
12665 * Parse a glob pattern into tokens.
12666 *
12667 * When no paths or '**' are in the glob, we use a
12668 * different strategy for parsing the filename, since
12669 * file names can contain braces and other difficult
12670 * patterns. such as:
12671 *
12672 * - `*.{a,b}`
12673 * - `(**|*.js)`
12674 */
12675
12676module.exports = function parseGlob(glob) {
12677 if (cache.hasOwnProperty(glob)) {
12678 return cache[glob];
12679 }
12680
12681 var tok = {};
12682 tok.orig = glob;
12683 tok.is = {};
12684
12685 // unescape dots and slashes in braces/brackets
12686 glob = escape(glob);
12687
12688 var parsed = index$64(glob);
12689 tok.is.glob = parsed.isGlob;
12690
12691 tok.glob = parsed.glob;
12692 tok.base = parsed.base;
12693 var segs = /([^\/]*)$/.exec(glob);
12694
12695 tok.path = {};
12696 tok.path.dirname = '';
12697 tok.path.basename = segs[1] || '';
12698 tok.path.dirname = glob.split(tok.path.basename).join('') || '';
12699 var basename$$1 = (tok.path.basename || '').split('.') || '';
12700 tok.path.filename = basename$$1[0] || '';
12701 tok.path.extname = basename$$1.slice(1).join('.') || '';
12702 tok.path.ext = '';
12703
12704 if (index$48(tok.path.dirname) && !tok.path.basename) {
12705 if (!/\/$/.test(tok.glob)) {
12706 tok.path.basename = tok.glob;
12707 }
12708 tok.path.dirname = tok.base;
12709 }
12710
12711 if (glob.indexOf('/') === -1 && !tok.is.globstar) {
12712 tok.path.dirname = '';
12713 tok.path.basename = tok.orig;
12714 }
12715
12716 var dot = tok.path.basename.indexOf('.');
12717 if (dot !== -1) {
12718 tok.path.filename = tok.path.basename.slice(0, dot);
12719 tok.path.extname = tok.path.basename.slice(dot);
12720 }
12721
12722 if (tok.path.extname.charAt(0) === '.') {
12723 var exts = tok.path.extname.split('.');
12724 tok.path.ext = exts[exts.length - 1];
12725 }
12726
12727 // unescape dots and slashes in braces/brackets
12728 tok.glob = unescape(tok.glob);
12729 tok.path.dirname = unescape(tok.path.dirname);
12730 tok.path.basename = unescape(tok.path.basename);
12731 tok.path.filename = unescape(tok.path.filename);
12732 tok.path.extname = unescape(tok.path.extname);
12733
12734 // Booleans
12735 var is = (glob && tok.is.glob);
12736 tok.is.negated = glob && glob.charAt(0) === '!';
12737 tok.is.extglob = glob && index$46(glob);
12738 tok.is.braces = has(is, glob, '{');
12739 tok.is.brackets = has(is, glob, '[:');
12740 tok.is.globstar = has(is, glob, '**');
12741 tok.is.dotfile = index$68(tok.path.basename) || index$68(tok.path.filename);
12742 tok.is.dotdir = dotdir(tok.path.dirname);
12743 return (cache[glob] = tok);
12744};
12745
12746/**
12747 * Returns true if the glob matches dot-directories.
12748 *
12749 * @param {Object} `tok` The tokens object
12750 * @param {Object} `path` The path object
12751 * @return {Object}
12752 */
12753
12754function dotdir(base) {
12755 if (base.indexOf('/.') !== -1) {
12756 return true;
12757 }
12758 if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
12759 return true;
12760 }
12761 return false;
12762}
12763
12764/**
12765 * Returns true if the pattern has the given `ch`aracter(s)
12766 *
12767 * @param {Object} `glob` The glob pattern.
12768 * @param {Object} `ch` The character to test for
12769 * @return {Object}
12770 */
12771
12772function has(is, glob, ch) {
12773 return is && glob.indexOf(ch) !== -1;
12774}
12775
12776/**
12777 * Escape/unescape utils
12778 */
12779
12780function escape(str) {
12781 var re = /\{([^{}]*?)}|\(([^()]*?)\)|\[([^\[\]]*?)\]/g;
12782 return str.replace(re, function (outter, braces, parens, brackets) {
12783 var inner = braces || parens || brackets;
12784 if (!inner) { return outter; }
12785 return outter.split(inner).join(esc(inner));
12786 });
12787}
12788
12789function esc(str) {
12790 str = str.split('/').join('__SLASH__');
12791 str = str.split('.').join('__DOT__');
12792 return str;
12793}
12794
12795function unescape(str) {
12796 str = str.split('__SLASH__').join('/');
12797 str = str.split('__DOT__').join('.');
12798 return str;
12799}
12800});
12801
12802/*!
12803 * is-primitive <https://github.com/jonschlinkert/is-primitive>
12804 *
12805 * Copyright (c) 2014-2015, Jon Schlinkert.
12806 * Licensed under the MIT License.
12807 */
12808
12809// see http://jsperf.com/testing-value-is-primitive/7
12810var index$72 = function isPrimitive(value) {
12811 return value == null || (typeof value !== 'function' && typeof value !== 'object');
12812};
12813
12814var index$74 = function isEqual(a, b) {
12815 if (!a && !b) { return true; }
12816 if (!a && b || a && !b) { return false; }
12817
12818 var numKeysA = 0, numKeysB = 0, key;
12819 for (key in b) {
12820 numKeysB++;
12821 if (!index$72(b[key]) || !a.hasOwnProperty(key) || (a[key] !== b[key])) {
12822 return false;
12823 }
12824 }
12825 for (key in a) {
12826 numKeysA++;
12827 }
12828 return numKeysA === numKeysB;
12829};
12830
12831var basic = {};
12832var cache$3 = {};
12833
12834/**
12835 * Expose `regexCache`
12836 */
12837
12838var index$70 = regexCache;
12839
12840/**
12841 * Memoize the results of a call to the new RegExp constructor.
12842 *
12843 * @param {Function} fn [description]
12844 * @param {String} str [description]
12845 * @param {Options} options [description]
12846 * @param {Boolean} nocompare [description]
12847 * @return {RegExp}
12848 */
12849
12850function regexCache(fn, str, opts) {
12851 var key = '_default_', regex, cached;
12852
12853 if (!str && !opts) {
12854 if (typeof fn !== 'function') {
12855 return fn;
12856 }
12857 return basic[key] || (basic[key] = fn(str));
12858 }
12859
12860 var isString = typeof str === 'string';
12861 if (isString) {
12862 if (!opts) {
12863 return basic[str] || (basic[str] = fn(str));
12864 }
12865 key = str;
12866 } else {
12867 opts = str;
12868 }
12869
12870 cached = cache$3[key];
12871 if (cached && index$74(cached.opts, opts)) {
12872 return cached.regex;
12873 }
12874
12875 memo(key, opts, (regex = fn(str, opts)));
12876 return regex;
12877}
12878
12879function memo(key, opts, regex) {
12880 cache$3[key] = {regex: regex, opts: opts};
12881}
12882
12883/**
12884 * Expose `cache`
12885 */
12886
12887var cache_1 = cache$3;
12888var basic_1 = basic;
12889
12890index$70.cache = cache_1;
12891index$70.basic = basic_1;
12892
12893var utils_1 = createCommonjsModule(function (module) {
12894'use strict';
12895
12896var win32 = process && process.platform === 'win32';
12897
12898
12899var utils = module.exports;
12900
12901/**
12902 * Module dependencies
12903 */
12904
12905utils.diff = index$4;
12906utils.unique = index$8;
12907utils.braces = index$10;
12908utils.brackets = index$40;
12909utils.extglob = index$44;
12910utils.isExtglob = index$46;
12911utils.isGlob = index$48;
12912utils.typeOf = index$22;
12913utils.normalize = index$50;
12914utils.omit = index$54;
12915utils.parseGlob = index$62;
12916utils.cache = index$70;
12917
12918/**
12919 * Get the filename of a filepath
12920 *
12921 * @param {String} `string`
12922 * @return {String}
12923 */
12924
12925utils.filename = function filename(fp) {
12926 var seg = fp.match(index$2());
12927 return seg && seg[0];
12928};
12929
12930/**
12931 * Returns a function that returns true if the given
12932 * pattern is the same as a given `filepath`
12933 *
12934 * @param {String} `pattern`
12935 * @return {Function}
12936 */
12937
12938utils.isPath = function isPath(pattern, opts) {
12939 opts = opts || {};
12940 return function(fp) {
12941 var unixified = utils.unixify(fp, opts);
12942 if(opts.nocase){
12943 return pattern.toLowerCase() === unixified.toLowerCase();
12944 }
12945 return pattern === unixified;
12946 };
12947};
12948
12949/**
12950 * Returns a function that returns true if the given
12951 * pattern contains a `filepath`
12952 *
12953 * @param {String} `pattern`
12954 * @return {Function}
12955 */
12956
12957utils.hasPath = function hasPath(pattern, opts) {
12958 return function(fp) {
12959 return utils.unixify(pattern, opts).indexOf(fp) !== -1;
12960 };
12961};
12962
12963/**
12964 * Returns a function that returns true if the given
12965 * pattern matches or contains a `filepath`
12966 *
12967 * @param {String} `pattern`
12968 * @return {Function}
12969 */
12970
12971utils.matchPath = function matchPath(pattern, opts) {
12972 var fn = (opts && opts.contains)
12973 ? utils.hasPath(pattern, opts)
12974 : utils.isPath(pattern, opts);
12975 return fn;
12976};
12977
12978/**
12979 * Returns a function that returns true if the given
12980 * regex matches the `filename` of a file path.
12981 *
12982 * @param {RegExp} `re`
12983 * @return {Boolean}
12984 */
12985
12986utils.hasFilename = function hasFilename(re) {
12987 return function(fp) {
12988 var name = utils.filename(fp);
12989 return name && re.test(name);
12990 };
12991};
12992
12993/**
12994 * Coerce `val` to an array
12995 *
12996 * @param {*} val
12997 * @return {Array}
12998 */
12999
13000utils.arrayify = function arrayify(val) {
13001 return !Array.isArray(val)
13002 ? [val]
13003 : val;
13004};
13005
13006/**
13007 * Normalize all slashes in a file path or glob pattern to
13008 * forward slashes.
13009 */
13010
13011utils.unixify = function unixify(fp, opts) {
13012 if (opts && opts.unixify === false) return fp;
13013 if (opts && opts.unixify === true || win32 || path.sep === '\\') {
13014 return utils.normalize(fp, false);
13015 }
13016 if (opts && opts.unescape === true) {
13017 return fp ? fp.toString().replace(/\\(\w)/g, '$1') : '';
13018 }
13019 return fp;
13020};
13021
13022/**
13023 * Escape/unescape utils
13024 */
13025
13026utils.escapePath = function escapePath(fp) {
13027 return fp.replace(/[\\.]/g, '\\$&');
13028};
13029
13030utils.unescapeGlob = function unescapeGlob(fp) {
13031 return fp.replace(/[\\"']/g, '');
13032};
13033
13034utils.escapeRe = function escapeRe(str) {
13035 return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&');
13036};
13037
13038/**
13039 * Expose `utils`
13040 */
13041
13042module.exports = utils;
13043});
13044
13045var chars = {};
13046var unesc;
13047var temp;
13048
13049function reverse(object, prepender) {
13050 return Object.keys(object).reduce(function(reversed, key) {
13051 var newKey = prepender ? prepender + key : key; // Optionally prepend a string to key.
13052 reversed[object[key]] = newKey; // Swap key and value.
13053 return reversed; // Return the result.
13054 }, {});
13055}
13056
13057/**
13058 * Regex for common characters
13059 */
13060
13061chars.escapeRegex = {
13062 '?': /\?/g,
13063 '@': /\@/g,
13064 '!': /\!/g,
13065 '+': /\+/g,
13066 '*': /\*/g,
13067 '(': /\(/g,
13068 ')': /\)/g,
13069 '[': /\[/g,
13070 ']': /\]/g
13071};
13072
13073/**
13074 * Escape characters
13075 */
13076
13077chars.ESC = {
13078 '?': '__UNESC_QMRK__',
13079 '@': '__UNESC_AMPE__',
13080 '!': '__UNESC_EXCL__',
13081 '+': '__UNESC_PLUS__',
13082 '*': '__UNESC_STAR__',
13083 ',': '__UNESC_COMMA__',
13084 '(': '__UNESC_LTPAREN__',
13085 ')': '__UNESC_RTPAREN__',
13086 '[': '__UNESC_LTBRACK__',
13087 ']': '__UNESC_RTBRACK__'
13088};
13089
13090/**
13091 * Unescape characters
13092 */
13093
13094chars.UNESC = unesc || (unesc = reverse(chars.ESC, '\\'));
13095
13096chars.ESC_TEMP = {
13097 '?': '__TEMP_QMRK__',
13098 '@': '__TEMP_AMPE__',
13099 '!': '__TEMP_EXCL__',
13100 '*': '__TEMP_STAR__',
13101 '+': '__TEMP_PLUS__',
13102 ',': '__TEMP_COMMA__',
13103 '(': '__TEMP_LTPAREN__',
13104 ')': '__TEMP_RTPAREN__',
13105 '[': '__TEMP_LTBRACK__',
13106 ']': '__TEMP_RTBRACK__'
13107};
13108
13109chars.TEMP = temp || (temp = reverse(chars.ESC_TEMP));
13110
13111var chars_1 = chars;
13112
13113var glob = createCommonjsModule(function (module) {
13114'use strict';
13115
13116
13117
13118
13119/**
13120 * Expose `Glob`
13121 */
13122
13123var Glob = module.exports = function Glob(pattern, options) {
13124 if (!(this instanceof Glob)) {
13125 return new Glob(pattern, options);
13126 }
13127 this.options = options || {};
13128 this.pattern = pattern;
13129 this.history = [];
13130 this.tokens = {};
13131 this.init(pattern);
13132};
13133
13134/**
13135 * Initialize defaults
13136 */
13137
13138Glob.prototype.init = function(pattern) {
13139 this.orig = pattern;
13140 this.negated = this.isNegated();
13141 this.options.track = this.options.track || false;
13142 this.options.makeRe = true;
13143};
13144
13145/**
13146 * Push a change into `glob.history`. Useful
13147 * for debugging.
13148 */
13149
13150Glob.prototype.track = function(msg) {
13151 if (this.options.track) {
13152 this.history.push({msg: msg, pattern: this.pattern});
13153 }
13154};
13155
13156/**
13157 * Return true if `glob.pattern` was negated
13158 * with `!`, also remove the `!` from the pattern.
13159 *
13160 * @return {Boolean}
13161 */
13162
13163Glob.prototype.isNegated = function() {
13164 if (this.pattern.charCodeAt(0) === 33 /* '!' */) {
13165 this.pattern = this.pattern.slice(1);
13166 return true;
13167 }
13168 return false;
13169};
13170
13171/**
13172 * Expand braces in the given glob pattern.
13173 *
13174 * We only need to use the [braces] lib when
13175 * patterns are nested.
13176 */
13177
13178Glob.prototype.braces = function() {
13179 if (this.options.nobraces !== true && this.options.nobrace !== true) {
13180 // naive/fast check for imbalanced characters
13181 var a = this.pattern.match(/[\{\(\[]/g);
13182 var b = this.pattern.match(/[\}\)\]]/g);
13183
13184 // if imbalanced, don't optimize the pattern
13185 if (a && b && (a.length !== b.length)) {
13186 this.options.makeRe = false;
13187 }
13188
13189 // expand brace patterns and join the resulting array
13190 var expanded = utils_1.braces(this.pattern, this.options);
13191 this.pattern = expanded.join('|');
13192 }
13193};
13194
13195/**
13196 * Expand bracket expressions in `glob.pattern`
13197 */
13198
13199Glob.prototype.brackets = function() {
13200 if (this.options.nobrackets !== true) {
13201 this.pattern = utils_1.brackets(this.pattern);
13202 }
13203};
13204
13205/**
13206 * Expand bracket expressions in `glob.pattern`
13207 */
13208
13209Glob.prototype.extglob = function() {
13210 if (this.options.noextglob === true) return;
13211
13212 if (utils_1.isExtglob(this.pattern)) {
13213 this.pattern = utils_1.extglob(this.pattern, {escape: true});
13214 }
13215};
13216
13217/**
13218 * Parse the given pattern
13219 */
13220
13221Glob.prototype.parse = function(pattern) {
13222 this.tokens = utils_1.parseGlob(pattern || this.pattern, true);
13223 return this.tokens;
13224};
13225
13226/**
13227 * Replace `a` with `b`. Also tracks the change before and
13228 * after each replacement. This is disabled by default, but
13229 * can be enabled by setting `options.track` to true.
13230 *
13231 * Also, when the pattern is a string, `.split()` is used,
13232 * because it's much faster than replace.
13233 *
13234 * @param {RegExp|String} `a`
13235 * @param {String} `b`
13236 * @param {Boolean} `escape` When `true`, escapes `*` and `?` in the replacement.
13237 * @return {String}
13238 */
13239
13240Glob.prototype._replace = function(a, b, escape) {
13241 this.track('before (find): "' + a + '" (replace with): "' + b + '"');
13242 if (escape) b = esc(b);
13243 if (a && b && typeof a === 'string') {
13244 this.pattern = this.pattern.split(a).join(b);
13245 } else {
13246 this.pattern = this.pattern.replace(a, b);
13247 }
13248 this.track('after');
13249};
13250
13251/**
13252 * Escape special characters in the given string.
13253 *
13254 * @param {String} `str` Glob pattern
13255 * @return {String}
13256 */
13257
13258Glob.prototype.escape = function(str) {
13259 this.track('before escape: ');
13260 var re = /["\\](['"]?[^"'\\]['"]?)/g;
13261
13262 this.pattern = str.replace(re, function($0, $1) {
13263 var o = chars_1.ESC;
13264 var ch = o && o[$1];
13265 if (ch) {
13266 return ch;
13267 }
13268 if (/[a-z]/i.test($0)) {
13269 return $0.split('\\').join('');
13270 }
13271 return $0;
13272 });
13273
13274 this.track('after escape: ');
13275};
13276
13277/**
13278 * Unescape special characters in the given string.
13279 *
13280 * @param {String} `str`
13281 * @return {String}
13282 */
13283
13284Glob.prototype.unescape = function(str) {
13285 var re = /__([A-Z]+)_([A-Z]+)__/g;
13286 this.pattern = str.replace(re, function($0, $1) {
13287 return chars_1[$1][$0];
13288 });
13289 this.pattern = unesc(this.pattern);
13290};
13291
13292/**
13293 * Escape/unescape utils
13294 */
13295
13296function esc(str) {
13297 str = str.split('?').join('%~');
13298 str = str.split('*').join('%%');
13299 return str;
13300}
13301
13302function unesc(str) {
13303 str = str.split('%~').join('?');
13304 str = str.split('%%').join('*');
13305 return str;
13306}
13307});
13308
13309/**
13310 * Expose `expand`
13311 */
13312
13313var expand_1 = expand;
13314
13315/**
13316 * Expand a glob pattern to resolve braces and
13317 * similar patterns before converting to regex.
13318 *
13319 * @param {String|Array} `pattern`
13320 * @param {Array} `files`
13321 * @param {Options} `opts`
13322 * @return {Array}
13323 */
13324
13325function expand(pattern, options) {
13326 if (typeof pattern !== 'string') {
13327 throw new TypeError('micromatch.expand(): argument should be a string.');
13328 }
13329
13330 var glob$$1 = new glob(pattern, options || {});
13331 var opts = glob$$1.options;
13332
13333 if (!utils_1.isGlob(pattern)) {
13334 glob$$1.pattern = glob$$1.pattern.replace(/([\/.])/g, '\\$1');
13335 return glob$$1;
13336 }
13337
13338 glob$$1.pattern = glob$$1.pattern.replace(/(\+)(?!\()/g, '\\$1');
13339 glob$$1.pattern = glob$$1.pattern.split('$').join('\\$');
13340
13341 if (typeof opts.braces !== 'boolean' && typeof opts.nobraces !== 'boolean') {
13342 opts.braces = true;
13343 }
13344
13345 if (glob$$1.pattern === '.*') {
13346 return {
13347 pattern: '\\.' + star,
13348 tokens: tok,
13349 options: opts
13350 };
13351 }
13352
13353 if (glob$$1.pattern === '*') {
13354 return {
13355 pattern: oneStar(opts.dot),
13356 tokens: tok,
13357 options: opts
13358 };
13359 }
13360
13361 // parse the glob pattern into tokens
13362 glob$$1.parse();
13363 var tok = glob$$1.tokens;
13364 tok.is.negated = opts.negated;
13365
13366 // dotfile handling
13367 if ((opts.dotfiles === true || tok.is.dotfile) && opts.dot !== false) {
13368 opts.dotfiles = true;
13369 opts.dot = true;
13370 }
13371
13372 if ((opts.dotdirs === true || tok.is.dotdir) && opts.dot !== false) {
13373 opts.dotdirs = true;
13374 opts.dot = true;
13375 }
13376
13377 // check for braces with a dotfile pattern
13378 if (/[{,]\./.test(glob$$1.pattern)) {
13379 opts.makeRe = false;
13380 opts.dot = true;
13381 }
13382
13383 if (opts.nonegate !== true) {
13384 opts.negated = glob$$1.negated;
13385 }
13386
13387 // if the leading character is a dot or a slash, escape it
13388 if (glob$$1.pattern.charAt(0) === '.' && glob$$1.pattern.charAt(1) !== '/') {
13389 glob$$1.pattern = '\\' + glob$$1.pattern;
13390 }
13391
13392 /**
13393 * Extended globs
13394 */
13395
13396 // expand braces, e.g `{1..5}`
13397 glob$$1.track('before braces');
13398 if (tok.is.braces) {
13399 glob$$1.braces();
13400 }
13401 glob$$1.track('after braces');
13402
13403 // expand extglobs, e.g `foo/!(a|b)`
13404 glob$$1.track('before extglob');
13405 if (tok.is.extglob) {
13406 glob$$1.extglob();
13407 }
13408 glob$$1.track('after extglob');
13409
13410 // expand brackets, e.g `[[:alpha:]]`
13411 glob$$1.track('before brackets');
13412 if (tok.is.brackets) {
13413 glob$$1.brackets();
13414 }
13415 glob$$1.track('after brackets');
13416
13417 // special patterns
13418 glob$$1._replace('[!', '[^');
13419 glob$$1._replace('(?', '(%~');
13420 glob$$1._replace(/\[\]/, '\\[\\]');
13421 glob$$1._replace('/[', '/' + (opts.dot ? dotfiles : nodot) + '[', true);
13422 glob$$1._replace('/?', '/' + (opts.dot ? dotfiles : nodot) + '[^/]', true);
13423 glob$$1._replace('/.', '/(?=.)\\.', true);
13424
13425 // windows drives
13426 glob$$1._replace(/^(\w):([\\\/]+?)/gi, '(?=.)$1:$2', true);
13427
13428 // negate slashes in exclusion ranges
13429 if (glob$$1.pattern.indexOf('[^') !== -1) {
13430 glob$$1.pattern = negateSlash(glob$$1.pattern);
13431 }
13432
13433 if (opts.globstar !== false && glob$$1.pattern === '**') {
13434 glob$$1.pattern = globstar(opts.dot);
13435
13436 } else {
13437 glob$$1.pattern = balance(glob$$1.pattern, '[', ']');
13438 glob$$1.escape(glob$$1.pattern);
13439
13440 // if the pattern has `**`
13441 if (tok.is.globstar) {
13442 glob$$1.pattern = collapse(glob$$1.pattern, '/**');
13443 glob$$1.pattern = collapse(glob$$1.pattern, '**/');
13444 glob$$1._replace('/**/', '(?:/' + globstar(opts.dot) + '/|/)', true);
13445 glob$$1._replace(/\*{2,}/g, '**');
13446
13447 // 'foo/*'
13448 glob$$1._replace(/(\w+)\*(?!\/)/g, '$1[^/]*?', true);
13449 glob$$1._replace(/\*\*\/\*(\w)/g, globstar(opts.dot) + '\\/' + (opts.dot ? dotfiles : nodot) + '[^/]*?$1', true);
13450
13451 if (opts.dot !== true) {
13452 glob$$1._replace(/\*\*\/(.)/g, '(?:**\\/|)$1');
13453 }
13454
13455 // 'foo/**' or '{**,*}', but not 'foo**'
13456 if (tok.path.dirname !== '' || /,\*\*|\*\*,/.test(glob$$1.orig)) {
13457 glob$$1._replace('**', globstar(opts.dot), true);
13458 }
13459 }
13460
13461 // ends with /*
13462 glob$$1._replace(/\/\*$/, '\\/' + oneStar(opts.dot), true);
13463 // ends with *, no slashes
13464 glob$$1._replace(/(?!\/)\*$/, star, true);
13465 // has 'n*.' (partial wildcard w/ file extension)
13466 glob$$1._replace(/([^\/]+)\*/, '$1' + oneStar(true), true);
13467 // has '*'
13468 glob$$1._replace('*', oneStar(opts.dot), true);
13469 glob$$1._replace('?.', '?\\.', true);
13470 glob$$1._replace('?:', '?:', true);
13471
13472 glob$$1._replace(/\?+/g, function(match) {
13473 var len = match.length;
13474 if (len === 1) {
13475 return qmark;
13476 }
13477 return qmark + '{' + len + '}';
13478 });
13479
13480 // escape '.abc' => '\\.abc'
13481 glob$$1._replace(/\.([*\w]+)/g, '\\.$1');
13482 // fix '[^\\\\/]'
13483 glob$$1._replace(/\[\^[\\\/]+\]/g, qmark);
13484 // '///' => '\/'
13485 glob$$1._replace(/\/+/g, '\\/');
13486 // '\\\\\\' => '\\'
13487 glob$$1._replace(/\\{2,}/g, '\\');
13488 }
13489
13490 // unescape previously escaped patterns
13491 glob$$1.unescape(glob$$1.pattern);
13492 glob$$1._replace('__UNESC_STAR__', '*');
13493
13494 // escape dots that follow qmarks
13495 glob$$1._replace('?.', '?\\.');
13496
13497 // remove unnecessary slashes in character classes
13498 glob$$1._replace('[^\\/]', qmark);
13499
13500 if (glob$$1.pattern.length > 1) {
13501 if (/^[\[?*]/.test(glob$$1.pattern)) {
13502 // only prepend the string if we don't want to match dotfiles
13503 glob$$1.pattern = (opts.dot ? dotfiles : nodot) + glob$$1.pattern;
13504 }
13505 }
13506
13507 return glob$$1;
13508}
13509
13510/**
13511 * Collapse repeated character sequences.
13512 *
13513 * ```js
13514 * collapse('a/../../../b', '../');
13515 * //=> 'a/../b'
13516 * ```
13517 *
13518 * @param {String} `str`
13519 * @param {String} `ch` Character sequence to collapse
13520 * @return {String}
13521 */
13522
13523function collapse(str, ch) {
13524 var res = str.split(ch);
13525 var isFirst = res[0] === '';
13526 var isLast = res[res.length - 1] === '';
13527 res = res.filter(Boolean);
13528 if (isFirst) res.unshift('');
13529 if (isLast) res.push('');
13530 return res.join(ch);
13531}
13532
13533/**
13534 * Negate slashes in exclusion ranges, per glob spec:
13535 *
13536 * ```js
13537 * negateSlash('[^foo]');
13538 * //=> '[^\\/foo]'
13539 * ```
13540 *
13541 * @param {String} `str` glob pattern
13542 * @return {String}
13543 */
13544
13545function negateSlash(str) {
13546 return str.replace(/\[\^([^\]]*?)\]/g, function(match, inner) {
13547 if (inner.indexOf('/') === -1) {
13548 inner = '\\/' + inner;
13549 }
13550 return '[^' + inner + ']';
13551 });
13552}
13553
13554/**
13555 * Escape imbalanced braces/bracket. This is a very
13556 * basic, naive implementation that only does enough
13557 * to serve the purpose.
13558 */
13559
13560function balance(str, a, b) {
13561 var aarr = str.split(a);
13562 var alen = aarr.join('').length;
13563 var blen = str.split(b).join('').length;
13564
13565 if (alen !== blen) {
13566 str = aarr.join('\\' + a);
13567 return str.split(b).join('\\' + b);
13568 }
13569 return str;
13570}
13571
13572/**
13573 * Special patterns to be converted to regex.
13574 * Heuristics are used to simplify patterns
13575 * and speed up processing.
13576 */
13577
13578/* eslint no-multi-spaces: 0 */
13579var qmark = '[^/]';
13580var star = qmark + '*?';
13581var nodot = '(?!\\.)(?=.)';
13582var dotfileGlob = '(?:\\/|^)\\.{1,2}($|\\/)';
13583var dotfiles = '(?!' + dotfileGlob + ')(?=.)';
13584var twoStarDot = '(?:(?!' + dotfileGlob + ').)*?';
13585
13586/**
13587 * Create a regex for `*`.
13588 *
13589 * If `dot` is true, or the pattern does not begin with
13590 * a leading star, then return the simpler regex.
13591 */
13592
13593function oneStar(dotfile) {
13594 return dotfile ? '(?!' + dotfileGlob + ')(?=.)' + star : (nodot + star);
13595}
13596
13597function globstar(dotfile) {
13598 if (dotfile) { return twoStarDot; }
13599 return '(?:(?!(?:\\/|^)\\.).)*?';
13600}
13601
13602/**
13603 * The main function. Pass an array of filepaths,
13604 * and a string or array of glob patterns
13605 *
13606 * @param {Array|String} `files`
13607 * @param {Array|String} `patterns`
13608 * @param {Object} `opts`
13609 * @return {Array} Array of matches
13610 */
13611
13612function micromatch(files, patterns, opts) {
13613 if (!files || !patterns) return [];
13614 opts = opts || {};
13615
13616 if (typeof opts.cache === 'undefined') {
13617 opts.cache = true;
13618 }
13619
13620 if (!Array.isArray(patterns)) {
13621 return match(files, patterns, opts);
13622 }
13623
13624 var len = patterns.length, i = 0;
13625 var omit = [], keep = [];
13626
13627 while (len--) {
13628 var glob = patterns[i++];
13629 if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) {
13630 omit.push.apply(omit, match(files, glob.slice(1), opts));
13631 } else {
13632 keep.push.apply(keep, match(files, glob, opts));
13633 }
13634 }
13635 return utils_1.diff(keep, omit);
13636}
13637
13638/**
13639 * Return an array of files that match the given glob pattern.
13640 *
13641 * This function is called by the main `micromatch` function If you only
13642 * need to pass a single pattern you might get very minor speed improvements
13643 * using this function.
13644 *
13645 * @param {Array} `files`
13646 * @param {String} `pattern`
13647 * @param {Object} `options`
13648 * @return {Array}
13649 */
13650
13651function match(files, pattern, opts) {
13652 if (utils_1.typeOf(files) !== 'string' && !Array.isArray(files)) {
13653 throw new Error(msg('match', 'files', 'a string or array'));
13654 }
13655
13656 files = utils_1.arrayify(files);
13657 opts = opts || {};
13658
13659 var negate = opts.negate || false;
13660 var orig = pattern;
13661
13662 if (typeof pattern === 'string') {
13663 negate = pattern.charAt(0) === '!';
13664 if (negate) {
13665 pattern = pattern.slice(1);
13666 }
13667
13668 // we need to remove the character regardless,
13669 // so the above logic is still needed
13670 if (opts.nonegate === true) {
13671 negate = false;
13672 }
13673 }
13674
13675 var _isMatch = matcher(pattern, opts);
13676 var len = files.length, i = 0;
13677 var res = [];
13678
13679 while (i < len) {
13680 var file = files[i++];
13681 var fp = utils_1.unixify(file, opts);
13682
13683 if (!_isMatch(fp)) { continue; }
13684 res.push(fp);
13685 }
13686
13687 if (res.length === 0) {
13688 if (opts.failglob === true) {
13689 throw new Error('micromatch.match() found no matches for: "' + orig + '".');
13690 }
13691
13692 if (opts.nonull || opts.nullglob) {
13693 res.push(utils_1.unescapeGlob(orig));
13694 }
13695 }
13696
13697 // if `negate` was defined, diff negated files
13698 if (negate) { res = utils_1.diff(files, res); }
13699
13700 // if `ignore` was defined, diff ignored filed
13701 if (opts.ignore && opts.ignore.length) {
13702 pattern = opts.ignore;
13703 opts = utils_1.omit(opts, ['ignore']);
13704 res = utils_1.diff(res, micromatch(res, pattern, opts));
13705 }
13706
13707 if (opts.nodupes) {
13708 return utils_1.unique(res);
13709 }
13710 return res;
13711}
13712
13713/**
13714 * Returns a function that takes a glob pattern or array of glob patterns
13715 * to be used with `Array#filter()`. (Internally this function generates
13716 * the matching function using the [matcher] method).
13717 *
13718 * ```js
13719 * var fn = mm.filter('[a-c]');
13720 * ['a', 'b', 'c', 'd', 'e'].filter(fn);
13721 * //=> ['a', 'b', 'c']
13722 * ```
13723 * @param {String|Array} `patterns` Can be a glob or array of globs.
13724 * @param {Options} `opts` Options to pass to the [matcher] method.
13725 * @return {Function} Filter function to be passed to `Array#filter()`.
13726 */
13727
13728function filter(patterns, opts) {
13729 if (!Array.isArray(patterns) && typeof patterns !== 'string') {
13730 throw new TypeError(msg('filter', 'patterns', 'a string or array'));
13731 }
13732
13733 patterns = utils_1.arrayify(patterns);
13734 var len = patterns.length, i = 0;
13735 var patternMatchers = Array(len);
13736 while (i < len) {
13737 patternMatchers[i] = matcher(patterns[i++], opts);
13738 }
13739
13740 return function(fp) {
13741 if (fp == null) return [];
13742 var len = patternMatchers.length, i = 0;
13743 var res = true;
13744
13745 fp = utils_1.unixify(fp, opts);
13746 while (i < len) {
13747 var fn = patternMatchers[i++];
13748 if (!fn(fp)) {
13749 res = false;
13750 break;
13751 }
13752 }
13753 return res;
13754 };
13755}
13756
13757/**
13758 * Returns true if the filepath contains the given
13759 * pattern. Can also return a function for matching.
13760 *
13761 * ```js
13762 * isMatch('foo.md', '*.md', {});
13763 * //=> true
13764 *
13765 * isMatch('*.md', {})('foo.md')
13766 * //=> true
13767 * ```
13768 * @param {String} `fp`
13769 * @param {String} `pattern`
13770 * @param {Object} `opts`
13771 * @return {Boolean}
13772 */
13773
13774function isMatch(fp, pattern, opts) {
13775 if (typeof fp !== 'string') {
13776 throw new TypeError(msg('isMatch', 'filepath', 'a string'));
13777 }
13778
13779 fp = utils_1.unixify(fp, opts);
13780 if (utils_1.typeOf(pattern) === 'object') {
13781 return matcher(fp, pattern);
13782 }
13783 return matcher(pattern, opts)(fp);
13784}
13785
13786/**
13787 * Returns true if the filepath matches the
13788 * given pattern.
13789 */
13790
13791function contains(fp, pattern, opts) {
13792 if (typeof fp !== 'string') {
13793 throw new TypeError(msg('contains', 'pattern', 'a string'));
13794 }
13795
13796 opts = opts || {};
13797 opts.contains = (pattern !== '');
13798 fp = utils_1.unixify(fp, opts);
13799
13800 if (opts.contains && !utils_1.isGlob(pattern)) {
13801 return fp.indexOf(pattern) !== -1;
13802 }
13803 return matcher(pattern, opts)(fp);
13804}
13805
13806/**
13807 * Returns true if a file path matches any of the
13808 * given patterns.
13809 *
13810 * @param {String} `fp` The filepath to test.
13811 * @param {String|Array} `patterns` Glob patterns to use.
13812 * @param {Object} `opts` Options to pass to the `matcher()` function.
13813 * @return {String}
13814 */
13815
13816function any(fp, patterns, opts) {
13817 if (!Array.isArray(patterns) && typeof patterns !== 'string') {
13818 throw new TypeError(msg('any', 'patterns', 'a string or array'));
13819 }
13820
13821 patterns = utils_1.arrayify(patterns);
13822 var len = patterns.length;
13823
13824 fp = utils_1.unixify(fp, opts);
13825 while (len--) {
13826 var isMatch = matcher(patterns[len], opts);
13827 if (isMatch(fp)) {
13828 return true;
13829 }
13830 }
13831 return false;
13832}
13833
13834/**
13835 * Filter the keys of an object with the given `glob` pattern
13836 * and `options`
13837 *
13838 * @param {Object} `object`
13839 * @param {Pattern} `object`
13840 * @return {Array}
13841 */
13842
13843function matchKeys(obj, glob, options) {
13844 if (utils_1.typeOf(obj) !== 'object') {
13845 throw new TypeError(msg('matchKeys', 'first argument', 'an object'));
13846 }
13847
13848 var fn = matcher(glob, options);
13849 var res = {};
13850
13851 for (var key in obj) {
13852 if (obj.hasOwnProperty(key) && fn(key)) {
13853 res[key] = obj[key];
13854 }
13855 }
13856 return res;
13857}
13858
13859/**
13860 * Return a function for matching based on the
13861 * given `pattern` and `options`.
13862 *
13863 * @param {String} `pattern`
13864 * @param {Object} `options`
13865 * @return {Function}
13866 */
13867
13868function matcher(pattern, opts) {
13869 // pattern is a function
13870 if (typeof pattern === 'function') {
13871 return pattern;
13872 }
13873 // pattern is a regex
13874 if (pattern instanceof RegExp) {
13875 return function(fp) {
13876 return pattern.test(fp);
13877 };
13878 }
13879
13880 if (typeof pattern !== 'string') {
13881 throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function'));
13882 }
13883
13884 // strings, all the way down...
13885 pattern = utils_1.unixify(pattern, opts);
13886
13887 // pattern is a non-glob string
13888 if (!utils_1.isGlob(pattern)) {
13889 return utils_1.matchPath(pattern, opts);
13890 }
13891 // pattern is a glob string
13892 var re = makeRe(pattern, opts);
13893
13894 // `matchBase` is defined
13895 if (opts && opts.matchBase) {
13896 return utils_1.hasFilename(re, opts);
13897 }
13898 // `matchBase` is not defined
13899 return function(fp) {
13900 fp = utils_1.unixify(fp, opts);
13901 return re.test(fp);
13902 };
13903}
13904
13905/**
13906 * Create and cache a regular expression for matching
13907 * file paths.
13908 *
13909 * If the leading character in the `glob` is `!`, a negation
13910 * regex is returned.
13911 *
13912 * @param {String} `glob`
13913 * @param {Object} `options`
13914 * @return {RegExp}
13915 */
13916
13917function toRegex(glob, options) {
13918 // clone options to prevent mutating the original object
13919 var opts = Object.create(options || {});
13920 var flags = opts.flags || '';
13921 if (opts.nocase && flags.indexOf('i') === -1) {
13922 flags += 'i';
13923 }
13924
13925 var parsed = expand_1(glob, opts);
13926
13927 // pass in tokens to avoid parsing more than once
13928 opts.negated = opts.negated || parsed.negated;
13929 opts.negate = opts.negated;
13930 glob = wrapGlob(parsed.pattern, opts);
13931 var re;
13932
13933 try {
13934 re = new RegExp(glob, flags);
13935 return re;
13936 } catch (err) {
13937 err.reason = 'micromatch invalid regex: (' + re + ')';
13938 if (opts.strict) throw new SyntaxError(err);
13939 }
13940
13941 // we're only here if a bad pattern was used and the user
13942 // passed `options.silent`, so match nothing
13943 return /$^/;
13944}
13945
13946/**
13947 * Create the regex to do the matching. If the leading
13948 * character in the `glob` is `!` a negation regex is returned.
13949 *
13950 * @param {String} `glob`
13951 * @param {Boolean} `negate`
13952 */
13953
13954function wrapGlob(glob, opts) {
13955 var prefix = (opts && !opts.contains) ? '^' : '';
13956 var after = (opts && !opts.contains) ? '$' : '';
13957 glob = ('(?:' + glob + ')' + after);
13958 if (opts && opts.negate) {
13959 return prefix + ('(?!^' + glob + ').*$');
13960 }
13961 return prefix + glob;
13962}
13963
13964/**
13965 * Create and cache a regular expression for matching file paths.
13966 * If the leading character in the `glob` is `!`, a negation
13967 * regex is returned.
13968 *
13969 * @param {String} `glob`
13970 * @param {Object} `options`
13971 * @return {RegExp}
13972 */
13973
13974function makeRe(glob, opts) {
13975 if (utils_1.typeOf(glob) !== 'string') {
13976 throw new Error(msg('makeRe', 'glob', 'a string'));
13977 }
13978 return utils_1.cache(toRegex, glob, opts);
13979}
13980
13981/**
13982 * Make error messages consistent. Follows this format:
13983 *
13984 * ```js
13985 * msg(methodName, argNumber, nativeType);
13986 * // example:
13987 * msg('matchKeys', 'first', 'an object');
13988 * ```
13989 *
13990 * @param {String} `method`
13991 * @param {String} `num`
13992 * @param {String} `type`
13993 * @return {String}
13994 */
13995
13996function msg(method, what, type) {
13997 return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.';
13998}
13999
14000/**
14001 * Public methods
14002 */
14003
14004/* eslint no-multi-spaces: 0 */
14005micromatch.any = any;
14006micromatch.braces = micromatch.braceExpand = utils_1.braces;
14007micromatch.contains = contains;
14008micromatch.expand = expand_1;
14009micromatch.filter = filter;
14010micromatch.isMatch = isMatch;
14011micromatch.makeRe = makeRe;
14012micromatch.match = match;
14013micromatch.matcher = matcher;
14014micromatch.matchKeys = matchKeys;
14015
14016/**
14017 * Expose `micromatch`
14018 */
14019
14020var index$1 = micromatch;
14021
14022function ensureArray$1 ( thing ) {
14023 if ( Array.isArray( thing ) ) return thing;
14024 if ( thing == undefined ) return [];
14025 return [ thing ];
14026}
14027
14028function createFilter ( include, exclude ) {
14029 const getMatcher = id => ( isRegexp( id ) ? id : { test: index$1.matcher( resolve( id ) ) } );
14030 include = ensureArray$1( include ).map( getMatcher );
14031 exclude = ensureArray$1( exclude ).map( getMatcher );
14032
14033 return function ( id ) {
14034
14035 if ( typeof id !== 'string' ) return false;
14036 if ( /\0/.test( id ) ) return false;
14037
14038 id = id.split( sep ).join( '/' );
14039
14040 for ( let i = 0; i < exclude.length; ++i ) {
14041 const matcher = exclude[i];
14042 if ( matcher.test( id ) ) return false;
14043 }
14044
14045 for ( let i = 0; i < include.length; ++i ) {
14046 const matcher = include[i];
14047 if ( matcher.test( id ) ) return true;
14048 }
14049
14050 return !include.length;
14051 };
14052}
14053
14054function isRegexp ( val ) {
14055 return val instanceof RegExp;
14056}
14057
14058var modules = {};
14059
14060var getModule = function(dir) {
14061 var rootPath = dir ? path.resolve(dir) : process.cwd();
14062 var rootName = path.join(rootPath, '@root');
14063 var root = modules[rootName];
14064 if (!root) {
14065 root = new module$1(rootName);
14066 root.filename = rootName;
14067 root.paths = module$1._nodeModulePaths(rootPath);
14068 modules[rootName] = root;
14069 }
14070 return root;
14071};
14072
14073var requireRelative = function(requested, relativeTo) {
14074 var root = getModule(relativeTo);
14075 return root.require(requested);
14076};
14077
14078requireRelative.resolve = function(requested, relativeTo) {
14079 var root = getModule(relativeTo);
14080 return module$1._resolveFilename(requested, root);
14081};
14082
14083var index$76 = requireRelative;
14084
14085var chokidar;
14086
14087try {
14088 chokidar = index$76( 'chokidar', process.cwd() );
14089} catch (err) {
14090 chokidar = null;
14091}
14092
14093var chokidar$1 = chokidar;
14094
14095var opts = { encoding: 'utf-8', persistent: true };
14096
14097var watchers = new Map();
14098
14099function addTask(id, task, chokidarOptions, chokidarOptionsHash) {
14100 if (!watchers.has(chokidarOptionsHash)) { watchers.set(chokidarOptionsHash, new Map()); }
14101 var group = watchers.get(chokidarOptionsHash);
14102
14103 if (!group.has(id)) {
14104 var watcher = new FileWatcher(id, chokidarOptions, function () {
14105 group.delete(id);
14106 });
14107
14108 if (watcher.fileExists) {
14109 group.set(id, watcher);
14110 } else {
14111 return;
14112 }
14113 }
14114
14115 group.get(id).tasks.add(task);
14116}
14117
14118function deleteTask(id, target, chokidarOptionsHash) {
14119 var group = watchers.get(chokidarOptionsHash);
14120
14121 var watcher = group.get(id);
14122 if (watcher) {
14123 watcher.tasks.delete(target);
14124
14125 if (watcher.tasks.size === 0) {
14126 watcher.close();
14127 group.delete(id);
14128 }
14129 }
14130}
14131
14132var FileWatcher = function FileWatcher(id, chokidarOptions, dispose) {
14133 var this$1 = this;
14134
14135 this.tasks = new Set();
14136
14137 var data;
14138
14139 try {
14140 statSync(id);
14141 this.fileExists = true;
14142 } catch (err) {
14143 if (err.code === 'ENOENT') {
14144 // can't watch files that don't exist (e.g. injected
14145 // by plugins somehow)
14146 this.fileExists = false;
14147 return;
14148 } else {
14149 throw err;
14150 }
14151 }
14152
14153 var handleWatchEvent = function (event) {
14154 if (event === 'rename' || event === 'unlink') {
14155 this$1.fsWatcher.close();
14156 this$1.trigger();
14157 dispose();
14158 } else {
14159 // this is necessary because we get duplicate events...
14160 var contents = readFileSync(id, 'utf-8');
14161 if (contents !== data) {
14162 data = contents;
14163 this$1.trigger();
14164 }
14165 }
14166 };
14167
14168 if (chokidarOptions) {
14169 this.fsWatcher = chokidar$1
14170 .watch(id, chokidarOptions)
14171 .on('all', handleWatchEvent);
14172 } else {
14173 this.fsWatcher = watch(id, opts, handleWatchEvent);
14174 }
14175};
14176
14177FileWatcher.prototype.close = function close () {
14178 this.fsWatcher.close();
14179};
14180
14181FileWatcher.prototype.trigger = function trigger () {
14182 this.tasks.forEach(function (task) {
14183 task.makeDirty();
14184 });
14185};
14186
14187var DELAY = 100;
14188
14189var Watcher = (function (EventEmitter$$1) {
14190 function Watcher(configs) {
14191 var this$1 = this;
14192
14193 EventEmitter$$1.call(this);
14194
14195 this.dirty = true;
14196 this.running = false;
14197 this.tasks = ensureArray(configs).map(function (config) { return new Task(this$1, config); });
14198 this.succeeded = false;
14199
14200 process.nextTick(function () {
14201 this$1._run();
14202 });
14203 }
14204
14205 if ( EventEmitter$$1 ) Watcher.__proto__ = EventEmitter$$1;
14206 Watcher.prototype = Object.create( EventEmitter$$1 && EventEmitter$$1.prototype );
14207 Watcher.prototype.constructor = Watcher;
14208
14209 Watcher.prototype.close = function close () {
14210 this.tasks.forEach(function (task) {
14211 task.close();
14212 });
14213
14214 this.removeAllListeners();
14215 };
14216
14217 Watcher.prototype._makeDirty = function _makeDirty () {
14218 var this$1 = this;
14219
14220 if (this.dirty) { return; }
14221 this.dirty = true;
14222
14223 if (!this.running) {
14224 setTimeout(function () {
14225 this$1._run();
14226 }, DELAY);
14227 }
14228 };
14229
14230 Watcher.prototype._run = function _run () {
14231 var this$1 = this;
14232
14233 this.running = true;
14234 this.dirty = false;
14235
14236 this.emit('event', {
14237 code: 'START'
14238 });
14239
14240 mapSequence(this.tasks, function (task) { return task.run(); })
14241 .then(function () {
14242 this$1.succeeded = true;
14243
14244 this$1.emit('event', {
14245 code: 'END'
14246 });
14247 })
14248 .catch(function (error) {
14249 this$1.emit('event', {
14250 code: this$1.succeeded ? 'ERROR' : 'FATAL',
14251 error: error
14252 });
14253 })
14254 .then(function () {
14255 this$1.running = false;
14256
14257 if (this$1.dirty) {
14258 this$1._run();
14259 }
14260 });
14261 };
14262
14263 return Watcher;
14264}(EventEmitter));
14265
14266var Task = function Task(watcher, options) {
14267 this.cache = null;
14268 this.watcher = watcher;
14269 this.options = options;
14270
14271 this.dirty = true;
14272 this.closed = false;
14273 this.watched = new Set();
14274
14275 this.targets = options.targets ? options.targets : [{ dest: options.dest, format: options.format }];
14276
14277 this.dests = (this.targets.map(function (t) { return t.dest; })).map(function (dest) { return path.resolve(dest); });
14278
14279 var watchOptions = options.watch || {};
14280 if ('useChokidar' in watchOptions) { watchOptions.chokidar = watchOptions.useChokidar; }
14281 var chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
14282 if (chokidarOptions) {
14283 chokidarOptions = Object.assign(
14284 chokidarOptions === true ? {} : chokidarOptions,
14285 {
14286 ignoreInitial: true
14287 }
14288 );
14289 }
14290
14291 if (chokidarOptions && !chokidar$1) {
14292 throw new Error("options.watch.chokidar was provided, but chokidar could not be found. Have you installed it?");
14293 }
14294
14295 this.chokidarOptions = chokidarOptions;
14296 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
14297
14298 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
14299};
14300
14301Task.prototype.close = function close () {
14302 var this$1 = this;
14303
14304 this.closed = true;
14305 this.watched.forEach(function (id) {
14306 deleteTask(id, this$1, this$1.chokidarOptionsHash);
14307 });
14308};
14309
14310Task.prototype.makeDirty = function makeDirty () {
14311 if (!this.dirty) {
14312 this.dirty = true;
14313 this.watcher._makeDirty();
14314 }
14315};
14316
14317Task.prototype.run = function run () {
14318 var this$1 = this;
14319
14320 if (!this.dirty) { return; }
14321 this.dirty = false;
14322
14323 var options = Object.assign(this.options, {
14324 cache: this.cache
14325 });
14326
14327 var start = Date.now();
14328
14329 this.watcher.emit('event', {
14330 code: 'BUNDLE_START',
14331 input: this.options.entry,
14332 output: this.dests
14333 });
14334
14335 return rollup(options)
14336 .then(function (bundle) {
14337 if (this$1.closed) { return; }
14338
14339 this$1.cache = bundle;
14340
14341 var watched = new Set();
14342
14343 bundle.modules.forEach(function (module) {
14344 watched.add(module.id);
14345 this$1.watchFile(module.id);
14346 });
14347
14348 this$1.watched.forEach(function (id) {
14349 if (!watched.has(id)) { deleteTask(id, this$1, this$1.chokidarOptionsHash); }
14350 });
14351
14352 this$1.watched = watched;
14353
14354 return Promise.all(
14355 this$1.targets.map(function (target) {
14356 var options = Object.assign({}, this$1.options, target);
14357 return bundle.write(options);
14358 })
14359 );
14360 })
14361 .then(function () {
14362 this$1.watcher.emit('event', {
14363 code: 'BUNDLE_END',
14364 input: this$1.options.entry,
14365 output: this$1.dests,
14366 duration: Date.now() - start
14367 });
14368 })
14369 .catch(function (error) {
14370 if (this$1.closed) { return; }
14371
14372 if (this$1.cache) {
14373 this$1.cache.modules.forEach(function (module) {
14374 // this is necessary to ensure that any 'renamed' files
14375 // continue to be watched following an error
14376 this$1.watchFile(module.id);
14377 });
14378 }
14379 throw error;
14380 });
14381};
14382
14383Task.prototype.watchFile = function watchFile (id) {
14384 if (!this.filter(id)) { return; }
14385
14386 if (~this.dests.indexOf(id)) {
14387 throw new Error('Cannot import the generated bundle');
14388 }
14389
14390 // this is necessary to ensure that any 'renamed' files
14391 // continue to be watched following an error
14392 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash);
14393};
14394
14395function watch$1(configs) {
14396 return new Watcher(configs);
14397}
14398
14399var version$1 = "0.47.4";
14400
14401export { rollup, watch$1 as watch, version$1 as VERSION };
14402//# sourceMappingURL=rollup.es.js.map