import { Context } from '../types' function appendToHead( { document }: Context, elementType: string, attributes: Object = {} ): Promise { return new Promise((res, rej) => { const node = document.createElement(elementType) const head = document.getElementsByTagName('head')[0] node.addEventListener('load', res) node.addEventListener('error', rej) for (const key of Object.keys(attributes)) { node.setAttribute(key, attributes[key]) } head.appendChild(node) }) } export function loadStyle(context: Context, href: string) { return appendToHead(context, 'link', { href, rel: 'stylesheet', }) } export function loadScript(context: Context, src: string) { return appendToHead(context, 'script', { src, }) } export async function loadScripts(this: Context, url) { const resp = await fetch(url) const code = await resp.text() // eslint-disable-next-line @typescript-eslint/no-implied-eval const resolver = new Function(` return function ({window, location, history, document}) { with(window.__CONSOLE_OS_GLOBAL_VARS_) { try { ${code} } catch(e) { console.error(e) } } }${ process.env.NODE_ENV === 'development' ? `//@ sourceMappingURL=${url}.map` : '' }`) resolver().call(this.window, { ...this }) } export async function loadCommonJSModule(context: Context, url: string) { const { window } = context const exports = {} Object.assign(window, { exports, module: { exports, }, require: () => {}, }) await context.loadScripts(url) const module = window.module!.exports window.module = window.exports = window.require = undefined return module }