1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.BrowserESModuleLoader = factory());
}(this, (function () { 'use strict';
/*
* Environment
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/);
var envGlobal = typeof self !== 'undefined' ? self : global;
/*
* Simple Symbol() shim
*/
var hasSymbol = typeof Symbol !== 'undefined';
function createSymbol (name) {
return hasSymbol ? Symbol() : '@@' + name;
}
/*
* Environment baseURI
*/
var baseURI;
// environent baseURI detection
if (typeof document != 'undefined' && document.getElementsByTagName) {
baseURI = document.baseURI;
if (!baseURI) {
var bases = document.getElementsByTagName('base');
baseURI = bases[0] && bases[0].href || window.location.href;
}
}
else if (typeof location != 'undefined') {
baseURI = location.href;
}
// sanitize out the hash and querystring
if (baseURI) {
baseURI = baseURI.split('#')[0].split('?')[0];
var slashIndex = baseURI.lastIndexOf('/');
if (slashIndex !== -1)
baseURI = baseURI.substr(0, slashIndex + 1);
}
else if (typeof process !== 'undefined' && process.cwd) {
baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd();
if (isWindows)
baseURI = baseURI.replace(/\\/g, '/');
}
else {
throw new TypeError('No environment baseURI');
}
// ensure baseURI has trailing "/"
if (baseURI[baseURI.length - 1] !== '/')
baseURI += '/';
/*
* LoaderError with chaining for loader stacks
*/
var errArgs = new Error(0, '_').fileName == '_';
function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) {
// Convert file:/// URLs to paths in Node
if (!isBrowser)
newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, '');
var message = (childErr.message || childErr) + '\n ' + newMessage;
var err;
if (errArgs && childErr.fileName)
err = new Error(message, childErr.fileName, childErr.lineNumber);
else
err = new Error(message);
var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack;
if (isNode)
// node doesn't show the message otherwise
err.stack = message + '\n ' + stack;
else
err.stack = stack;
err.originalErr = childErr.originalErr || childErr;
return err;
}
var resolvedPromise = Promise.resolve();
/*
* Simple Array values shim
*/
function arrayValues (arr) {
if (arr.values)
return arr.values();
if (typeof Symbol === 'undefined' || !Symbol.iterator)
throw new Error('Symbol.iterator not supported in this browser');
var iterable = {};
iterable[Symbol.iterator] = function () {
var keys = Object.keys(arr);
var keyIndex = 0;
return {
next: function () {
if (keyIndex < keys.length)
return {
value: arr[keys[keyIndex++]],
done: false
};
else
return {
value: undefined,
done: true
};
}
};
};
return iterable;
}
/*
* 3. Reflect.Loader
*
* We skip the entire native internal pipeline, just providing the bare API
*/
// 3.1.1
function Loader () {
this.registry = new Registry();
}
// 3.3.1
Loader.prototype.constructor = Loader;
function ensureInstantiated (module) {
if (!(module instanceof ModuleNamespace))
throw new TypeError('Module instantiation did not return a valid namespace object.');
return module;
}
// 3.3.2
Loader.prototype.import = function (key, parent) {
if (typeof key !== 'string')
throw new TypeError('Loader import method must be passed a module key string');
// custom resolveInstantiate combined hook for better perf
var loader = this;
return resolvedPromise
.then(function () {
return loader[RESOLVE_INSTANTIATE](key, parent);
})
.then(ensureInstantiated)
//.then(Module.evaluate)
.catch(function (err) {
throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));
});
};
// 3.3.3
var RESOLVE = Loader.resolve = createSymbol('resolve');
/*
* Combined resolve / instantiate hook
*
* Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described
* in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted.
*
* We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid
* the need for double registry lookups as a performance optimization.
*/
var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate');
// default resolveInstantiate is just to call resolve and then get from the registry
// this provides compatibility for the resolveInstantiate optimization
Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) {
var loader = this;
return loader.resolve(key, parent)
.then(function (resolved) {
return loader.registry.get(resolved);
});
};
function ensureResolution (resolvedKey) {
if (resolvedKey === undefined)
throw new RangeError('No resolution found.');
return resolvedKey;
}
Loader.prototype.resolve = function (key, parent) {
var loader = this;
return resolvedPromise
.then(function() {
return loader[RESOLVE](key, parent);
})
.then(ensureResolution)
.catch(function (err) {
throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : ''));
});
};
// 3.3.4 (import without evaluate)
// this is not documented because the use of deferred evaluation as in Module.evaluate is not
// documented, as it is not considered a stable feature to be encouraged
// Loader.prototype.load may well be deprecated if this stays disabled
/* Loader.prototype.load = function (key, parent) {
return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key))
.catch(function (err) {
throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));
});
}; */
/*
* 4. Registry
*
* Instead of structuring through a Map, just use a dictionary object
* We throw for construction attempts so this doesn't affect the public API
*
* Registry has been adjusted to use Namespace objects over ModuleStatus objects
* as part of simplifying loader API implementation
*/
var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator;
var REGISTRY = createSymbol('registry');
function Registry() {
this[REGISTRY] = {};
}
// 4.4.1
if (iteratorSupport) {
// 4.4.2
Registry.prototype[Symbol.iterator] = function () {
return this.entries()[Symbol.iterator]();
};
// 4.4.3
Registry.prototype.entries = function () {
var registry = this[REGISTRY];
return arrayValues(Object.keys(registry).map(function (key) {
return [key, registry[key]];
}));
};
}
// 4.4.4
Registry.prototype.keys = function () {
return arrayValues(Object.keys(this[REGISTRY]));
};
// 4.4.5
Registry.prototype.values = function () {
var registry = this[REGISTRY];
return arrayValues(Object.keys(registry).map(function (key) {
return registry[key];
}));
};
// 4.4.6
Registry.prototype.get = function (key) {
return this[REGISTRY][key];
};
// 4.4.7
Registry.prototype.set = function (key, namespace) {
if (!(namespace instanceof ModuleNamespace))
throw new Error('Registry must be set with an instance of Module Namespace');
this[REGISTRY][key] = namespace;
return this;
};
// 4.4.8
Registry.prototype.has = function (key) {
return Object.hasOwnProperty.call(this[REGISTRY], key);
};
// 4.4.9
Registry.prototype.delete = function (key) {
if (Object.hasOwnProperty.call(this[REGISTRY], key)) {
delete this[REGISTRY][key];
return true;
}
return false;
};
/*
* Simple ModuleNamespace Exotic object based on a baseObject
* We export this for allowing a fast-path for module namespace creation over Module descriptors
*/
// var EVALUATE = createSymbol('evaluate');
var BASE_OBJECT = createSymbol('baseObject');
// 8.3.1 Reflect.Module
/*
* Best-effort simplified non-spec implementation based on
* a baseObject referenced via getters.
*
* Allows:
*
* loader.registry.set('x', new Module({ default: 'x' }));
*
* Optional evaluation function provides experimental Module.evaluate
* support for non-executed modules in registry.
*/
function ModuleNamespace (baseObject/*, evaluate*/) {
Object.defineProperty(this, BASE_OBJECT, {
value: baseObject
});
// evaluate defers namespace population
/* if (evaluate) {
Object.defineProperty(this, EVALUATE, {
value: evaluate,
configurable: true,
writable: true
});
}
else { */
Object.keys(baseObject).forEach(extendNamespace, this);
//}
}
// 8.4.2
ModuleNamespace.prototype = Object.create(null);
if (typeof Symbol !== 'undefined' && Symbol.toStringTag)
Object.defineProperty(ModuleNamespace.prototype, Symbol.toStringTag, {
value: 'Module'
});
function extendNamespace (key) {
Object.defineProperty(this, key, {
enumerable: true,
get: function () {
return this[BASE_OBJECT][key];
}
});
}
/* function doEvaluate (evaluate, context) {
try {
evaluate.call(context);
}
catch (e) {
return e;
}
}
// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable
Module.evaluate = function (ns) {
var evaluate = ns[EVALUATE];
if (evaluate) {
ns[EVALUATE] = undefined;
var err = doEvaluate(evaluate);
if (err) {
// cache the error
ns[EVALUATE] = function () {
throw err;
};
throw err;
}
Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns);
}
// make chainable
return ns;
}; */
/*
* Optimized URL normalization assuming a syntax-valid URL parent
*/
function throwResolveError (relUrl, parentUrl) {
throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl);
}
function resolveIfNotPlain (relUrl, parentUrl) {
relUrl = relUrl.trim();
var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1);
var firstChar = relUrl[0];
var secondChar = relUrl[1];
// protocol-relative
if (firstChar === '/' && secondChar === '/') {
if (!parentProtocol)
throwResolveError(relUrl, parentUrl);
return parentProtocol + relUrl;
}
// relative-url
else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) ||
relUrl.length === 1 && (relUrl += '/')) ||
firstChar === '/') {
var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/';
// read pathname from parent if a URL
// pathname taken to be part after leading "/"
var pathname;
if (parentIsPlain) {
// resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname
if (parentUrl === undefined)
throwResolveError(relUrl, parentUrl);
pathname = parentUrl;
}
else if (parentUrl[parentProtocol.length + 1] === '/') {
// resolving to a :// so we need to read out the auth and host
if (parentProtocol !== 'file:') {
pathname = parentUrl.substr(parentProtocol.length + 2);
pathname = pathname.substr(pathname.indexOf('/') + 1);
}
else {
pathname = parentUrl.substr(8);
}
}
else {
// resolving to :/ so pathname is the /... part
pathname = parentUrl.substr(parentProtocol.length + 1);
}
if (firstChar === '/') {
if (parentIsPlain)
throwResolveError(relUrl, parentUrl);
else
return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl;
}
// join together and split for removal of .. and . segments
// looping the string instead of anything fancy for perf reasons
// '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain
var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl;
var output = [];
var segmentIndex = -1;
for (var i = 0; i < segmented.length; i++) {
// busy reading a segment - only terminate on '/'
if (segmentIndex !== -1) {
if (segmented[i] === '/') {
output.push(segmented.substring(segmentIndex, i + 1));
segmentIndex = -1;
}
continue;
}
// new segment - check if it is relative
if (segmented[i] === '.') {
// ../ segment
if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {
output.pop();
i += 2;
}
// ./ segment
else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {
i += 1;
}
else {
// the start of a new segment as below
segmentIndex = i;
continue;
}
// this is the plain URI backtracking error (../, package:x -> error)
if (parentIsPlain && output.length === 0)
throwResolveError(relUrl, parentUrl);
continue;
}
// it is the start of a new segment
segmentIndex = i;
}
// finish reading out the last segment
if (segmentIndex !== -1)
output.push(segmented.substr(segmentIndex));
return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join('');
}
// sanitizes and verifies (by returning undefined if not a valid URL-like form)
// Windows filepath compatibility is an added convenience here
var protocolIndex = relUrl.indexOf(':');
if (protocolIndex !== -1) {
if (isNode) {
// C:\x becomes file:///c:/x (we don't support C|\x)
if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i))
return 'file:///' + relUrl.replace(/\\/g, '/');
}
return relUrl;
}
}
/*
* Register Loader
*
* Builds directly on top of loader polyfill to provide:
* - loader.register support
* - hookable higher-level resolve
* - instantiate hook returning a ModuleNamespace or undefined for es module loading
* - loader error behaviour as in HTML and loader specs, caching load and eval errors separately
* - build tracing support by providing a .trace=true and .loads object format
*/
var REGISTER_INTERNAL = createSymbol('register-internal');
function RegisterLoader$1 () {
Loader.call(this);
var registryDelete = this.registry.delete;
this.registry.delete = function (key) {
var deleted = registryDelete.call(this, key);
// also delete from register registry if linked
if (records.hasOwnProperty(key) && !records[key].linkRecord) {
delete records[key];
deleted = true;
}
return deleted;
};
var records = {};
this[REGISTER_INTERNAL] = {
// last anonymous System.register call
lastRegister: undefined,
// in-flight es module load records
records: records
};
// tracing
this.trace = false;
}
RegisterLoader$1.prototype = Object.create(Loader.prototype);
RegisterLoader$1.prototype.constructor = RegisterLoader$1;
var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate');
// default normalize is the WhatWG style normalizer
RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) {
return resolveIfNotPlain(key, parentKey || baseURI);
};
RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {};
// once evaluated, the linkRecord is set to undefined leaving just the other load record properties
// this allows tracking new binding listeners for es modules through importerSetters
// for dynamic modules, the load record is removed entirely.
function createLoadRecord (state, key, registration) {
return state.records[key] = {
key: key,
// defined System.register cache
registration: registration,
// module namespace object
module: undefined,
// es-only
// this sticks around so new module loads can listen to binding changes
// for already-loaded modules by adding themselves to their importerSetters
importerSetters: undefined,
loadError: undefined,
evalError: undefined,
// in-flight linking record
linkRecord: {
// promise for instantiated
instantiatePromise: undefined,
dependencies: undefined,
execute: undefined,
executingRequire: false,
// underlying module object bindings
moduleObj: undefined,
// es only, also indicates if es or not
setters: undefined,
// promise for instantiated dependencies (dependencyInstantiations populated)
depsInstantiatePromise: undefined,
// will be the array of dependency load record or a module namespace
dependencyInstantiations: undefined,
// NB optimization and way of ensuring module objects in setters
// indicates setters which should run pre-execution of that dependency
// setters is then just for completely executed module objects
// alternatively we just pass the partially filled module objects as
// arguments into the execute function
// hoisted: undefined
}
};
}
RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) {
var loader = this;
var state = this[REGISTER_INTERNAL];
var registry = this.registry[REGISTRY];
return resolveInstantiate(loader, key, parentKey, registry, state)
.then(function (instantiated) {
if (instantiated instanceof ModuleNamespace)
return instantiated;
// resolveInstantiate always returns a load record with a link record and no module value
var link = instantiated.linkRecord;
// if already beaten to done, return
if (!link) {
if (instantiated.module)
return instantiated.module;
throw instantiated.evalError;
}
return deepInstantiateDeps(loader, instantiated, link, registry, state)
.then(function () {
return ensureEvaluate(loader, instantiated, link, registry, state, undefined);
});
});
};
function resolveInstantiate (loader, key, parentKey, registry, state) {
// normalization shortpath for already-normalized key
// could add a plain name filter, but doesn't yet seem necessary for perf
var module = registry[key];
if (module)
return Promise.resolve(module);
var load = state.records[key];
// already linked but not in main registry is ignored
if (load && !load.module) {
if (load.loadError)
return Promise.reject(load.loadError);
return instantiate(loader, load, load.linkRecord, registry, state);
}
return loader.resolve(key, parentKey)
.then(function (resolvedKey) {
// main loader registry always takes preference
module = registry[resolvedKey];
if (module)
return module;
load = state.records[resolvedKey];
// already has a module value but not already in the registry (load.module)
// means it was removed by registry.delete, so we should
// disgard the current load record creating a new one over it
// but keep any existing registration
if (!load || load.module)
load = createLoadRecord(state, resolvedKey, load && load.registration);
if (load.loadError)
return Promise.reject(load.loadError);
var link = load.linkRecord;
if (!link)
return load;
return instantiate(loader, load, link, registry, state);
});
}
function createProcessAnonRegister (loader, load, state) {
return function () {
var lastRegister = state.lastRegister;
if (!lastRegister)
return !!load.registration;
state.lastRegister = undefined;
load.registration = lastRegister;
return true;
};
}
function instantiate (loader, load, link, registry, state) {
return link.instantiatePromise || (link.instantiatePromise =
// if there is already an existing registration, skip running instantiate
(load.registration ? Promise.resolve() : Promise.resolve().then(function () {
state.lastRegister = undefined;
return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state));
}))
.then(function (instantiation) {
// direct module return from instantiate -> we're done
if (instantiation !== undefined) {
if (!(instantiation instanceof ModuleNamespace))
throw new TypeError('Instantiate did not return a valid Module object.');
delete state.records[load.key];
if (loader.trace)
traceLoad(loader, load, link);
return registry[load.key] = instantiation;
}
// run the cached loader.register declaration if there is one
var registration = load.registration;
// clear to allow new registrations for future loads (combined with registry delete)
load.registration = undefined;
if (!registration)
throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.');
link.dependencies = registration[0];
load.importerSetters = [];
link.moduleObj = {};
// process System.registerDynamic declaration
if (registration[2]) {
link.moduleObj.default = link.moduleObj.__useDefault = {};
link.executingRequire = registration[1];
link.execute = registration[2];
}
// process System.register declaration
else {
registerDeclarative(loader, load, link, registration[1]);
}
return load;
})
.catch(function (err) {
load.linkRecord = undefined;
throw load.loadError = load.loadError || LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key);
}));
}
// like resolveInstantiate, but returning load records for linking
function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) {
// normalization shortpaths for already-normalized key
// DISABLED to prioritise consistent resolver calls
// could add a plain name filter, but doesn't yet seem necessary for perf
/* var load = state.records[key];
var module = registry[key];
if (module) {
if (traceDepMap)
traceDepMap[key] = key;
// registry authority check in case module was deleted or replaced in main registry
if (load && load.module && load.module === module)
return load;
else
return module;
}
// already linked but not in main registry is ignored
if (load && !load.module) {
if (traceDepMap)
traceDepMap[key] = key;
return instantiate(loader, load, load.linkRecord, registry, state);
} */
return loader.resolve(key, parentKey)
.then(function (resolvedKey) {
if (traceDepMap)
traceDepMap[key] = resolvedKey;
// normalization shortpaths for already-normalized key
var load = state.records[resolvedKey];
var module = registry[resolvedKey];
// main loader registry always takes preference
if (module && (!load || load.module && module !== load.module))
return module;
if (load && load.loadError)
throw load.loadError;
// already has a module value but not already in the registry (load.module)
// means it was removed by registry.delete, so we should
// disgard the current load record creating a new one over it
// but keep any existing registration
if (!load || !module && load.module)
load = createLoadRecord(state, resolvedKey, load && load.registration);
var link = load.linkRecord;
if (!link)
return load;
return instantiate(loader, load, link, registry, state);
});
}
function traceLoad (loader, load, link) {
loader.loads = loader.loads || {};
loader.loads[load.key] = {
key: load.key,
deps: link.dependencies,
dynamicDeps: [],
depMap: link.depMap || {}
};
}
/*
* Convert a CJS module.exports into a valid object for new Module:
*
* new Module(getEsModule(module.exports))
*
* Sets the default value to the module, while also reading off named exports carefully.
*/
function registerDeclarative (loader, load, link, declare) {
var moduleObj = link.moduleObj;
var importerSetters = load.importerSetters;
var definedExports = false;
// closure especially not based on link to allow link record disposal
var declared = declare.call(envGlobal, function (name, value) {
if (typeof name === 'object') {
var changed = false;
for (var p in name) {
value = name[p];
if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) {
changed = true;
moduleObj[p] = value;
}
}
if (changed === false)
return value;
}
else {
if ((definedExports || name in moduleObj) && moduleObj[name] === value)
return value;
moduleObj[name] = value;
}
for (var i = 0; i < importerSetters.length; i++)
importerSetters[i](moduleObj);
return value;
}, new ContextualLoader(loader, load.key));
link.setters = declared.setters;
link.execute = declared.execute;
if (declared.exports) {
link.moduleObj = moduleObj = declared.exports;
definedExports = true;
}
}
function instantiateDeps (loader, load, link, registry, state) {
if (link.depsInstantiatePromise)
return link.depsInstantiatePromise;
var depsInstantiatePromises = Array(link.dependencies.length);
for (var i = 0; i < link.dependencies.length; i++)
depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {}));
var depsInstantiatePromise = Promise.all(depsInstantiatePromises)
.then(function (dependencyInstantiations) {
link.dependencyInstantiations = dependencyInstantiations;
// run setters to set up bindings to instantiated dependencies
if (link.setters) {
for (var i = 0; i < dependencyInstantiations.length; i++) {
var setter = link.setters[i];
if (setter) {
var instantiation = dependencyInstantiations[i];
if (instantiation instanceof ModuleNamespace) {
setter(instantiation);
}
else {
if (instantiation.loadError)
throw instantiation.loadError;
setter(instantiation.module || instantiation.linkRecord.moduleObj);
// this applies to both es and dynamic registrations
if (instantiation.importerSetters)
instantiation.importerSetters.push(setter);
}
}
}
}
return load;
});
if (loader.trace)
depsInstantiatePromise = depsInstantiatePromise.then(function () {
traceLoad(loader, load, link);
return load;
});
depsInstantiatePromise = depsInstantiatePromise.catch(function (err) {
// throw up the instantiateDeps stack
link.depsInstantiatePromise = undefined;
throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key);
});
depsInstantiatePromise.catch(function () {});
return link.depsInstantiatePromise = depsInstantiatePromise;
}
function deepInstantiateDeps (loader, load, link, registry, state) {
return new Promise(function (resolve, reject) {
var seen = [];
var loadCnt = 0;
function queueLoad (load) {
var link = load.linkRecord;
if (!link)
return;
if (seen.indexOf(load) !== -1)
return;
seen.push(load);
loadCnt++;
instantiateDeps(loader, load, link, registry, state)
.then(processLoad, reject);
}
function processLoad (load) {
loadCnt--;
var link = load.linkRecord;
if (link) {
for (var i = 0; i < link.dependencies.length; i++) {
var depLoad = link.dependencyInstantiations[i];
if (!(depLoad instanceof ModuleNamespace))
queueLoad(depLoad);
}
}
if (loadCnt === 0)
resolve();
}
queueLoad(load);
});
}
/*
* System.register
*/
RegisterLoader$1.prototype.register = function (key, deps, declare) {
var state = this[REGISTER_INTERNAL];
// anonymous modules get stored as lastAnon
if (declare === undefined) {
state.lastRegister = [key, deps, undefined];
}
// everything else registers into the register cache
else {
var load = state.records[key] || createLoadRecord(state, key, undefined);
load.registration = [deps, declare, undefined];
}
};
/*
* System.registerDyanmic
*/
RegisterLoader$1.prototype.registerDynamic = function (key, deps, executingRequire, execute) {
var state = this[REGISTER_INTERNAL];
// anonymous modules get stored as lastAnon
if (typeof key !== 'string') {
state.lastRegister = [key, deps, executingRequire];
}
// everything else registers into the register cache
else {
var load = state.records[key] || createLoadRecord(state, key, undefined);
load.registration = [deps, executingRequire, execute];
}
};
// ContextualLoader class
// backwards-compatible with previous System.register context argument by exposing .id, .key
function ContextualLoader (loader, key) {
this.loader = loader;
this.key = this.id = key;
this.meta = {
url: key
// scriptElement: null
};
}
/*ContextualLoader.prototype.constructor = function () {
throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.');
};*/
ContextualLoader.prototype.import = function (key) {
if (this.loader.trace)
this.loader.loads[this.key].dynamicDeps.push(key);
return this.loader.import(key, this.key);
};
/*ContextualLoader.prototype.resolve = function (key) {
return this.loader.resolve(key, this.key);
};*/
// this is the execution function bound to the Module namespace record
function ensureEvaluate (loader, load, link, registry, state, seen) {
if (load.module)
return load.module;
if (load.evalError)
throw load.evalError;
if (seen && seen.indexOf(load) !== -1)
return load.linkRecord.moduleObj;
// for ES loads we always run ensureEvaluate on top-level, so empty seen is passed regardless
// for dynamic loads, we pass seen if also dynamic
var err = doEvaluate(loader, load, link, registry, state, link.setters ? [] : seen || []);
if (err)
throw err;
return load.module;
}
function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) {
// we can only require from already-known dependencies
return function (name) {
for (var i = 0; i < dependencies.length; i++) {
if (dependencies[i] === name) {
var depLoad = dependencyInstantiations[i];
var module;
if (depLoad instanceof ModuleNamespace)
module = depLoad;
else
module = ensureEvaluate(loader, depLoad, depLoad.linkRecord, registry, state, seen);
return '__useDefault' in module ? module.__useDefault : module;
}
}
throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key);
};
}
// ensures the given es load is evaluated
// returns the error if any
function doEvaluate (loader, load, link, registry, state, seen) {
seen.push(load);
var err;
// es modules evaluate dependencies first
// non es modules explicitly call moduleEvaluate through require
if (link.setters) {
var depLoad, depLink;
for (var i = 0; i < link.dependencies.length; i++) {
depLoad = link.dependencyInstantiations[i];
if (depLoad instanceof ModuleNamespace)
continue;
// custom Module returned from instantiate
depLink = depLoad.linkRecord;
if (depLink && seen.indexOf(depLoad) === -1) {
if (depLoad.evalError)
err = depLoad.evalError;
else
// dynamic / declarative boundaries clear the "seen" list
// we just let cross format circular throw as would happen in real implementations
err = doEvaluate(loader, depLoad, depLink, registry, state, depLink.setters ? seen : []);
}
if (err) {
load.linkRecord = undefined;
load.evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key);
return load.evalError;
}
}
}
// link.execute won't exist for Module returns from instantiate on top-level load
if (link.execute) {
// ES System.register execute
// "this" is null in ES
if (link.setters) {
err = declarativeExecute(link.execute);
}
// System.registerDynamic execute
// "this" is "exports" in CJS
else {
var module = { id: load.key };
var moduleObj = link.moduleObj;
Object.defineProperty(module, 'exports', {
configurable: true,
set: function (exports) {
moduleObj.default = moduleObj.__useDefault = exports;
},
get: function () {
return moduleObj.__useDefault;
}
});
var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen);
// evaluate deps first
if (!link.executingRequire)
for (var i = 0; i < link.dependencies.length; i++)
require(link.dependencies[i]);
err = dynamicExecute(link.execute, require, moduleObj.default, module);
// pick up defineProperty calls to module.exports when we can
if (module.exports !== moduleObj.__useDefault)
moduleObj.default = moduleObj.__useDefault = module.exports;
var moduleDefault = moduleObj.default;
// __esModule flag extension support via lifting
if (moduleDefault && moduleDefault.__esModule) {
for (var p in moduleDefault) {
if (Object.hasOwnProperty.call(moduleDefault, p))
moduleObj[p] = moduleDefault[p];
}
}
}
}
// dispose link record
load.linkRecord = undefined;
if (err)
return load.evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key);
registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);
// if not an esm module, run importer setters and clear them
// this allows dynamic modules to update themselves into es modules
// as soon as execution has completed
if (!link.setters) {
if (load.importerSetters)
for (var i = 0; i < load.importerSetters.length; i++)
load.importerSetters[i](load.module);
load.importerSetters = undefined;
}
}
// {} is the closest we can get to call(undefined)
var nullContext = {};
if (Object.freeze)
Object.freeze(nullContext);
function declarativeExecute (execute) {
try {
execute.call(nullContext);
}
catch (e) {
return e;
}
}
function dynamicExecute (execute, require, exports, module) {
try {
var output = execute.call(envGlobal, require, exports, module);
if (output !== undefined)
module.exports = output;
}
catch (e) {
return e;
}
}
var loader;
// <script type="module"> support
var anonSources = {};
if (typeof document != 'undefined' && document.getElementsByTagName) {
var handleError = function(err) {
// dispatch an error event so that we can display in errors in browsers
// that don't yet support unhandledrejection
if (window.onunhandledrejection === undefined) {
try {
var evt = new Event('error');
} catch (_eventError) {
var evt = document.createEvent('Event');
evt.initEvent('error', true, true);
}
evt.message = err.message;
if (err.fileName) {
evt.filename = err.fileName;
evt.lineno = err.lineNumber;
evt.colno = err.columnNumber;
} else if (err.sourceURL) {
evt.filename = err.sourceURL;
evt.lineno = err.line;
evt.colno = err.column;
}
evt.error = err;
window.dispatchEvent(evt);
}
// throw so it still shows up in the console
throw err;
};
var ready = function() {
document.removeEventListener('DOMContentLoaded', ready, false );
var anonCnt = 0;
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (script.type == 'module' && !script.loaded) {
script.loaded = true;
if (script.src) {
loader.import(script.src).catch(handleError);
}
// anonymous modules supported via a custom naming scheme and registry
else {
var uri = './<anon' + ++anonCnt + '>.js';
if (script.id !== ""){
uri = "./" + script.id;
}
var anonName = resolveIfNotPlain(uri, baseURI);
anonSources[anonName] = script.innerHTML;
loader.import(anonName).catch(handleError);
}
}
}
};
// simple DOM ready
if (document.readyState === 'complete')
setTimeout(ready);
else
document.addEventListener('DOMContentLoaded', ready, false);
}
function BrowserESModuleLoader(baseKey) {
if (baseKey)
this.baseKey = resolveIfNotPlain(baseKey, baseURI) || resolveIfNotPlain('./' + baseKey, baseURI);
RegisterLoader$1.call(this);
var loader = this;
// ensure System.register is available
envGlobal.System = envGlobal.System || {};
if (typeof envGlobal.System.register == 'function')
var prevRegister = envGlobal.System.register;
envGlobal.System.register = function() {
loader.register.apply(loader, arguments);
if (prevRegister)
prevRegister.apply(this, arguments);
};
}
BrowserESModuleLoader.prototype = Object.create(RegisterLoader$1.prototype);
// normalize is never given a relative name like "./x", that part is already handled
BrowserESModuleLoader.prototype[RegisterLoader$1.resolve] = function(key, parent) {
var resolved = RegisterLoader$1.prototype[RegisterLoader$1.resolve].call(this, key, parent || this.baseKey) || key;
if (!resolved)
throw new RangeError('ES module loader does not resolve plain module names, resolving "' + key + '" to ' + parent);
return resolved;
};
function xhrFetch(url, resolve, reject) {
var xhr = new XMLHttpRequest();
var load = function(source) {
resolve(xhr.responseText);
};
var error = function() {
reject(new Error('XHR error' + (xhr.status ? ' (' + xhr.status + (xhr.statusText ? ' ' + xhr.statusText : '') + ')' : '') + ' loading ' + url));
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// in Chrome on file:/// URLs, status is 0
if (xhr.status == 0) {
if (xhr.responseText) {
load();
}
else {
// when responseText is empty, wait for load or error event
// to inform if it is a 404 or empty file
xhr.addEventListener('error', error);
xhr.addEventListener('load', load);
}
}
else if (xhr.status === 200) {
load();
}
else {
error();
}
}
};
xhr.open("GET", url, true);
xhr.send(null);
}
var WorkerPool = function (script, size) {
var current = document.currentScript;
// IE doesn't support currentScript
if (!current) {
// We should be the last loaded script
var scripts = document.getElementsByTagName('script');
current = scripts[scripts.length - 1];
}
script = current.src.substr(0, current.src.lastIndexOf("/")) + "/" + script;
this._workers = new Array(size);
this._ind = 0;
this._size = size;
this._jobs = 0;
this.onmessage = undefined;
this._stopTimeout = undefined;
for (var i = 0; i < size; i++) {
var wrkr = new Worker(script);
wrkr._count = 0;
wrkr._ind = i;
wrkr.onmessage = this._onmessage.bind(this, wrkr);
wrkr.onerror = this._onerror.bind(this);
this._workers[i] = wrkr;
}
this._checkJobs();
};
WorkerPool.prototype = {
postMessage: function (msg) {
if (this._stopTimeout !== undefined) {
clearTimeout(this._stopTimeout);
this._stopTimeout = undefined;
}
var wrkr = this._workers[this._ind % this._size];
wrkr._count++;
this._jobs++;
wrkr.postMessage(msg);
this._ind++;
},
_onmessage: function (wrkr, evt) {
wrkr._count--;
this._jobs--;
this.onmessage(evt, wrkr);
this._checkJobs();
},
_onerror: function(err) {
try {
var evt = new Event('error');
} catch (_eventError) {
var evt = document.createEvent('Event');
evt.initEvent('error', true, true);
}
evt.message = err.message;
evt.filename = err.filename;
evt.lineno = err.lineno;
evt.colno = err.colno;
evt.error = err.error;
window.dispatchEvent(evt);
},
_checkJobs: function () {
if (this._jobs === 0 && this._stopTimeout === undefined) {
// wait for 2s of inactivity before stopping (that should be enough for local loading)
this._stopTimeout = setTimeout(this._stop.bind(this), 2000);
}
},
_stop: function () {
this._workers.forEach(function(wrkr) {
wrkr.terminate();
});
}
};
var promiseMap = new Map();
var babelWorker = new WorkerPool('babel-worker.js', 3);
babelWorker.onmessage = function (evt) {
var promFuncs = promiseMap.get(evt.data.key);
promFuncs.resolve(evt.data);
promiseMap.delete(evt.data.key);
};
// instantiate just needs to run System.register
// so we fetch the source, convert into the Babel System module format, then evaluate it
BrowserESModuleLoader.prototype[RegisterLoader$1.instantiate] = function(key, processAnonRegister) {
var loader = this;
// load as ES with Babel converting into System.register
return new Promise(function(resolve, reject) {
// anonymous module
if (anonSources[key]) {
resolve(anonSources[key]);
anonSources[key] = undefined;
}
// otherwise we fetch
else {
xhrFetch(key, resolve, reject);
}
})
.then(function(source) {
// check our cache first
var cacheEntry = localStorage.getItem(key);
if (cacheEntry) {
cacheEntry = JSON.parse(cacheEntry);
// TODO: store a hash instead
if (cacheEntry.source === source) {
return Promise.resolve({key: key, code: cacheEntry.code, source: cacheEntry.source});
}
}
return new Promise(function (resolve, reject) {
promiseMap.set(key, {resolve: resolve, reject: reject});
babelWorker.postMessage({key: key, source: source});
});
}).then(function (data) {
// evaluate without require, exports and module variables
// we leave module in for now to allow module.require access
try {
var cacheEntry = JSON.stringify({source: data.source, code: data.code});
localStorage.setItem(key, cacheEntry);
} catch (e) {
if (window.console) {
window.console.warn('Unable to cache transpiled version of ' + key + ': ' + e);
}
}
(0, eval)(data.code + '\n//# sourceURL=' + data.key + '!transpiled');
processAnonRegister();
});
};
// create a default loader instance in the browser
if (isBrowser)
loader = new BrowserESModuleLoader();
return BrowserESModuleLoader;
})));
//# sourceMappingURL=browser-es-module-loader.js.map
|