//#region src/utils/load.ts
const cache = {};
function createScript(options) {
	const script = document.createElement("script");
	script.type = options.type || "text/javascript";
	script.async = !!options.async;
	script.id = options.id || options.url;
	if (options.url) script.src = options.url;
	if (options.text) script.text = options.text;
	return script;
}
function loadScript(head, script) {
	return new Promise(function(resolve, reject) {
		let done = false;
		script.onload = script.onreadystatechange = function() {
			if (!done && (!script.readyState || script.readyState === "loaded" || script.readyState === "complete")) {
				done = true;
				script.onload = null;
				resolve(script);
			}
		};
		script.onerror = reject;
		head.appendChild(script);
	});
}
function getScriptById(id) {
	const script = id && document.getElementById(id);
	if (script) return script;
}
function getScriptByUrl(url) {
	const script = url && document.querySelector("script[src='" + url + "']");
	if (script) return script;
}
function exec(options, parent) {
	if (typeof options === "string") options = {
		url: options,
		debug: false
	};
	const cacheId = options.id || options.url;
	const cacheEntry = cache[cacheId];
	if (cacheEntry) {
		if (!!options.debug) console.log("load-js: cache hit", cacheId);
		return cacheEntry;
	}
	if (options.allowExternal !== false) {
		let el;
		if (options.id) el = getScriptById(options.id);
		if (!el) el = getScriptByUrl(options.url);
		if (el) {
			const promise = Promise.resolve(el);
			if (cacheId) cache[cacheId] = promise;
			return promise;
		}
	}
	if (!options.url && !options.text) throw new Error("load-js: must provide a url or text to load");
	return loadScript(parent, createScript(options));
}
//#endregion
export { exec as default };
