import * as t from "@babel/types";
import { getTagName } from "./parsing/util.js";
import { getLegacyComponentsFolder } from "./plugin-options.js";
export function modifyLegacyCustomComponentImports(path, tracker) {
    const source = path.node.source.value;
    const customFolder = `${getLegacyComponentsFolder()}/`;
    if (!source.includes(customFolder))
        return;
    const specifier = path.node.specifiers[0];
    if (!specifier)
        return;
    tracker.add(specifier.local.name);
    // remap to the built source
    path
        .get("source")
        .replaceWith(t.stringLiteral(source.replace(customFolder, `${customFolder}dist/`)));
    const program = path.scope.getProgramParent()?.path;
    const existingImport = program
        ?.get("body")
        .find((p) => p.isImportDeclaration() &&
        p.node.source.value === "virtual:legacy-wrapper");
    if (existingImport) {
        return;
    }
    program?.unshiftContainer("body", t.importDeclaration([
        t.importSpecifier(t.identifier("wrapCustomComponent"), t.identifier("wrapCustomComponent")),
    ], t.stringLiteral("virtual:legacy-wrapper")));
}
export function modifyLegacyCustomComponentElements(path, tracker) {
    const elementName = getTagName(path.node.openingElement.name);
    if (elementName && tracker.has(elementName)) {
        path
            .get("openingElement")
            .get("name")
            .replaceWith(t.jsxIdentifier(`Wrapped${elementName}`));
        const closingElement = path.get("closingElement");
        if (closingElement) {
            closingElement.replaceWith(t.jsxClosingElement(t.jsxIdentifier(`Wrapped${elementName}`)));
        }
    }
}
export function addLegacyCustomComponentVariables(path, tracker) {
    tracker.forEach((name) => {
        path.unshiftContainer("body", t.variableDeclaration("const", [
            t.variableDeclarator(t.identifier(`Wrapped${name}`), t.callExpression(t.identifier("wrapCustomComponent"), [
                t.identifier(name),
            ])),
        ]));
    });
}
//# sourceMappingURL=custom-components.js.map