browser-es-module-loader.js 43 KB

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