extensions/load.tstypescript
import { defineExtension } from "./registry";
import type { IExtension } from "./types";

/**
 * Extension module loading options.
 * @property {string} [integrity] - Hash of the module file, load fails if the file was changed on the server.
 * @property {object} [og] - Openglobus module of the app, import * as og from "@openglobus/og".
 * @example
 * // The ruler 1.0.0 was checked and its hash saved. If someone replaces the file on the CDN,
 * // load rejects with "doesn't match the integrity" instead of running the new code in the app.
 * await globe.extensions.load("https://cdn.example.com/og-ruler@1.0.0/index.js", {
 *     integrity: "sha384-..."
 * });
 */
export interface ILoadOptions {
    integrity?: string;
    og?: object;
}

const OG_KEY = Symbol.for("openglobus.og");
const _shims = new WeakMap<object, string>();
let _ogUrl = "";

/** @internal The og entry module url, src/index.ts sets it. */
export function setOgUrl(url: string) {
    _ogUrl = url;
}

function toBase64(buffer: ArrayBuffer): string {
    let s = "";
    const bytes = new Uint8Array(buffer);

    for (let i = 0; i < bytes.length; i++) {
        s += String.fromCharCode(bytes[i]);
    }

    return btoa(s);
}

/**
 * Checks the data against a subresource integrity string, e.g. "sha384-...".
 * @param {ArrayBuffer} data - Data.
 * @param {string} integrity - Integrity, several hashes separated by a space.
 * @returns {Promise<boolean>} -
 */
export async function checkIntegrity(data: ArrayBuffer, integrity: string): Promise<boolean> {
    for (const item of integrity.trim().split(/\s+/)) {
        const m = /^sha(256|384|512)-(.+)$/.exec(item);
        if (!m) {
            throw new Error(`Unsupported integrity "${item}"`);
        }

        const hash = await crypto.subtle.digest(`SHA-${m[1]}`, data);
        if (toBase64(hash) === m[2]) {
            return true;
        }
    }
    return false;
}

/**
 * Points the "@openglobus/og" imports of the module code to the url.
 * @param {string} code - Module code.
 * @param {string} url - Openglobus module url.
 * @returns {string} -
 */
export function replaceOgImport(code: string, url: string): string {
    return code.replace(
        /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s*)(["'])@openglobus\/og\2/g,
        (_, prefix) => prefix + JSON.stringify(url)
    );
}

/**
 * Module that reexports the given og, so the extension takes the classes of the app.
 * @param {Object} og - Openglobus module.
 * @returns {string} - Module url.
 */
export function getOgShim(og: Record<string, any>): string {
    let url = _shims.get(og);
    if (!url) {
        const list: object[] = ((globalThis as any)[OG_KEY] ||= []);
        list.push(og);
        const names = Object.keys(og).filter((n) => n !== "default" && /^[A-Za-z_$][\w$]*$/.test(n));
        const code = [
            `const og = globalThis[Symbol.for("openglobus.og")][${list.length - 1}];`,
            `export const { ${names.join(", ")} } = og;`,
            "export default og;"
        ].join("\n");
        url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
        _shims.set(og, url);
    }
    return url;
}

// The og file the app runs, when og is loaded as a file and not bundled into the app
async function getOgUrl(): Promise<string> {
    const self = _ogUrl ? await import(/* @vite-ignore */ _ogUrl).catch(() => null) : null;
    if (self?.defineExtension !== defineExtension) {
        throw new Error("Openglobus is bundled into the app, pass it: load(url, { og })");
    }
    return _ogUrl;
}

/**
 * Fetches the extension module, checks its integrity and imports it with the og of the app.
 * @param {string} url - Module url.
 * @param {ILoadOptions} [options] - Integrity and og.
 * @param {Function} [importModule] - Module import, for tests.
 * @returns {Promise<IExtension>} -
 */
export async function loadExtension(
    url: string,
    options: ILoadOptions = {},
    importModule: (url: string) => Promise<any> = (u) => import(/* @vite-ignore */ u)
): Promise<IExtension> {
    const response = await fetch(url);

    if (!response.ok) {
        throw new Error(`Can't load extension ${url}: ${response.status}`);
    }

    const data = await response.arrayBuffer();

    if (options.integrity && !(await checkIntegrity(data, options.integrity))) {
        throw new Error(`Extension ${url} doesn't match the integrity`);
    }

    let code = new TextDecoder().decode(data);
    if (code.includes("@openglobus/og")) {
        code = replaceOgImport(code, options.og ? getOgShim(options.og) : await getOgUrl());
    }

    const blobUrl = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
    let module;

    try {
        module = await importModule(blobUrl);
    } finally {
        URL.revokeObjectURL(blobUrl);
    }

    const extension = module.default;
    if (!extension || typeof extension.id !== "string" || typeof extension.activate !== "function") {
        throw new Error(`${url} has no default export with an extension`);
    }

    return extension;
}