esperanto-source 0.6.8

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1837 @@
1
+ /*
2
+ esperanto.js v0.6.8 - 2015-02-07
3
+ http://esperantojs.org
4
+
5
+ Released under the MIT License.
6
+ */
7
+
8
+ (function (global, factory) {
9
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('acorn'), require('magic-string'), require('estraverse')) :
10
+ typeof define === 'function' && define.amd ? define(['acorn', 'magic-string', 'estraverse'], factory) :
11
+ global.esperanto = factory(global.acorn, global.MagicString, global.estraverse)
12
+ }(this, function (acorn, MagicString, estraverse) { 'use strict';
13
+
14
+ var hasOwnProp = Object.prototype.hasOwnProperty;
15
+
16
+ function hasNamedImports ( mod ) {
17
+ var i = mod.imports.length;
18
+
19
+ while ( i-- ) {
20
+ if ( mod.imports[i].isNamed ) {
21
+ return true;
22
+ }
23
+ }
24
+ }
25
+
26
+ function hasNamedExports ( mod ) {
27
+ var i = mod.exports.length;
28
+
29
+ while ( i-- ) {
30
+ if ( !mod.exports[i].isDefault ) {
31
+ return true;
32
+ }
33
+ }
34
+ }
35
+
36
+ /*
37
+ This module traverse a module's AST, attaching scope information
38
+ to nodes as it goes, which is later used to determine which
39
+ identifiers need to be rewritten to avoid collisions
40
+ */
41
+
42
+ var Scope = function ( options ) {
43
+ options = options || {};
44
+
45
+ this.parent = options.parent;
46
+ this.names = options.params || [];
47
+ };
48
+
49
+ Scope.prototype = {
50
+ add: function ( name ) {
51
+ this.names.push( name );
52
+ },
53
+
54
+ contains: function ( name, ignoreTopLevel ) {
55
+ if ( ignoreTopLevel && !this.parent ) {
56
+ return false;
57
+ }
58
+
59
+ if ( ~this.names.indexOf( name ) ) {
60
+ return true;
61
+ }
62
+
63
+ if ( this.parent ) {
64
+ return this.parent.contains( name, ignoreTopLevel );
65
+ }
66
+
67
+ return false;
68
+ }
69
+ };
70
+
71
+ function annotateAst ( ast ) {
72
+ var scope = new Scope(), blockScope = new Scope(), declared = {}, topLevelFunctionNames = [], templateLiteralRanges = [];
73
+
74
+ var envDepth = 0;
75
+
76
+ estraverse.traverse( ast, {
77
+ enter: function ( node ) {
78
+ if ( node.type === 'ImportDeclaration' ) {
79
+ node._skip = true;
80
+ }
81
+
82
+ if ( node._skip ) {
83
+ return this.skip();
84
+ }
85
+
86
+ switch ( node.type ) {
87
+ case 'FunctionExpression':
88
+ case 'FunctionDeclaration':
89
+
90
+ envDepth++;
91
+
92
+ // fallthrough
93
+
94
+ case 'ArrowFunctionExpression':
95
+ if ( node.id ) {
96
+ addToScope( node );
97
+
98
+ // If this is the root scope, this may need to be
99
+ // exported early, so we make a note of it
100
+ if ( !scope.parent && node.type === 'FunctionDeclaration' ) {
101
+ topLevelFunctionNames.push( node.id.name );
102
+ }
103
+ }
104
+
105
+ scope = node._scope = new Scope({
106
+ parent: scope,
107
+ params: node.params.map( function(x ) {return x.name} ) // TODO rest params?
108
+ });
109
+
110
+ break;
111
+
112
+ case 'BlockStatement':
113
+ blockScope = node._blockScope = new Scope({
114
+ parent: blockScope
115
+ });
116
+
117
+ break;
118
+
119
+ case 'VariableDeclaration':
120
+ node.declarations.forEach( node.kind === 'let' ? addToBlockScope : addToScope );
121
+ break;
122
+
123
+ case 'ClassExpression':
124
+ case 'ClassDeclaration':
125
+ addToScope( node );
126
+ break;
127
+
128
+ case 'MemberExpression':
129
+ if ( envDepth === 0 && node.object.type === 'ThisExpression' ) {
130
+ throw new Error('`this` at the top level is undefined');
131
+ }
132
+ !node.computed && ( node.property._skip = true );
133
+ break;
134
+
135
+ case 'Property':
136
+ node.key._skip = true;
137
+ break;
138
+
139
+ case 'TemplateLiteral':
140
+ templateLiteralRanges.push([ node.start, node.end ]);
141
+ break;
142
+
143
+ case 'ThisExpression':
144
+ if (envDepth === 0) {
145
+ node._topLevel = true;
146
+ }
147
+ break;
148
+ }
149
+ },
150
+ leave: function ( node ) {
151
+ switch ( node.type ) {
152
+ case 'FunctionExpression':
153
+ case 'FunctionDeclaration':
154
+
155
+ envDepth--;
156
+
157
+ // fallthrough
158
+
159
+ case 'ArrowFunctionExpression':
160
+
161
+ scope = scope.parent;
162
+
163
+ break;
164
+
165
+ case 'BlockStatement':
166
+ blockScope = blockScope.parent;
167
+ break;
168
+ }
169
+ }
170
+ });
171
+
172
+ function addToScope ( declarator ) {
173
+ var name = declarator.id.name;
174
+
175
+ scope.add( name );
176
+ declared[ name ] = true;
177
+ }
178
+
179
+ function addToBlockScope ( declarator ) {
180
+ var name = declarator.id.name;
181
+
182
+ blockScope.add( name );
183
+ declared[ name ] = true;
184
+ }
185
+
186
+ ast._scope = scope;
187
+ ast._blockScope = blockScope;
188
+ ast._topLevelNames = ast._scope.names.concat( ast._blockScope.names );
189
+ ast._topLevelFunctionNames = topLevelFunctionNames;
190
+ ast._declared = declared;
191
+ ast._templateLiteralRanges = templateLiteralRanges;
192
+ }
193
+
194
+ /**
195
+ * Inspects a module and discovers/categorises import & export declarations
196
+ * @param {object} mod - the module object
197
+ * @param {string} source - the module's original source code
198
+ * @param {object} ast - the result of parsing `source` with acorn
199
+ * @returns {array} - [ imports, exports ]
200
+ */
201
+ function findImportsAndExports ( mod, source, ast ) {
202
+ var imports = [], exports = [], previousDeclaration;
203
+
204
+ ast.body.forEach( function(node ) {
205
+ var passthrough, declaration;
206
+
207
+ if ( previousDeclaration ) {
208
+ previousDeclaration.next = node.start;
209
+
210
+ if ( node.type !== 'EmptyStatement' ) {
211
+ previousDeclaration = null;
212
+ }
213
+ }
214
+
215
+ if ( node.type === 'ImportDeclaration' ) {
216
+ declaration = processImport( node );
217
+ imports.push( declaration );
218
+ }
219
+
220
+ else if ( node.type === 'ExportDeclaration' ) {
221
+ declaration = processExport( node, source );
222
+ exports.push( declaration );
223
+
224
+ if ( declaration.isDefault ) {
225
+ if ( mod.defaultExport ) {
226
+ throw new Error( 'Duplicate default exports' );
227
+ }
228
+ mod.defaultExport = declaration;
229
+ }
230
+
231
+ if ( node.source ) {
232
+ // it's both an import and an export, e.g.
233
+ // `export { foo } from './bar';
234
+ passthrough = processImport( node, true );
235
+ imports.push( passthrough );
236
+
237
+ declaration.passthrough = passthrough;
238
+ }
239
+ }
240
+
241
+ if ( declaration ) {
242
+ previousDeclaration = declaration;
243
+ }
244
+ });
245
+
246
+ // catch any trailing semicolons
247
+ if ( previousDeclaration ) {
248
+ previousDeclaration.next = source.length;
249
+ previousDeclaration.isFinal = true;
250
+ }
251
+
252
+ return [ imports, exports ];
253
+ }
254
+
255
+ /**
256
+ * Generates a representation of an import declaration
257
+ * @param {object} node - the original AST node
258
+ * @param {boolean} passthrough - `true` if this is an `export { foo } from 'bar'`-style declaration
259
+ * @returns {object}
260
+ */
261
+ function processImport ( node, passthrough ) {
262
+ var x = {
263
+ id: null, // used by bundler - filled in later
264
+ node: node,
265
+ start: node.start,
266
+ end: node.end,
267
+ passthrough: !!passthrough,
268
+
269
+ path: node.source.value,
270
+ specifiers: node.specifiers.map( function(s ) {
271
+ var id;
272
+
273
+ if ( s.type === 'ImportBatchSpecifier' ) {
274
+ return {
275
+ isBatch: true,
276
+ name: s.name.name,
277
+ as: s.name.name
278
+ };
279
+ }
280
+
281
+ id = s.id.name;
282
+
283
+ return {
284
+ isDefault: !!s.default,
285
+ name: s.default ? 'default' : id,
286
+ as: s.name ? s.name.name : id
287
+ };
288
+ })
289
+ };
290
+
291
+ // TODO have different types of imports - batch, default, named
292
+ if ( x.specifiers.length === 0 ) {
293
+ x.isEmpty = true;
294
+ } else if ( x.specifiers.length === 1 && x.specifiers[0].isDefault ) {
295
+ x.isDefault = true;
296
+ x.name = x.specifiers[0].as;
297
+
298
+ } else if ( x.specifiers.length === 1 && x.specifiers[0].isBatch ) {
299
+ x.isBatch = true;
300
+ x.name = x.specifiers[0].name;
301
+ } else {
302
+ x.isNamed = true;
303
+ }
304
+
305
+ return x;
306
+ }
307
+
308
+ /**
309
+ * Generates a representation of an export declaration
310
+ * @param {object} node - the original AST node
311
+ * @param {string} source - the original source code
312
+ * @returns {object}
313
+ */
314
+ function processExport ( node, source ) {
315
+ var result, d;
316
+
317
+ result = {
318
+ node: node,
319
+ start: node.start,
320
+ end: node.end
321
+ };
322
+
323
+ if ( d = node.declaration ) {
324
+ result.value = source.slice( d.start, d.end );
325
+ result.valueStart = d.start;
326
+
327
+ // Case 1: `export var foo = 'bar'`
328
+ if ( d.type === 'VariableDeclaration' ) {
329
+ result.hasDeclaration = true; // TODO remove in favour of result.type
330
+ result.type = 'varDeclaration';
331
+ result.name = d.declarations[0].id.name;
332
+ }
333
+
334
+ // Case 2: `export function foo () {...}`
335
+ else if ( d.type === 'FunctionDeclaration' ) {
336
+ result.hasDeclaration = true; // TODO remove in favour of result.type
337
+ result.type = 'namedFunction';
338
+ result.isDefault = !!node.default;
339
+ result.name = d.id.name;
340
+ }
341
+
342
+ else if ( d.type === 'FunctionExpression' ) {
343
+ result.hasDeclaration = true; // TODO remove in favour of result.type
344
+ result.isDefault = true;
345
+
346
+ // Case 3: `export default function foo () {...}`
347
+ if ( d.id ) {
348
+ result.type = 'namedFunction';
349
+ result.name = d.id.name;
350
+ }
351
+
352
+ // Case 4: `export default function () {...}`
353
+ else {
354
+ result.type = 'anonFunction';
355
+ }
356
+ }
357
+
358
+ // Case 5: `export class Foo {...}`
359
+ else if ( d.type === 'ClassDeclaration' ) {
360
+ result.hasDeclaration = true; // TODO remove in favour of result.type
361
+ result.type = 'namedClass';
362
+ result.isDefault = !!node.default;
363
+ result.name = d.id.name;
364
+ }
365
+
366
+ else if ( d.type === 'ClassExpression' ) {
367
+ result.hasDeclaration = true; // TODO remove in favour of result.type
368
+ result.isDefault = true;
369
+
370
+ // Case 6: `export default class Foo {...}`
371
+ if ( d.id ) {
372
+ result.type = 'namedClass';
373
+ result.name = d.id.name;
374
+ }
375
+
376
+ // Case 7: `export default class {...}`
377
+ else {
378
+ result.type = 'anonClass';
379
+ }
380
+ }
381
+
382
+ // Case 8: `export default 1 + 2`
383
+ else {
384
+ result.type = 'expression';
385
+ result.isDefault = true;
386
+ result.name = 'default';
387
+ }
388
+ }
389
+
390
+ // Case 9: `export { foo, bar };`
391
+ else {
392
+ result.type = 'named';
393
+ result.specifiers = node.specifiers.map( function(s ) {return { name: s.id.name }} ); // TODO as?
394
+ }
395
+
396
+ return result;
397
+ }
398
+
399
+ function getUnscopedNames ( mod ) {
400
+ var unscoped = [], importedNames, scope;
401
+
402
+ function imported ( name ) {
403
+ if ( !importedNames ) {
404
+ importedNames = {};
405
+ mod.imports.forEach( function(i ) {
406
+ !i.passthrough && i.specifiers.forEach( function(s ) {
407
+ importedNames[ s.as ] = true;
408
+ });
409
+ });
410
+ }
411
+ return hasOwnProp.call( importedNames, name );
412
+ }
413
+
414
+ estraverse.traverse( mod.ast, {
415
+ enter: function ( node ) {
416
+ // we're only interested in references, not property names etc
417
+ if ( node._skip ) return this.skip();
418
+
419
+ if ( node._scope ) {
420
+ scope = node._scope;
421
+ }
422
+
423
+ if ( node.type === 'Identifier' &&
424
+ !scope.contains( node.name ) &&
425
+ !imported( node.name ) &&
426
+ !~unscoped.indexOf( node.name ) ) {
427
+ unscoped.push( node.name );
428
+ }
429
+ },
430
+
431
+ leave: function ( node ) {
432
+ if ( node.type === 'Program' ) {
433
+ return;
434
+ }
435
+
436
+ if ( node._scope ) {
437
+ scope = scope.parent;
438
+ }
439
+ }
440
+ });
441
+
442
+ return unscoped;
443
+ }
444
+
445
+ var reserved = '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'.split( ' ' );
446
+
447
+ /**
448
+ * Generates a sanitized (i.e. valid identifier) name from a module ID
449
+ * @param {string} id - a module ID, or part thereof
450
+ * @returns {string}
451
+ */
452
+ function sanitize ( name ) {
453
+ name = name.replace( /[^a-zA-Z0-9_$]/g, '_' );
454
+ if ( /[^a-zA-Z_$]/.test( name[0] ) ) {
455
+ name = '_' + name;
456
+ }
457
+
458
+ if ( ~reserved.indexOf( name ) ) {
459
+ name = '_' + name;
460
+ }
461
+
462
+ return name;
463
+ }
464
+
465
+ var pathSplitRE = /\/|\\/;
466
+ function splitPath ( path ) {
467
+ return path.split( pathSplitRE );
468
+ }
469
+
470
+ function getModuleNameHelper ( userFn ) {var usedNames = arguments[1];if(usedNames === void 0)usedNames = {};
471
+ var nameById = {}, getModuleName;
472
+
473
+ getModuleName = function(x ) {
474
+ var moduleId, parts, i, prefix = '', name, candidate;
475
+
476
+ moduleId = x.path;
477
+
478
+ // use existing value
479
+ if ( hasOwnProp.call( nameById, moduleId ) ) {
480
+ return nameById[ moduleId ];
481
+ }
482
+
483
+ // if user supplied a function, defer to it
484
+ if ( userFn && ( name = userFn( moduleId ) ) ) {
485
+ name = sanitize( name );
486
+
487
+ if ( hasOwnProp.call( usedNames, name ) ) {
488
+ // TODO write a test for this
489
+ throw new Error( 'Naming collision: module ' + moduleId + ' cannot be called ' + name );
490
+ }
491
+ }
492
+
493
+ else if ( x.isDefault || x.isBatch ) {
494
+ name = x.name;
495
+ }
496
+
497
+ else {
498
+ parts = splitPath( moduleId );
499
+ i = parts.length;
500
+
501
+ do {
502
+ while ( i-- ) {
503
+ candidate = prefix + sanitize( parts.slice( i ).join( '__' ) );
504
+
505
+ if ( !hasOwnProp.call( usedNames, candidate ) ) {
506
+ name = candidate;
507
+ break;
508
+ }
509
+ }
510
+
511
+ prefix += '_';
512
+ } while ( !name );
513
+ }
514
+
515
+ usedNames[ name ] = true;
516
+ nameById[ moduleId ] = name;
517
+
518
+ return name;
519
+ };
520
+
521
+ return getModuleName;
522
+ }
523
+
524
+ function getStandaloneModule ( options ) {var $D$0;
525
+ var mod, imports, exports, conflicts = {};
526
+
527
+ mod = {
528
+ body: new MagicString( options.source ),
529
+ ast: acorn.parse( options.source, {
530
+ ecmaVersion: 6,
531
+ locations: true
532
+ })
533
+ };
534
+
535
+ imports = ($D$0 = findImportsAndExports( mod, options.source, mod.ast ))[0], exports = $D$0[1], $D$0;
536
+
537
+
538
+ mod.imports = imports;
539
+ mod.exports = exports;
540
+
541
+ if ( options.strict ) {
542
+ annotateAst( mod.ast );
543
+
544
+ // TODO there's probably an easier way to get this array
545
+ Object.keys( mod.ast._declared ).concat( getUnscopedNames( mod ) ).forEach( function(n ) {
546
+ conflicts[n] = true;
547
+ });
548
+ } else {
549
+ conflicts = mod.ast._declared;
550
+ }
551
+
552
+ mod.getName = getModuleNameHelper( options.getModuleName, conflicts );
553
+
554
+ return mod;
555
+ ;$D$0 = void 0}
556
+
557
+ function transformExportDeclaration ( declaration, body ) {
558
+ var exportedValue;
559
+
560
+ if ( declaration ) {
561
+ switch ( declaration.type ) {
562
+ case 'namedFunction':
563
+ case 'namedClass':
564
+ body.remove( declaration.start, declaration.valueStart );
565
+ exportedValue = declaration.name;
566
+ break;
567
+
568
+ case 'anonFunction':
569
+ case 'anonClass':
570
+ if ( declaration.isFinal ) {
571
+ body.replace( declaration.start, declaration.valueStart, 'return ' );
572
+ } else {
573
+ body.replace( declaration.start, declaration.valueStart, 'var __export = ' );
574
+ exportedValue = '__export';
575
+ }
576
+
577
+ // add semi-colon, if necessary
578
+ if ( declaration.value.slice( -1 ) !== ';' ) {
579
+ body.insert( declaration.end, ';' );
580
+ }
581
+
582
+ break;
583
+
584
+ case 'expression':
585
+ body.remove( declaration.start, declaration.next );
586
+ exportedValue = declaration.value;
587
+ break;
588
+
589
+ default:
590
+ throw new Error( 'Unexpected export type' );
591
+ }
592
+
593
+ if ( exportedValue ) {
594
+ body.append( '\nreturn ' + exportedValue + ';' );
595
+ }
596
+ }
597
+ }
598
+
599
+ var warned = {};
600
+
601
+ function packageResult ( body, options, methodName, isBundle ) {
602
+ var code, map;
603
+
604
+ // wrap output
605
+ if ( options.banner ) body.prepend( options.banner );
606
+ if ( options.footer ) body.append( options.footer );
607
+
608
+ code = body.toString();
609
+
610
+ if ( !!options.sourceMap ) {
611
+ if ( !options.sourceMapFile || ( !isBundle && !options.sourceMapSource ) ) {
612
+ throw new Error( 'You must provide `sourceMapSource` and `sourceMapFile` options' );
613
+ }
614
+
615
+ map = body.generateMap({
616
+ includeContent: true,
617
+ hires: true,
618
+ file: options.sourceMapFile,
619
+ source: !isBundle ? getRelativePath( options.sourceMapFile, options.sourceMapSource ) : null
620
+ });
621
+
622
+ if ( options.sourceMap === 'inline' ) {
623
+ code += '\n//# sourceMa' + 'ppingURL=' + map.toUrl();
624
+ map = null;
625
+ } else {
626
+ code += '\n//# sourceMa' + 'ppingURL=./' + splitPath( options.sourceMapFile ).pop() + '.map';
627
+ }
628
+ } else {
629
+ map = null;
630
+ }
631
+
632
+ return {
633
+ code: code,
634
+ map: map,
635
+ toString: function () {
636
+ if ( !warned[ methodName ] ) {
637
+ console.log( 'Warning: esperanto.' + methodName + '() returns an object with a \'code\' property. You should use this instead of using the returned value directly' );
638
+ warned[ methodName ] = true;
639
+ }
640
+
641
+ return code;
642
+ }
643
+ };
644
+ }
645
+
646
+ function getRelativePath ( from, to ) {
647
+ var fromParts, toParts, i;
648
+
649
+ fromParts = splitPath( from );
650
+ toParts = splitPath( to );
651
+
652
+ fromParts.pop(); // get dirname
653
+
654
+ while ( fromParts[0] === toParts[0] ) {
655
+ fromParts.shift();
656
+ toParts.shift();
657
+ }
658
+
659
+ if ( fromParts.length ) {
660
+ i = fromParts.length;
661
+ while ( i-- ) fromParts[i] = '..';
662
+
663
+ return fromParts.concat( toParts ).join( '/' );
664
+ } else {
665
+ toParts.unshift( '.' );
666
+ return toParts.join( '/' );
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Creates a template function from a template string. The template
672
+ may have `<%= someVar %>` interpolators, and the returned function
673
+ should be called with a data object e.g. `{ someVar: 'someData' }`
674
+ * @param {string} str - the template string
675
+ * @returns {function}
676
+ */
677
+ function template ( str ) {
678
+ return function ( data ) {
679
+ return str.replace( /<%=\s*([^\s]+)\s*%>/g, function ( match, $1 ) {
680
+ return $1 in data ? data[ $1 ] : match;
681
+ });
682
+ };
683
+ }
684
+
685
+ function resolveId ( importPath, importerPath ) {
686
+ var resolved, importerParts, importParts;
687
+
688
+ if ( importPath[0] !== '.' ) {
689
+ resolved = importPath;
690
+ } else {
691
+ importerParts = splitPath( importerPath );
692
+ importParts = splitPath( importPath );
693
+
694
+ if ( importParts[0] === '.' ) {
695
+ importParts.shift();
696
+ }
697
+
698
+ importerParts.pop(); // get dirname
699
+ while ( importParts[0] === '..' ) {
700
+ importParts.shift();
701
+ importerParts.pop();
702
+ }
703
+
704
+ while ( importParts[0] === '.' ) {
705
+ importParts.shift();
706
+ }
707
+
708
+ resolved = importerParts.concat( importParts ).join( '/' );
709
+ }
710
+
711
+ return resolved.replace( /\.js$/, '' );
712
+ }
713
+
714
+ function resolveAgainst ( importerPath ) {
715
+ return function ( importPath ) {
716
+ return resolveId( importPath, importerPath );
717
+ };
718
+ }
719
+
720
+ function getId ( m ) {
721
+ return m.id;
722
+ }
723
+
724
+ function getName ( m ) {
725
+ return m.name;
726
+ }
727
+
728
+ function quote ( str ) {
729
+ return "'" + JSON.stringify(str).slice(1, -1).replace(/'/g, "\\'") + "'";
730
+ }
731
+
732
+ function req ( path ) {
733
+ return 'require(' + quote(path) + ')';
734
+ }
735
+
736
+ function globalify ( name ) {
737
+ if ( /^__dep\d+__$/.test( name ) ) {
738
+ return 'undefined';
739
+ } else {
740
+ return 'global.' + name;
741
+ }
742
+ }
743
+
744
+ var amd__introTemplate = template( 'define(<%= amdName %><%= paths %>function (<%= names %>) {\n\n' );
745
+
746
+ function amd__amd ( mod, body, options ) {
747
+ var seen = {},
748
+ importNames = [],
749
+ importPaths = [],
750
+ intro,
751
+ placeholders = 0;
752
+
753
+ // gather imports, and remove import declarations
754
+ mod.imports.forEach( function(x ) {
755
+ var path = options.absolutePaths ? resolveId( x.path, options.amdName ) : x.path;
756
+
757
+ if ( !hasOwnProp.call( seen, path ) ) {
758
+ importPaths.push( path );
759
+
760
+ if ( x.name ) {
761
+ while ( placeholders ) {
762
+ importNames.push( '__dep' + importNames.length + '__' );
763
+ placeholders--;
764
+ }
765
+ importNames.push( x.name );
766
+ } else {
767
+ placeholders++;
768
+ }
769
+
770
+ seen[ path ] = true;
771
+ }
772
+
773
+ body.remove( x.start, x.next );
774
+ });
775
+
776
+ transformExportDeclaration( mod.exports[0], body );
777
+
778
+ intro = amd__introTemplate({
779
+ amdName: options.amdName ? (("'" + (options.amdName)) + "', ") : '',
780
+ paths: importPaths.length ? '[' + importPaths.map( quote ).join( ', ' ) + '], ' : '',
781
+ names: importNames.join( ', ' )
782
+ });
783
+
784
+ body.trim()
785
+ .prepend( "'use strict';\n\n" )
786
+ .trim()
787
+ .indent()
788
+ .prepend( intro )
789
+ .append( '\n\n});' );
790
+
791
+ return packageResult( body, options, 'toAmd' );
792
+ }
793
+
794
+ function cjs__cjs ( mod, body, options ) {
795
+ var seen = {}, exportDeclaration;
796
+
797
+ mod.imports.forEach( function(x ) {
798
+ if ( !hasOwnProp.call( seen, x.path ) ) {
799
+ var replacement = x.isEmpty ? (("" + (req(x.path))) + ";") : (("var " + (x.name)) + (" = " + (req(x.path))) + ";");
800
+ body.replace( x.start, x.end, replacement );
801
+
802
+ seen[ x.path ] = true;
803
+ } else {
804
+ body.remove( x.start, x.next );
805
+ }
806
+ });
807
+
808
+ exportDeclaration = mod.exports[0];
809
+
810
+ if ( exportDeclaration ) {
811
+ switch ( exportDeclaration.type ) {
812
+ case 'namedFunction':
813
+ case 'namedClass':
814
+ body.remove( exportDeclaration.start, exportDeclaration.valueStart );
815
+ body.replace( exportDeclaration.end, exportDeclaration.end, (("\nmodule.exports = " + (exportDeclaration.node.declaration.id.name)) + ";") );
816
+ break;
817
+
818
+ case 'anonFunction':
819
+ case 'anonClass':
820
+ case 'expression':
821
+ body.replace( exportDeclaration.start, exportDeclaration.valueStart, 'module.exports = ' );
822
+ break;
823
+
824
+ default:
825
+ throw new Error( 'Unexpected export type' );
826
+ }
827
+ }
828
+
829
+ body.prepend( "'use strict';\n\n" ).trimLines();
830
+
831
+ return packageResult( body, options, 'toCjs' );
832
+ }
833
+
834
+ function standaloneUmdIntro ( options, indentStr ) {
835
+ var amdName = options.amdName ?
836
+ quote(options.amdName) + ", " :
837
+ '';
838
+
839
+ var intro =
840
+ (("(function (factory) {\
841
+ \n !(typeof exports === 'object' && typeof module !== 'undefined') &&\
842
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + "factory) :\
843
+ \n factory()\
844
+ \n }(function () { 'use strict';\
845
+ \n\
846
+ \n ");
847
+
848
+ return intro.replace( /\t/g, indentStr );
849
+ }
850
+
851
+ function defaultUmdIntro ( options, indentStr ) {
852
+ var hasExports = options.hasExports;
853
+
854
+ var amdName = options.amdName ?
855
+ quote(options.amdName) + ", " :
856
+ '';
857
+ var amdDeps = options.importPaths.length > 0 ?
858
+ '[' + ( options.absolutePaths ? options.importPaths.map( resolveAgainst( options.amdName ) ) : options.importPaths ).map( quote ).join( ', ' ) + '], ' :
859
+ '';
860
+ var cjsDeps = options.importPaths.map( req ).join( ', ' );
861
+ var globalDeps = options.importNames.map( globalify ).join( ', ' );
862
+ var args = options.importNames.join( ', ' );
863
+
864
+ var cjsExport =
865
+ (hasExports ? 'module.exports = ' : '') + (("factory(" + cjsDeps) + ")");
866
+
867
+ var globalExport =
868
+ (hasExports ? (("global." + (options.name)) + " = ") : '') + (("factory(" + globalDeps) + ")");
869
+
870
+
871
+ var intro =
872
+ (("(function (global, factory) {\
873
+ \n typeof exports === 'object' && typeof module !== 'undefined' ? " + cjsExport) + (" :\
874
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + ("" + amdDeps) + ("factory) :\
875
+ \n " + globalExport) + ("\
876
+ \n }(this, function (" + args) + ") { 'use strict';\
877
+ \n\
878
+ \n ");
879
+
880
+ return intro.replace( /\t/g, indentStr );
881
+ }
882
+
883
+ var EsperantoError = function ( message, data ) {
884
+ var prop;
885
+
886
+ this.message = message;
887
+ this.stack = (new Error()).stack;
888
+
889
+ for ( prop in data ) {
890
+ if ( data.hasOwnProperty( prop ) ) {
891
+ this[ prop ] = data[ prop ];
892
+ }
893
+ }
894
+ };
895
+
896
+ EsperantoError.prototype = new Error();
897
+ EsperantoError.prototype.constructor = EsperantoError;
898
+ EsperantoError.prototype.name = 'EsperantoError';
899
+
900
+ function requireName ( options ) {
901
+ if ( !options.name ) {
902
+ throw new EsperantoError( 'You must supply a `name` option for UMD modules', {
903
+ code: 'MISSING_NAME'
904
+ });
905
+ }
906
+ }
907
+
908
+ function umd__umd ( mod, body, options ) {
909
+ var importNames = [];
910
+ var importPaths = [];
911
+ var seen = {};
912
+ var placeholders = 0;
913
+
914
+ requireName( options );
915
+
916
+ var hasImports = mod.imports.length > 0;
917
+ var hasExports = mod.exports.length > 0;
918
+
919
+ var intro;
920
+ if (!hasImports && !hasExports) {
921
+ intro = standaloneUmdIntro({
922
+ amdName: options.amdName,
923
+ }, body.getIndentString() );
924
+ } else {
925
+ // gather imports, and remove import declarations
926
+ mod.imports.forEach( function(x ) {
927
+ if ( !hasOwnProp.call( seen, x.path ) ) {
928
+ importPaths.push( x.path );
929
+
930
+ if ( x.name ) {
931
+ while ( placeholders ) {
932
+ importNames.push( '__dep' + importNames.length + '__' );
933
+ placeholders--;
934
+ }
935
+ importNames.push( x.name );
936
+ } else {
937
+ placeholders++;
938
+ }
939
+
940
+ seen[ x.path ] = true;
941
+ }
942
+
943
+ body.remove( x.start, x.next );
944
+ });
945
+
946
+ transformExportDeclaration( mod.exports[0], body );
947
+
948
+ intro = defaultUmdIntro({
949
+ hasExports: hasExports,
950
+ importPaths: importPaths,
951
+ importNames: importNames,
952
+ amdName: options.amdName,
953
+ absolutePaths: options.absolutePaths,
954
+ name: options.name
955
+ }, body.getIndentString() );
956
+ }
957
+
958
+ body.indent().prepend( intro ).trimLines().append( '\n\n}));' );
959
+
960
+ return packageResult( body, options, 'toUmd' );
961
+ }
962
+
963
+ var defaultsMode = {
964
+ amd: amd__amd,
965
+ cjs: cjs__cjs,
966
+ umd: umd__umd
967
+ };
968
+
969
+ function gatherImports ( imports, getName ) {
970
+ var chains = {}, identifierReplacements = {};
971
+
972
+ imports.forEach( function(x ) {
973
+ var moduleName = getName( x );
974
+
975
+ x.specifiers.forEach( function(s ) {
976
+ var name, replacement;
977
+
978
+ if ( s.isBatch ) {
979
+ return;
980
+ }
981
+
982
+ name = s.as;
983
+ replacement = moduleName + ( s.isDefault ? ("['default']") : ("." + (s.name)) );
984
+
985
+ if ( !x.passthrough ) {
986
+ identifierReplacements[ name ] = replacement;
987
+ }
988
+
989
+ chains[ name ] = replacement;
990
+ });
991
+ });
992
+
993
+ return [ chains, identifierReplacements ];
994
+ }
995
+
996
+ function getExportNames ( exports ) {
997
+ var result = {};
998
+
999
+ exports.forEach( function(x ) {
1000
+ if ( x.isDefault ) return;
1001
+
1002
+ if ( x.hasDeclaration ) {
1003
+ result[ x.name ] = x.name;
1004
+ return;
1005
+ }
1006
+
1007
+ x.specifiers.forEach( function(s ) {
1008
+ result[ s.name ] = s.name;
1009
+ });
1010
+ });
1011
+
1012
+ return result;
1013
+ }
1014
+
1015
+ /**
1016
+ * Scans an array of imports, and determines which identifiers
1017
+ are readonly, and which cannot be assigned to. For example
1018
+ you cannot `import foo from 'foo'` then do `foo = 42`, nor
1019
+ can you `import * from 'foo'` then do `foo.answer = 42`
1020
+ * @param {array} imports - the array of imports
1021
+ * @returns {array} [ importedBindings, importedNamespaces ]
1022
+ */
1023
+ function getReadOnlyIdentifiers ( imports ) {
1024
+ var importedBindings = {}, importedNamespaces = {};
1025
+
1026
+ imports.forEach( function(x ) {
1027
+ if ( x.passthrough ) return;
1028
+
1029
+ x.specifiers.forEach( function(s ) {
1030
+ if ( s.isBatch ) {
1031
+ importedNamespaces[ s.as ] = true;
1032
+ } else {
1033
+ importedBindings[ s.as ] = true;
1034
+ }
1035
+ });
1036
+ });
1037
+
1038
+ return [ importedBindings, importedNamespaces ];
1039
+ }
1040
+
1041
+ var bindingMessage = 'Cannot reassign imported binding ',
1042
+ namespaceMessage = 'Cannot reassign imported binding of namespace ';
1043
+
1044
+ function disallowIllegalReassignment ( node, importedBindings, importedNamespaces, scope ) {
1045
+ var assignee, name, isNamespaceAssignment;
1046
+
1047
+ if ( node.type === 'AssignmentExpression' ) {
1048
+ assignee = node.left;
1049
+ } else if ( node.type === 'UpdateExpression' ) {
1050
+ assignee = node.argument;
1051
+ } else {
1052
+ return; // not an assignment
1053
+ }
1054
+
1055
+ if ( assignee.type === 'MemberExpression' ) {
1056
+ assignee = assignee.object;
1057
+ isNamespaceAssignment = true;
1058
+ }
1059
+
1060
+ if ( assignee.type !== 'Identifier' ) {
1061
+ return; // not assigning to a binding
1062
+ }
1063
+
1064
+ name = assignee.name;
1065
+
1066
+ if ( hasOwnProp.call( isNamespaceAssignment ? importedNamespaces : importedBindings, name ) && !scope.contains( name ) ) {
1067
+ throw new Error( ( isNamespaceAssignment ? namespaceMessage : bindingMessage ) + '`' + name + '`' );
1068
+ }
1069
+ }
1070
+
1071
+ function rewriteIdentifiers ( body, node, identifierReplacements, scope ) {
1072
+ var name, replacement;
1073
+
1074
+ if ( node.type === 'Identifier' ) {
1075
+ name = node.name;
1076
+ replacement = hasOwnProp.call( identifierReplacements, name ) && identifierReplacements[ name ];
1077
+
1078
+ // TODO unchanged identifiers shouldn't have got this far -
1079
+ // remove the `replacement !== name` safeguard once that's the case
1080
+ if ( replacement && replacement !== name && !scope.contains( name, true ) ) {
1081
+ // rewrite
1082
+ body.replace( node.start, node.end, replacement );
1083
+ }
1084
+ }
1085
+ }
1086
+
1087
+ function rewriteExportAssignments ( body, node, exports, scope, alreadyExported, isTopLevelNode, capturedUpdates ) {
1088
+ var assignee, name, exportAs;
1089
+
1090
+ if ( node.type === 'AssignmentExpression' ) {
1091
+ assignee = node.left;
1092
+ } else if ( node.type === 'UpdateExpression' ) {
1093
+ assignee = node.argument;
1094
+ } else {
1095
+ return; // not an assignment
1096
+ }
1097
+
1098
+ if ( assignee.type !== 'Identifier' ) {
1099
+ return;
1100
+ }
1101
+
1102
+ name = assignee.name;
1103
+
1104
+ if ( scope.contains( name, true ) ) {
1105
+ return; // shadows an export
1106
+ }
1107
+
1108
+ if ( exports && hasOwnProp.call( exports, name ) && ( exportAs = exports[ name ] ) ) {
1109
+ if ( !!capturedUpdates ) {
1110
+ capturedUpdates.push({
1111
+ name: name,
1112
+ exportAs: exportAs
1113
+ });
1114
+ return;
1115
+ }
1116
+
1117
+ // special case - increment/decrement operators
1118
+ if ( node.operator === '++' || node.operator === '--' ) {
1119
+ body.replace( node.end, node.end, ((", exports." + exportAs) + (" = " + name) + "") );
1120
+ } else {
1121
+ body.replace( node.start, node.start, (("exports." + exportAs) + " = ") );
1122
+ }
1123
+
1124
+ // keep track of what we've already exported - we don't need to
1125
+ // export it again later
1126
+ if ( isTopLevelNode ) {
1127
+ alreadyExported[ name ] = true;
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ function traverseAst ( ast, body, identifierReplacements, importedBindings, importedNamespaces, exportNames, alreadyExported ) {
1133
+ var scope = ast._scope,
1134
+ blockScope = ast._blockScope,
1135
+ capturedUpdates = null,
1136
+ previousCapturedUpdates = null;
1137
+
1138
+ estraverse.traverse( ast, {
1139
+ enter: function ( node ) {
1140
+ // we're only interested in references, not property names etc
1141
+ if ( node._skip ) return this.skip();
1142
+
1143
+ if ( node._scope ) {
1144
+ scope = node._scope;
1145
+ } else if ( node._blockScope ) {
1146
+ blockScope = node._blockScope;
1147
+ }
1148
+
1149
+ // Special case: if you have a variable declaration that updates existing
1150
+ // bindings as a side-effect, e.g. `var a = b++`, where `b` is an exported
1151
+ // value, we can't simply append `exports.b = b` to the update (as we
1152
+ // normally would) because that would be syntactically invalid. Instead,
1153
+ // we capture the change and update the export (and any others) after the
1154
+ // variable declaration
1155
+ if ( node.type === 'VariableDeclaration' ) {
1156
+ previousCapturedUpdates = capturedUpdates;
1157
+ capturedUpdates = [];
1158
+ return;
1159
+ }
1160
+
1161
+ // Catch illegal reassignments
1162
+ disallowIllegalReassignment( node, importedBindings, importedNamespaces, scope );
1163
+
1164
+ // Rewrite assignments to exports. This call may mutate `alreadyExported`
1165
+ // and `capturedUpdates`, which are used elsewhere
1166
+ rewriteExportAssignments( body, node, exportNames, scope, alreadyExported, scope === ast._scope, capturedUpdates );
1167
+
1168
+ // Replace identifiers
1169
+ rewriteIdentifiers( body, node, identifierReplacements, scope );
1170
+
1171
+ // Replace top-level this with undefined ES6 8.1.1.5.4
1172
+ if ( node.type === 'ThisExpression' && node._topLevel ) {
1173
+ body.replace( node.start, node.end, 'undefined' );
1174
+ }
1175
+ },
1176
+
1177
+ leave: function ( node ) {
1178
+ // Special case - see above
1179
+ if ( node.type === 'VariableDeclaration' ) {
1180
+ if ( capturedUpdates.length ) {
1181
+ body.insert( node.end, capturedUpdates.map( exportCapturedUpdate ).join( '' ) );
1182
+ }
1183
+
1184
+ capturedUpdates = previousCapturedUpdates;
1185
+ }
1186
+
1187
+ if ( node._scope ) {
1188
+ scope = scope.parent;
1189
+ } else if ( node._blockScope ) {
1190
+ blockScope = blockScope.parent;
1191
+ }
1192
+ }
1193
+ });
1194
+ }
1195
+
1196
+ function exportCapturedUpdate ( c ) {
1197
+ return ((" exports." + (c.name)) + (" = " + (c.exportAs)) + ";");
1198
+ }
1199
+
1200
+ function transformBody ( mod, body, options ) {var $D$1;
1201
+ var chains,
1202
+ identifierReplacements,
1203
+ importedBindings = {},
1204
+ importedNamespaces = {},
1205
+ exportNames,
1206
+ alreadyExported = {},
1207
+ earlyExports,
1208
+ lateExports;
1209
+
1210
+ chains = ($D$1 = gatherImports( mod.imports, mod.getName ))[0], identifierReplacements = $D$1[1], $D$1;
1211
+ exportNames = getExportNames( mod.exports );
1212
+
1213
+ importedBindings = ($D$1 = getReadOnlyIdentifiers( mod.imports ))[0], importedNamespaces = $D$1[1], $D$1;
1214
+
1215
+ // ensure no conflict with `exports`
1216
+ identifierReplacements.exports = deconflict( 'exports', mod.ast._declared );
1217
+
1218
+ traverseAst( mod.ast, body, identifierReplacements, importedBindings, importedNamespaces, exportNames, alreadyExported );
1219
+
1220
+ // Remove import statements from the body of the module
1221
+ mod.imports.forEach( function(x ) {
1222
+ if ( x.passthrough ) {
1223
+ // this is an `export { foo } from './bar'` statement -
1224
+ // it will be dealt with in the next section
1225
+ return;
1226
+ }
1227
+
1228
+ body.remove( x.start, x.next );
1229
+ });
1230
+
1231
+ // Prepend require() statements (CommonJS output only)
1232
+ if ( options.header ) {
1233
+ body.prepend( options.header + '\n\n' );
1234
+ }
1235
+
1236
+ // Remove export statements (but keep declarations)
1237
+ mod.exports.forEach( function(x ) {
1238
+ switch ( x.type ) {
1239
+ case 'varDeclaration': // export var answer = 42;
1240
+ body.remove( x.start, x.valueStart );
1241
+ return;
1242
+
1243
+ case 'namedFunction':
1244
+ case 'namedClass':
1245
+ if ( x.isDefault ) {
1246
+ // export default function answer () { return 42; }
1247
+ body.remove( x.start, x.valueStart );
1248
+ body.insert( x.end, (("\nexports['default'] = " + (x.name)) + ";") );
1249
+ } else {
1250
+ // export function answer () { return 42; }
1251
+ body.remove( x.start, x.valueStart );
1252
+ }
1253
+ return;
1254
+
1255
+ case 'anonFunction': // export default function () {}
1256
+ case 'anonClass': // export default class () {}
1257
+ case 'expression': // export default 40 + 2;
1258
+ body.replace( x.start, x.valueStart, 'exports[\'default\'] = ' );
1259
+ return;
1260
+
1261
+ case 'named': // export { foo, bar };
1262
+ body.remove( x.start, x.next );
1263
+ break;
1264
+
1265
+ default:
1266
+ throw new Error( 'Unknown export type: ' + x.type );
1267
+ }
1268
+ });
1269
+
1270
+ // Append export block (this is the same for all module types, unlike imports)
1271
+ earlyExports = [];
1272
+ lateExports = [];
1273
+
1274
+ Object.keys( exportNames ).forEach( function(name ) {
1275
+ var exportAs = exportNames[ name ];
1276
+
1277
+ if ( chains.hasOwnProperty( name ) ) {
1278
+ // special case - a binding from another module
1279
+ if ( !options._evilES3SafeReExports ) {
1280
+ earlyExports.push( (("Object.defineProperty(exports, '" + exportAs) + ("', { enumerable: true, get: function () { return " + (chains[name])) + "; }});") );
1281
+ } else {
1282
+ lateExports.push( (("exports." + exportAs) + (" = " + (chains[name])) + ";") );
1283
+ }
1284
+ } else if ( ~mod.ast._topLevelFunctionNames.indexOf( name ) ) {
1285
+ // functions should be exported early, in
1286
+ // case of cyclic dependencies
1287
+ earlyExports.push( (("exports." + exportAs) + (" = " + name) + ";") );
1288
+ } else if ( !alreadyExported.hasOwnProperty( name ) ) {
1289
+ lateExports.push( (("exports." + exportAs) + (" = " + name) + ";") );
1290
+ }
1291
+ });
1292
+
1293
+ // Function exports should be exported immediately after 'use strict'
1294
+ if ( earlyExports.length ) {
1295
+ body.trim().prepend( earlyExports.join( '\n' ) + '\n\n' );
1296
+ }
1297
+
1298
+ // Everything else should be exported at the end
1299
+ if ( lateExports.length ) {
1300
+ body.trim().append( '\n\n' + lateExports.join( '\n' ) );
1301
+ }
1302
+
1303
+ if ( options.intro && options.outro ) {
1304
+ body.indent().prepend( options.intro ).trimLines().append( options.outro );
1305
+ }
1306
+ ;$D$1 = void 0}
1307
+
1308
+ function deconflict ( name, declared ) {
1309
+ while ( hasOwnProp.call( declared, name ) ) {
1310
+ name = '_' + name;
1311
+ }
1312
+
1313
+ return name;
1314
+ }
1315
+
1316
+ function getImportSummary ( mod ) {
1317
+ var importPaths = [], importNames = [], seen = {}, placeholders = 0;
1318
+
1319
+ mod.imports.forEach( function(x ) {
1320
+ if ( !hasOwnProp.call( seen, x.path ) ) {
1321
+ importPaths.push( x.path );
1322
+
1323
+ if ( x.specifiers.length ) {
1324
+ while ( placeholders ) {
1325
+ importNames.push( '__dep' + importNames.length + '__' );
1326
+ placeholders--;
1327
+ }
1328
+ importNames.push( mod.getName( x ) );
1329
+ } else {
1330
+ placeholders++;
1331
+ }
1332
+
1333
+ seen[ x.path ] = true;
1334
+ }
1335
+ });
1336
+
1337
+ return [ importPaths, importNames ];
1338
+ }
1339
+
1340
+ var strictMode_amd__introTemplate;
1341
+
1342
+ strictMode_amd__introTemplate = template( 'define(<%= amdName %><%= paths %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
1343
+
1344
+ function strictMode_amd__amd ( mod, body, options ) {var $D$2;
1345
+ var importPaths,
1346
+ importNames,
1347
+ intro;
1348
+
1349
+ importPaths = ($D$2 = getImportSummary( mod ))[0], importNames = $D$2[1], $D$2;
1350
+
1351
+ if ( mod.exports.length ) {
1352
+ importPaths.unshift( 'exports' );
1353
+ importNames.unshift( 'exports' );
1354
+ }
1355
+
1356
+ intro = strictMode_amd__introTemplate({
1357
+ amdName: options.amdName ? (("'" + (options.amdName)) + "', ") : '',
1358
+ paths: importPaths.length ? '[' + ( options.absolutePaths ? importPaths.map( resolveAgainst( options.amdName ) ) : importPaths ).map( quote ).join( ', ' ) + '], ' : '',
1359
+ names: importNames.join( ', ' )
1360
+ }).replace( /\t/g, body.getIndentString() );
1361
+
1362
+ transformBody( mod, body, {
1363
+ intro: intro,
1364
+ outro: '\n\n});',
1365
+ _evilES3SafeReExports: options._evilES3SafeReExports
1366
+ });
1367
+
1368
+ return packageResult( body, options, 'toAmd' );
1369
+ ;$D$2 = void 0}
1370
+
1371
+ function strictMode_cjs__cjs ( mod, body, options ) {
1372
+ var importBlock, seen = {};
1373
+
1374
+ // Create block of require statements
1375
+ importBlock = mod.imports.map( function(x ) {
1376
+ var name, replacement;
1377
+
1378
+ if ( !hasOwnProp.call( seen, x.path ) ) {
1379
+ if ( x.isEmpty ) {
1380
+ replacement = (("" + (req(x.path))) + ";");
1381
+ } else {
1382
+ name = mod.getName( x );
1383
+ replacement = (("var " + name) + (" = " + (req(x.path))) + ";");
1384
+ }
1385
+
1386
+ seen[ x.path ] = true;
1387
+ }
1388
+
1389
+ return replacement;
1390
+ }).filter( Boolean ).join( '\n' );
1391
+
1392
+ transformBody( mod, body, {
1393
+ header: importBlock,
1394
+ _evilES3SafeReExports: options._evilES3SafeReExports
1395
+ });
1396
+
1397
+ body.prepend( "'use strict';\n\n" ).trimLines();
1398
+
1399
+ return packageResult( body, options, 'toCjs' );
1400
+ }
1401
+
1402
+ function strictUmdIntro ( options, indentStr ) {
1403
+ var hasExports = options.hasExports;
1404
+
1405
+ var amdName = options.amdName ?
1406
+ "'" + options.amdName + "', " :
1407
+ '';
1408
+ var amdDeps = hasExports || options.importPaths.length > 0 ?
1409
+ '[' +
1410
+ ( hasExports ? [ 'exports' ] : [] ).concat( options.absolutePaths ? options.importPaths.map( resolveAgainst( options.amdName ) ) : options.importPaths ).map( quote ).join( ', ' ) +
1411
+ '], ' :
1412
+ '';
1413
+ var cjsDeps = ( hasExports ? [ 'exports' ] : [] ).concat( options.importPaths.map( req ) ).join( ', ' );
1414
+ var globalDeps = ( hasExports ? [ (("(global." + (options.name)) + " = {})") ] : [] )
1415
+ .concat( options.importNames.map( globalify ) ).join( ', ' );
1416
+ var args = ( hasExports ? [ 'exports' ] : [] ).concat( options.importNames ).join( ', ' );
1417
+
1418
+ var defaultsBlock = '';
1419
+ if ( options.externalDefaults && options.externalDefaults.length > 0 ) {
1420
+ defaultsBlock = options.externalDefaults.map( function(x )
1421
+ {return '\t' + ( x.needsNamed ? (("var " + (x.name)) + "__default") : x.name ) +
1422
+ ((" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");")}
1423
+ ).join('\n') + '\n\n';
1424
+ }
1425
+
1426
+ var intro =
1427
+ (("(function (global, factory) {\
1428
+ \n typeof exports === 'object' && typeof module !== 'undefined' ? factory(" + cjsDeps) + (") :\
1429
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + ("" + amdDeps) + ("factory) :\
1430
+ \n factory(" + globalDeps) + (")\
1431
+ \n }(this, function (" + args) + (") { 'use strict';\
1432
+ \n\
1433
+ \n " + defaultsBlock) + "");
1434
+
1435
+ return intro.replace( /\t/g, indentStr );
1436
+ }
1437
+
1438
+ function strictMode_umd__umd ( mod, body, options ) {
1439
+ requireName( options );
1440
+
1441
+ var importPaths = (importNames = getImportSummary( mod ))[0], importNames = importNames[1];
1442
+
1443
+ var hasImports = mod.imports.length > 0;
1444
+ var hasExports = mod.exports.length > 0;
1445
+
1446
+ var intro;
1447
+ if (!hasImports && !hasExports) {
1448
+ intro = standaloneUmdIntro({
1449
+ amdName: options.amdName,
1450
+ }, body.getIndentString() );
1451
+ } else {
1452
+ intro = strictUmdIntro({
1453
+ hasExports: hasExports,
1454
+ importPaths: importPaths,
1455
+ importNames: importNames,
1456
+ amdName: options.amdName,
1457
+ absolutePaths: options.absolutePaths,
1458
+ name: options.name
1459
+ }, body.getIndentString() );
1460
+ }
1461
+
1462
+ transformBody( mod, body, {
1463
+ intro: intro,
1464
+ outro: '\n\n}));',
1465
+ _evilES3SafeReExports: options._evilES3SafeReExports
1466
+ });
1467
+
1468
+ return packageResult( body, options, 'toUmd' );
1469
+ }
1470
+
1471
+ var strictMode = {
1472
+ amd: strictMode_amd__amd,
1473
+ cjs: strictMode_cjs__cjs,
1474
+ umd: strictMode_umd__umd
1475
+ };
1476
+
1477
+ // TODO rewrite with named imports/exports
1478
+ var moduleBuilders = {
1479
+ defaultsMode: defaultsMode,
1480
+ strictMode: strictMode
1481
+ };
1482
+
1483
+ var defaultsMode_amd__introTemplate = template( 'define(<%= amdName %><%= amdDeps %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
1484
+
1485
+ function defaultsMode_amd__amd ( bundle, body, options ) {
1486
+ var defaultName = bundle.entryModule.identifierReplacements.default;
1487
+ if ( defaultName ) {
1488
+ body.append( (("\n\nreturn " + defaultName) + ";") );
1489
+ }
1490
+
1491
+ var intro = defaultsMode_amd__introTemplate({
1492
+ amdName: options.amdName ? (("" + (quote(options.amdName))) + ", ") : '',
1493
+ amdDeps: bundle.externalModules.length ? '[' + bundle.externalModules.map( quoteId ).join( ', ' ) + '], ' : '',
1494
+ names: bundle.externalModules.map( getName ).join( ', ' )
1495
+ }).replace( /\t/g, body.getIndentString() );
1496
+
1497
+ body.indent().prepend( intro ).trimLines().append( '\n\n});' );
1498
+ return packageResult( body, options, 'toAmd', true );
1499
+ }
1500
+
1501
+ function quoteId ( m ) {
1502
+ return "'" + m.id + "'";
1503
+ }
1504
+
1505
+ function defaultsMode_cjs__cjs ( bundle, body, options ) {
1506
+ var importBlock = bundle.externalModules.map( function(x ) {
1507
+ return (("var " + (x.name)) + (" = " + (req(x.id))) + ";");
1508
+ }).join( '\n' );
1509
+
1510
+ if ( importBlock ) {
1511
+ body.prepend( importBlock + '\n\n' );
1512
+ }
1513
+
1514
+ var defaultName = bundle.entryModule.identifierReplacements.default;
1515
+ if ( defaultName ) {
1516
+ body.append( (("\n\nmodule.exports = " + defaultName) + ";") );
1517
+ }
1518
+
1519
+ body.prepend("'use strict';\n\n").trimLines();
1520
+
1521
+ return packageResult( body, options, 'toCjs', true );
1522
+ }
1523
+
1524
+ function defaultsMode_umd__umd ( bundle, body, options ) {
1525
+ requireName( options );
1526
+
1527
+ var entry = bundle.entryModule;
1528
+
1529
+ var hasImports = bundle.externalModules.length > 0;
1530
+ var hasExports = entry.exports.length > 0;
1531
+
1532
+ var intro;
1533
+ if (!hasImports && !hasExports) {
1534
+ intro = standaloneUmdIntro({
1535
+ amdName: options.amdName,
1536
+ }, body.getIndentString() );
1537
+ } else {
1538
+
1539
+ var defaultName = entry.identifierReplacements.default;
1540
+ if ( defaultName ) {
1541
+ body.append( (("\n\nreturn " + defaultName) + ";") );
1542
+ }
1543
+
1544
+ var importPaths = bundle.externalModules.map( getId );
1545
+ var importNames = bundle.externalModules.map( getName );
1546
+
1547
+ intro = defaultUmdIntro({
1548
+ hasExports: hasExports,
1549
+ importPaths: importPaths,
1550
+ importNames: importNames,
1551
+ amdName: options.amdName,
1552
+ name: options.name
1553
+ }, body.getIndentString() );
1554
+ }
1555
+
1556
+ body.indent().prepend( intro ).trimLines().append('\n\n}));');
1557
+
1558
+ return packageResult( body, options, 'toUmd', true );
1559
+ }
1560
+
1561
+ var builders_defaultsMode = {
1562
+ amd: defaultsMode_amd__amd,
1563
+ cjs: defaultsMode_cjs__cjs,
1564
+ umd: defaultsMode_umd__umd
1565
+ };
1566
+
1567
+ function getExportBlock ( entry ) {
1568
+ var name = entry.identifierReplacements.default;
1569
+ return (("exports['default'] = " + name) + ";");
1570
+ }
1571
+
1572
+ var builders_strictMode_amd__introTemplate = template( 'define(<%= amdName %><%= amdDeps %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
1573
+
1574
+ function builders_strictMode_amd__amd ( bundle, body, options ) {
1575
+ var externalDefaults = bundle.externalModules.filter( builders_strictMode_amd__needsDefault );
1576
+ var entry = bundle.entryModule;
1577
+
1578
+ var importIds = bundle.externalModules.map( getId );
1579
+ var importNames = bundle.externalModules.map( getName );
1580
+
1581
+ if ( externalDefaults.length ) {
1582
+ var defaultsBlock = externalDefaults.map( function(x ) {
1583
+ // Case 1: default is used, and named is not
1584
+ if ( !x.needsNamed ) {
1585
+ return (("" + (x.name)) + (" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
1586
+ }
1587
+
1588
+ // Case 2: both default and named are used
1589
+ return (("var " + (x.name)) + ("__default = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
1590
+ }).join( '\n' );
1591
+
1592
+ body.prepend( defaultsBlock + '\n\n' );
1593
+ }
1594
+
1595
+ if ( entry.exports.length ) {
1596
+ importIds.unshift( 'exports' );
1597
+ importNames.unshift( 'exports' );
1598
+
1599
+ if ( entry.defaultExport ) {
1600
+ body.append( '\n\n' + getExportBlock( entry ) );
1601
+ }
1602
+ }
1603
+
1604
+ var intro = builders_strictMode_amd__introTemplate({
1605
+ amdName: options.amdName ? (("" + (quote(options.amdName))) + ", ") : '',
1606
+ amdDeps: importIds.length ? '[' + importIds.map( quote ).join( ', ' ) + '], ' : '',
1607
+ names: importNames.join( ', ' )
1608
+ }).replace( /\t/g, body.getIndentString() );
1609
+
1610
+ body.indent().prepend( intro ).trimLines().append( '\n\n});' );
1611
+ return packageResult( body, options, 'toAmd', true );
1612
+ }
1613
+
1614
+ function builders_strictMode_amd__needsDefault ( externalModule ) {
1615
+ return externalModule.needsDefault;
1616
+ }
1617
+
1618
+ function builders_strictMode_cjs__cjs ( bundle, body, options ) {
1619
+ var entry = bundle.entryModule;
1620
+
1621
+ var importBlock = bundle.externalModules.map( function(x ) {
1622
+ var statement = (("var " + (x.name)) + (" = " + (req(x.id))) + ";");
1623
+
1624
+ if ( x.needsDefault ) {
1625
+ statement += '\n' +
1626
+ ( x.needsNamed ? (("var " + (x.name)) + "__default") : x.name ) +
1627
+ ((" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
1628
+ }
1629
+
1630
+ return statement;
1631
+ }).join( '\n' );
1632
+
1633
+ if ( importBlock ) {
1634
+ body.prepend( importBlock + '\n\n' );
1635
+ }
1636
+
1637
+ if ( entry.defaultExport ) {
1638
+ body.append( '\n\n' + getExportBlock( entry ) );
1639
+ }
1640
+
1641
+ body.prepend("'use strict';\n\n").trimLines();
1642
+
1643
+ return packageResult( body, options, 'toCjs', true );
1644
+ }
1645
+
1646
+ function builders_strictMode_umd__umd ( bundle, body, options ) {
1647
+ requireName( options );
1648
+
1649
+ var entry = bundle.entryModule;
1650
+
1651
+ var hasImports = bundle.externalModules.length > 0;
1652
+ var hasExports = entry.exports.length > 0;
1653
+
1654
+ var intro;
1655
+ if (!hasImports && !hasExports) {
1656
+ intro = standaloneUmdIntro({
1657
+ amdName: options.amdName,
1658
+ }, body.getIndentString() );
1659
+ } else {
1660
+
1661
+ if ( hasExports && entry.defaultExport ) {
1662
+ body.append( '\n\n' + getExportBlock( entry ) );
1663
+ }
1664
+
1665
+ var importPaths = bundle.externalModules.map( getId );
1666
+ var importNames = bundle.externalModules.map( getName );
1667
+
1668
+ intro = strictUmdIntro({
1669
+ hasExports: hasExports,
1670
+ importPaths: importPaths,
1671
+ importNames: importNames,
1672
+ externalDefaults: bundle.externalModules.filter( builders_strictMode_umd__needsDefault ),
1673
+ amdName: options.amdName,
1674
+ name: options.name,
1675
+ }, body.getIndentString() );
1676
+ }
1677
+
1678
+ body.indent().prepend( intro ).trimLines().append('\n\n}));');
1679
+
1680
+ return packageResult( body, options, 'toUmd', true );
1681
+ }
1682
+
1683
+ function builders_strictMode_umd__needsDefault ( externalModule ) {
1684
+ return externalModule.needsDefault;
1685
+ }
1686
+
1687
+ var builders_strictMode = {
1688
+ amd: builders_strictMode_amd__amd,
1689
+ cjs: builders_strictMode_cjs__cjs,
1690
+ umd: builders_strictMode_umd__umd
1691
+ };
1692
+
1693
+ // TODO rewrite with named imports/exports
1694
+ var bundleBuilders = {
1695
+ defaultsMode: builders_defaultsMode,
1696
+ strictMode: builders_strictMode
1697
+ };
1698
+
1699
+ function concat ( bundle, options ) {
1700
+ var body, intro, outro, indent;
1701
+
1702
+ // This bundle must be self-contained - no imports or exports
1703
+ if ( bundle.externalModules.length || bundle.entryModule.exports.length ) {
1704
+ throw new Error( (("bundle.concat() can only be used with bundles that have no imports/exports (imports: [" + (bundle.externalModules.map(function(x){return x.id}).join(', '))) + ("], exports: [" + (bundle.entryModule.exports.join(', '))) + "])") );
1705
+ }
1706
+
1707
+ body = bundle.body.clone();
1708
+
1709
+ // TODO test these options
1710
+ intro = 'intro' in options ? options.intro : ("(function () { 'use strict';\n\n");
1711
+ outro = 'outro' in options ? options.outro : '\n\n})();';
1712
+
1713
+ if ( !( 'indent' in options ) || options.indent === true ) {
1714
+ indent = body.getIndentString();
1715
+ } else {
1716
+ indent = options.indent || '';
1717
+ }
1718
+
1719
+ body.trimLines().indent( indent ).prepend( intro ).append( outro );
1720
+
1721
+ return packageResult( body, options, 'toString', true );
1722
+ }
1723
+
1724
+ var deprecateMessage = 'options.defaultOnly has been deprecated, and is now standard behaviour. To use named imports/exports, pass `strict: true`.',
1725
+ alreadyWarned = false;
1726
+
1727
+ function transpileMethod ( format ) {
1728
+ return function ( source ) {var options = arguments[1];if(options === void 0)options = {};
1729
+ var mod,
1730
+ body,
1731
+ builder;
1732
+
1733
+ mod = getStandaloneModule({ source: source, getModuleName: options.getModuleName, strict: options.strict });
1734
+ body = mod.body.clone();
1735
+
1736
+ if ( 'defaultOnly' in options && !alreadyWarned ) {
1737
+ // TODO link to a wiki page explaining this, or something
1738
+ console.log( deprecateMessage );
1739
+ alreadyWarned = true;
1740
+ }
1741
+
1742
+ if ( options.absolutePaths && !options.amdName ) {
1743
+ throw new Error( 'You must specify an `amdName` in order to use the `absolutePaths` option' );
1744
+ }
1745
+
1746
+ if ( !options.strict ) {
1747
+ // ensure there are no named imports/exports. TODO link to a wiki page...
1748
+ if ( hasNamedImports( mod ) || hasNamedExports( mod ) ) {
1749
+ throw new Error( 'You must be in strict mode (pass `strict: true`) to use named imports or exports' );
1750
+ }
1751
+
1752
+ builder = moduleBuilders.defaultsMode[ format ];
1753
+ } else {
1754
+ builder = moduleBuilders.strictMode[ format ];
1755
+ }
1756
+
1757
+ return builder( mod, body, options );
1758
+ };
1759
+ }
1760
+
1761
+ var esperanto = {
1762
+ toAmd: transpileMethod( 'amd' ),
1763
+ toCjs: transpileMethod( 'cjs' ),
1764
+ toUmd: transpileMethod( 'umd' ),
1765
+
1766
+ bundle: function ( options ) {
1767
+ return getBundle( options ).then( function ( bundle ) {
1768
+ return {
1769
+ imports: bundle.externalModules.map( function(mod ) {return mod.id} ),
1770
+ exports: flattenExports( bundle.entryModule.exports ),
1771
+
1772
+ toAmd: function(options ) {return transpile( 'amd', options )},
1773
+ toCjs: function(options ) {return transpile( 'cjs', options )},
1774
+ toUmd: function(options ) {return transpile( 'umd', options )},
1775
+
1776
+ concat: function(options ) {return concat( bundle, options || {} )}
1777
+ };
1778
+
1779
+ function transpile ( format, options ) {
1780
+ var builder;
1781
+
1782
+ options = options || {};
1783
+
1784
+ if ( 'defaultOnly' in options && !alreadyWarned ) {
1785
+ // TODO link to a wiki page explaining this, or something
1786
+ console.log( deprecateMessage );
1787
+ alreadyWarned = true;
1788
+ }
1789
+
1790
+ if ( !options.strict ) {
1791
+ // ensure there are no named imports/exports
1792
+ if ( hasNamedExports( bundle.entryModule ) ) {
1793
+ throw new Error( 'Entry module can only have named exports in strict mode (pass `strict: true`)' );
1794
+ }
1795
+
1796
+ bundle.modules.forEach( function(mod ) {
1797
+ mod.imports.forEach( function(x ) {
1798
+ if ( hasOwnProp.call( bundle.externalModuleLookup, x.id ) && ( !x.isDefault && !x.isBatch ) ) {
1799
+ throw new Error( 'You can only have named external imports in strict mode (pass `strict: true`)' );
1800
+ }
1801
+ });
1802
+ });
1803
+
1804
+ builder = bundleBuilders.defaultsMode[ format ];
1805
+ } else {
1806
+ builder = bundleBuilders.strictMode[ format ];
1807
+ }
1808
+
1809
+ return builder( bundle, bundle.body.clone(), options );
1810
+ }
1811
+ });
1812
+ }
1813
+ };
1814
+
1815
+ function flattenExports ( exports ) {
1816
+ var flattened = [];
1817
+
1818
+ exports.forEach( function(x ) {
1819
+ if ( x.isDefault ) {
1820
+ flattened.push( 'default' );
1821
+ }
1822
+
1823
+ else if ( x.name ) {
1824
+ flattened.push( x.name );
1825
+ }
1826
+
1827
+ else if ( x.specifiers ) {
1828
+ flattened.push.apply( flattened, x.specifiers.map( getName ) );
1829
+ }
1830
+ });
1831
+
1832
+ return flattened;
1833
+ }
1834
+
1835
+ return esperanto;
1836
+
1837
+ }));