"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.vue2FrameworkPlugin = void 0;
const vfs_1 = require("@previewjs/vfs");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const analyze_component_1 = require("./analyze-component");
const infer_component_name_1 = require("./infer-component-name");
const vue_reader_1 = require("./vue-reader");
/** @deprecated */
exports.vue2FrameworkPlugin = {
    isCompatible: async (dependencies) => {
        var _a, _b;
        const version = (await ((_a = dependencies["vue"]) === null || _a === void 0 ? void 0 : _a.readInstalledVersion())) ||
            (await ((_b = dependencies["nuxt"]) === null || _b === void 0 ? void 0 : _b.readInstalledVersion()));
        if (!version) {
            return false;
        }
        return parseInt(version) === 2;
    },
    async create() {
        const { loadNuxtConfig } = await Promise.resolve().then(() => __importStar(require("@nuxt/config")));
        const { createVuePlugin } = await Promise.resolve().then(() => __importStar(require("vite-plugin-vue2")));
        const { extractVueComponents } = await Promise.resolve().then(() => __importStar(require("./extract-component")));
        const previewDirPath = path_1.default.resolve(__dirname, "..", "preview");
        return {
            pluginApiVersion: 3,
            name: "@previewjs/plugin-vue2",
            defaultWrapperPath: "__previewjs__/Wrapper.vue",
            previewDirPath,
            transformReader: (reader, rootDirPath) => (0, vfs_1.createStackedReader)([
                (0, vue_reader_1.createVueTypeScriptReader)(reader),
                (0, vfs_1.createFileSystemReader)({
                    mapping: {
                        from: path_1.default.join(previewDirPath, "modules"),
                        to: path_1.default.join(rootDirPath, "node_modules"),
                    },
                    watch: false,
                }),
            ]),
            detectComponents: async (typeAnalyzer, absoluteFilePaths) => {
                const resolver = typeAnalyzer.analyze(absoluteFilePaths);
                const components = [];
                for (const absoluteFilePath of absoluteFilePaths) {
                    if (absoluteFilePath.endsWith(".vue") &&
                        (await fs_extra_1.default.pathExists(absoluteFilePath))) {
                        components.push({
                            absoluteFilePath,
                            name: (0, infer_component_name_1.inferComponentNameFromVuePath)(absoluteFilePath),
                            offsets: [
                                [0, (await fs_extra_1.default.readFile(absoluteFilePath, "utf-8")).length],
                            ],
                            info: {
                                kind: "component",
                                exported: true,
                                analyze: async () => (0, analyze_component_1.analyzeVueComponentFromTemplate)(typeAnalyzer, absoluteFilePath),
                            },
                        });
                    }
                    else {
                        components.push(...extractVueComponents(resolver, absoluteFilePath));
                    }
                }
                return components;
            },
            viteConfig: () => {
                let rootDirPath;
                return {
                    resolve: {
                        alias: {
                            vue: "vue/dist/vue.esm.js",
                        },
                    },
                    plugins: [
                        createVuePlugin({
                            jsx: true,
                        }),
                        {
                            name: "previewjs:import-vue-without-extension",
                            configResolved(config) {
                                rootDirPath = config.root;
                            },
                            async resolveId(source, importer) {
                                const potentialVueFilePath = path_1.default.join(importer && source.startsWith(".")
                                    ? path_1.default.dirname(importer)
                                    : rootDirPath, source + ".vue");
                                if (await fs_extra_1.default.pathExists(potentialVueFilePath)) {
                                    return potentialVueFilePath;
                                }
                                return null;
                            },
                        },
                        {
                            name: "previewjs:disable-vue-hmr",
                            async transform(code) {
                                // HMR causes issues such as https://github.com/underfin/vite-plugin-vue2/issues/149.
                                // It also prevents preview props from being refreshed.
                                // For now, we disable it entirely.
                                const matchHmr = /\/\* hot reload \*\/(.|\n)*\n}/m;
                                return code.replace(matchHmr, "");
                            },
                        },
                        {
                            name: "previewjs:nuxt-style-resources",
                            async config(config) {
                                try {
                                    const nuxtConfig = await loadNuxtConfig({
                                        rootDir: config.root || process.cwd(),
                                    });
                                    const preprocessorOptions = {};
                                    for (const [key, resources] of Object.entries(nuxtConfig.styleResources || {})) {
                                        const imports = typeof resources === "string" ? [resources] : resources;
                                        if (!Array.isArray(imports)) {
                                            throw new Error(`Unsupported styleResources: ${JSON.stringify(imports)}`);
                                        }
                                        preprocessorOptions[key] = {
                                            additionalData: imports
                                                .map((p) => `@import "${p}";`)
                                                .join("\n"),
                                        };
                                    }
                                    return {
                                        css: {
                                            preprocessorOptions,
                                        },
                                    };
                                }
                                catch (e) {
                                    console.warn(e);
                                    return {};
                                }
                            },
                        },
                        {
                            name: "previewjs:optimize-deps",
                            config: () => ({
                                optimizeDeps: {
                                    include: ["vue"],
                                },
                            }),
                        },
                    ],
                };
            },
            esbuild: {
                jsxFactory: "h",
            },
        };
    },
};
exports.default = exports.vue2FrameworkPlugin;
