var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { get, has, unset } from 'lodash-es';
function loadJs(src, name) {
    const script = document.createElement('script');
    script.src = src;
    script.defer = true;
    document.head.appendChild(script);
    const url = new URL(src, location.href);
    return Object.assign(new Promise((resolve, reject) => {
        function windowErrorHandler(err) {
            if (err.filename === url.href) {
                reject(err.error);
                err.preventDefault();
            }
        }
        script.onload = () => {
            window.removeEventListener('error', windowErrorHandler);
            resolve(name ? get(window, name) : undefined);
        };
        script.onerror = (err) => {
            window.removeEventListener('error', windowErrorHandler);
            reject(err);
        };
        window.addEventListener('error', windowErrorHandler);
    }), {
        remove: () => {
            script.remove();
        }
    });
}
export function fetchPreload(preload) {
    return __awaiter(this, void 0, void 0, function* () {
        const tasks = [];
        const _loadJs = (src) => {
            const p = loadJs(src);
            tasks.push(p);
            return p;
        };
        const serialPromise = Promise.all(preload.files.map((file) => {
            return _loadJs(file);
        }));
        yield serialPromise;
        const exported = get(window, preload.name);
        if (has(window, preload.name)) {
            unset(window, preload.name);
        }
        return {
            exported,
            dispose: () => {
                tasks.forEach((t) => t.remove());
            }
        };
    });
}
//# sourceMappingURL=fetch-preload.js.map