/*
 * Supports loading System.register via script tag injection
 */

import { systemJSPrototype } from '../system-core';

let err;
if (typeof window !== 'undefined')
  window.addEventListener('error', function (e) {
    err = e.error;
  });

const systemRegister = systemJSPrototype.register;
systemJSPrototype.register = function (deps, declare) {
  err = undefined;
  systemRegister.call(this, deps, declare);
};

systemJSPrototype.instantiate = function (url, firstParentUrl) {
  const loader = this;
  if (url.endsWith('.json')) {
    return fetch(url).then(function (resp) {
      return resp.text();
    }).then(function (source) {
      return [[], function(_export) {
        return {execute: function() {_export('default', JSON.parse(source))}};
      }];
    });
  } else {
    return new Promise(function (resolve, reject) {
      const script = document.createElement('script');
      script.charset = 'utf-8';
      script.async = true;
      script.crossOrigin = 'anonymous';
      script.addEventListener('error', function () {
        reject(Error('Error loading ' + url + (firstParentUrl ? ' from ' + firstParentUrl : '')));
      });
      script.addEventListener('load', function () {
        document.head.removeChild(script);
        // Note URL normalization issues are going to be a careful concern here
        if (err) {
          reject(err);
          return err = undefined;
        }
        else {
          resolve(loader.getRegister());
        }
      });
      script.src = url;
      document.head.appendChild(script);
    });
  }
};
@@ -119,128 +119,8 @@
 ';%0A%0A
-let err;%0Aif (typeof window !== 'undefined')%0A  window.addEventListener('error', function (e) %7B%0A    err = e.error;%0A  %7D);%0A%0A
 cons
@@ -705,24 +705,214 @@
 , reject) %7B%0A
+      let err;%0A%0A      function windowErrorListener(evt) %7B%0A        if (evt.filename === url)%0A          err = evt.error;%0A      %7D%0A%0A      window.addEventListener('error', windowErrorListener);%0A%0A
       const 
@@ -1098,32 +1098,98 @@
 , function () %7B%0A
+        window.removeEventListener('error', windowErrorListener);%0A
         reject(E
@@ -1345,122 +1345,283 @@
     
-document.head.removeChild(script);%0A        // Note URL normalization issues are going to be a careful concern here
+window.removeEventListener('error', windowErrorListener);%0A        document.head.removeChild(script);%0A        // Note that if an error occurs that isn't caught by this if statement,%0A        // that getRegister will return null and a %22did not instantiate%22 error will be thrown.
 %0A   
@@ -1663,42 +1663,8 @@
 r);%0A
-          return err = undefined;%0A
     

Fix for System.import() rejecting for other script's errors. Resolves #1960 (#1961)