import { __awaiter } from "tslib";
import { registerComponent } from "../interfaces";
import { mutate } from "swr";
export const registryUrlRegex = /^https:\/\/qore-apps.qore.dev\/api\/component\/(.+)\/.+\/.+\.js$/i;
export const importCustomComponent = (url) => __awaiter(void 0, void 0, void 0, function* () {
    const url_ = url.startsWith("http://localhost")
        ? `${url}?time=${Date.now()}`
        : url;
    return import(/* webpackIgnore: true */ /* @vite-ignore */ url_).then(({ default: { id, component } }) => {
        const [, author] = registryUrlRegex.exec(url) || [];
        const componentId = author ? [author, id].join("/") : id;
        registerComponent(componentId, component);
        return { id: componentId, component };
    });
});
const packageNameRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
export const isPackage = (name) => packageNameRegex.test(name);
export const importNpmComponent = (name, version = "latest") => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const url = ((_a = process.env.NEXT_PUBLIC_NPM_CDN_URL) !== null && _a !== void 0 ? _a : "")
        .replace("{name}", name)
        .replace("{version}", version);
    return import(/* webpackIgnore: true */ /* @vite-ignore */ url).then(({ default: component }) => {
        mutate(["npm components", name], component);
        registerComponent(name, component);
        return { id: name, component };
    });
});
export const isLocal = (url) => url.startsWith("http://localhost") && url.endsWith(".js");
export const listLocalComponents = () => {
    var _a;
    return ((_a = window.sessionStorage
        .getItem("localComponents")) === null || _a === void 0 ? void 0 : _a.split(",").filter((url) => url.length > 0)) || [];
};
export const importLocalNpmComponent = (url) => __awaiter(void 0, void 0, void 0, function* () {
    return import(
    /* webpackIgnore: true */ /* @vite-ignore */ `${url}?time=${Date.now()}`).then(({ default: { id, component } }) => {
        const componentWithName = Object.assign({ name: id }, component);
        registerComponent(url, componentWithName);
        window.sessionStorage.setItem("localComponents", listLocalComponents().concat(url).join(","));
        return { id, componentWithName };
    });
});
export const removeLocalNpmComponent = (url) => {
    window.sessionStorage.setItem("localComponents", listLocalComponents()
        .filter((u) => u !== url)
        .join(","));
};
//# sourceMappingURL=importComponent.js.map