"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePackageName = exports.generateLowcodeImportor = exports.getCompileDirs = exports.deepDealComponentSchemaJson = exports.canUseVite = exports.isOfficialComponentLib = exports.readComponentLibMata = exports.writeLibCommonRes2file = exports.getYyptConfigInfo = exports.getComponentsInfo = exports.getInputProps = exports.removeRequireUncached = exports.requireUncached = exports.JsonToStringWithVariableName = exports.getSelfPackageJson = exports.getCurrentPackageJson = exports.promiseWrapper = exports.getFileNameByUrl = exports.deepDealSchema = exports.simpleDeepClone = exports.deepDeal = exports.isPlainObject = exports.isArray = exports.getMetaInfoBySourceKey = void 0;
// import * as R from 'ramda'
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const style_1 = require("@cloudbase/lowcode-generator/lib/generator/util/style");
const generateFiles_1 = require("./generateFiles");
const cals_1 = require("@cloudbase/cals");
const compare_versions_1 = __importDefault(require("compare-versions"));
const config_1 = require("../config");
const os_1 = __importDefault(require("os"));
var common_1 = require("@cloudbase/lowcode-generator/lib/generator/util/common");
Object.defineProperty(exports, "getMetaInfoBySourceKey", { enumerable: true, get: function () { return common_1.getMetaInfoBySourceKey; } });
Object.defineProperty(exports, "isArray", { enumerable: true, get: function () { return common_1.isArray; } });
Object.defineProperty(exports, "isPlainObject", { enumerable: true, get: function () { return common_1.isPlainObject; } });
Object.defineProperty(exports, "deepDeal", { enumerable: true, get: function () { return common_1.deepDeal; } });
Object.defineProperty(exports, "simpleDeepClone", { enumerable: true, get: function () { return common_1.simpleDeepClone; } });
Object.defineProperty(exports, "deepDealSchema", { enumerable: true, get: function () { return common_1.deepDealSchema; } });
Object.defineProperty(exports, "getFileNameByUrl", { enumerable: true, get: function () { return common_1.getFileNameByUrl; } });
const homeDir = os_1.default.homedir();
const commandConfigPath = path_1.default.join(homeDir, '.warc');
function promiseWrapper(p) {
    return new Promise((resolve) => {
        try {
            p.then((i) => resolve([null, i])).catch((e) => resolve([e, null]));
        }
        catch (e) {
            resolve([e, null]);
        }
    });
}
exports.promiseWrapper = promiseWrapper;
function getCurrentPackageJson() {
    try {
        const { name, version } = fs_extra_1.default.readJSONSync(path_1.default.resolve(process.cwd(), 'package.json'));
        return {
            name,
            version,
        };
    }
    catch (e) { }
}
exports.getCurrentPackageJson = getCurrentPackageJson;
function getSelfPackageJson() {
    try {
        return fs_extra_1.default.readJSONSync(path_1.default.resolve(__dirname, '../../package.json'));
    }
    catch (e) { }
}
exports.getSelfPackageJson = getSelfPackageJson;
function JsonToStringWithVariableName(copyJson, options = {}) {
    let variable = JSON.stringify(copyJson, null, 2).replace(/"%%%(.*?)%%%"/g, (match, expression) => {
        return expression.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\r/g, '\r').replace(/\\n/g, '\n');
    });
    return variable;
}
exports.JsonToStringWithVariableName = JsonToStringWithVariableName;
function requireUncached(module) {
    delete require.cache[require.resolve(module)];
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    return require(module);
}
exports.requireUncached = requireUncached;
function removeRequireUncached(path = '') {
    if (fs_extra_1.default.existsSync(path)) {
        delete require.cache[require.resolve(path)];
    }
}
exports.removeRequireUncached = removeRequireUncached;
function getInputProps(componentsMetaMap) {
    var _a, _b;
    const outputObj = {};
    for (let key in componentsMetaMap) {
        let component = componentsMetaMap[key];
        const sourceKey = key;
        if (component.isComposite) {
            let compItem = component;
            Object.keys(compItem.dataForm || {}).forEach((key) => {
                var _a, _b;
                const inputProps = ((_a = compItem.dataForm[key]) === null || _a === void 0 ? void 0 : _a.inputProp) || ((_b = compItem.dataForm[key]) === null || _b === void 0 ? void 0 : _b.syncProps);
                if (inputProps) {
                    outputObj[sourceKey] = {
                        [key]: inputProps,
                        ...(outputObj[sourceKey] || {}),
                    };
                }
            });
        }
        else {
            const inputProps = ((_a = component === null || component === void 0 ? void 0 : component.meta) === null || _a === void 0 ? void 0 : _a.inputProps) || ((_b = component === null || component === void 0 ? void 0 : component.meta) === null || _b === void 0 ? void 0 : _b.syncProps);
            if (inputProps) {
                outputObj[sourceKey] = inputProps;
            }
        }
    }
    return outputObj;
}
exports.getInputProps = getInputProps;
async function getComponentsInfo(appBuildDir, dependencies) {
    const outputObj = {};
    await Promise.all(dependencies.map(async ({ name: materialName, version, components = [], isComposite }) => {
        if (isComposite) {
            components.forEach((component) => {
                let { lowCodes, componentInstances, ...compItem } = component;
                const sourceKey = `${materialName}:${compItem.name}`;
                outputObj[sourceKey] = {
                    isComposite,
                    ...compItem,
                };
            });
        }
        else {
            const materialComponentsPath = path_1.default.resolve(appBuildDir, `src/libraries/${materialName}@${version}/components`);
            const componentLibPath = path_1.default.resolve(appBuildDir, `src/libraries/${materialName}@${version}`);
            const meta = readComponentLibMata(componentLibPath);
            if (meta) {
                const { components: componentsMap } = meta;
                for (let name in componentsMap) {
                    const sourceKey = `${materialName}:${name}`;
                    let metaJson = componentsMap[name];
                    outputObj[sourceKey] = { isComposite, ...metaJson };
                }
            }
            else {
                // 老格式，需要从子目录下读取
                const components = await fs_extra_1.default.readdir(materialComponentsPath);
                await Promise.all(components.map(async (name) => {
                    const sourceKey = `${materialName}:${name}`;
                    const componentMetaPath = `${materialComponentsPath}/${name}/meta.json`;
                    let metaJson = {
                        name,
                        meta: await fs_extra_1.default.readJson(componentMetaPath),
                    };
                    outputObj[sourceKey] = { isComposite, ...metaJson };
                }));
            }
        }
    }));
    return outputObj;
}
exports.getComponentsInfo = getComponentsInfo;
async function getYyptConfigInfo(extraData) {
    let configJson;
    try {
        configJson = await fs_extra_1.default.readJSON(commandConfigPath);
    }
    catch (e) { }
    configJson = configJson || {
        yyptAppKey: '',
        reportUrl: '',
        stopReport: false,
    };
    if (!extraData || !extraData.operationService) {
        extraData = extraData || {};
        extraData.operationService = extraData.operationService || {};
    }
    const yyptAppKey = configJson.yyptAppKey || extraData.operationService.extAppId || '';
    const reportUrl = configJson.reportUrl || extraData.operationService.reportUrl || '';
    const stopReport = configJson.stopReport === 'true' || !extraData.operationService.yyptEnabled;
    return {
        yyptAppKey,
        reportUrl,
        stopReport,
    };
}
exports.getYyptConfigInfo = getYyptConfigInfo;
async function writeLibCommonRes2file(gItem, codeDir) {
    const { compLibCommonResource } = gItem;
    const libCommonResFiles = [];
    libCommonResFiles.push({
        path: path_1.default.join(codeDir, `class.${codeDir.includes('/mp/') ? 'wxss' : 'less'}`),
        code: compLibCommonResource
            ? await (0, style_1.processLess)(`
        ${compLibCommonResource.theme.variable || ''}
        ${compLibCommonResource.class || ''}
        ${compLibCommonResource.theme.class || ''}
        `)
            : '',
    }, {
        path: path_1.default.join(codeDir, 'const.js'),
        code: compLibCommonResource ? compLibCommonResource.const.code : '',
    }, {
        path: path_1.default.join(codeDir, 'tools.js'),
        code: compLibCommonResource ? compLibCommonResource.tools.code : '',
    });
    await Promise.all(libCommonResFiles.map((item) => (0, generateFiles_1.writeFile)(item.path, item.code)));
}
exports.writeLibCommonRes2file = writeLibCommonRes2file;
function readComponentLibMata(libDir) {
    var _a;
    let metaPath = path_1.default.join(libDir, 'meta.json');
    let isExistsMeta = fs_extra_1.default.existsSync(metaPath);
    if (!isExistsMeta) {
        return null;
    }
    let meta = fs_extra_1.default.readJSONSync(metaPath);
    let [major] = ((_a = meta === null || meta === void 0 ? void 0 : meta.schemaVersion) === null || _a === void 0 ? void 0 : _a.split('.')) || [];
    const originComponentMetaMap = meta.components;
    if (Number(major) >= 2) {
        meta = (0, cals_1.deserializeComponentLibraryMeta)(meta);
    }
    for (let key in meta.components) {
        meta.components[key] = {
            ...originComponentMetaMap[key],
            name: key,
            meta: meta.components[key],
        };
    }
    return meta;
}
exports.readComponentLibMata = readComponentLibMata;
const _OFFICIAL_COMPONENT_LIB = {
    [config_1.OFFICIAL_LIB_KEY]: ['*'],
    CLOUDBASE_BUSSINESS: ['1627377179261'],
};
function isOfficialComponentLib(name, version) {
    var _a, _b;
    return !!((_a = _OFFICIAL_COMPONENT_LIB[name]) === null || _a === void 0 ? void 0 : _a.includes(version)) || ((_b = _OFFICIAL_COMPONENT_LIB[name]) === null || _b === void 0 ? void 0 : _b.includes('*'));
}
exports.isOfficialComponentLib = isOfficialComponentLib;
/**
 * 能否使用 Vite
 * @param mode 当前 mode 模式
 */
function canUseVite(mode, devTool) {
    return false;
    return devTool === 'vite' && mode !== 'production' && (0, compare_versions_1.default)(process.version, '12.0.0') >= 0;
}
exports.canUseVite = canUseVite;
function deepDealComponentSchemaJson(schema, dealFn) {
    if (!schema)
        return;
    dealFn(schema);
    if (schema.properties) {
        const properties = schema.properties || {};
        Object.keys(properties).forEach((key) => {
            const childSchema = properties[key];
            deepDealComponentSchemaJson(childSchema, dealFn);
        });
    }
}
exports.deepDealComponentSchemaJson = deepDealComponentSchemaJson;
function getCompileDirs(appKey = 'test') {
    const materialsDir = path_1.default.join(os_1.default.homedir(), '.weapps-materials');
    const rootBuildDir = path_1.default.join(os_1.default.homedir(), '.weapps-build');
    const appBuildDir = path_1.default.join(rootBuildDir, appKey);
    return {
        rootBuildDir,
        appBuildDir,
        materialsDir,
    };
}
exports.getCompileDirs = getCompileDirs;
function generateLowcodeImportor(lowcodes = []) {
    const importor = {
        state: false,
        computed: false,
        lifecycle: false,
        common: false,
        styles: [],
    };
    lowcodes.forEach((mod) => {
        switch (mod.type) {
            case cals_1.ECodeType.STYLE: {
                importor.styles.push(mod);
                break;
            }
            case cals_1.ECodeType.LIFECYCLE: {
                importor.lifecycle = true;
                break;
            }
            case cals_1.ECodeType.STATE: {
                importor.state = true;
                break;
            }
            case cals_1.ECodeType.COMPUTEDN: {
                importor.computed = true;
                break;
            }
            case cals_1.ECodeType.NORMAL_MODULE: {
                importor.common = true;
                break;
            }
        }
    });
    return importor;
}
exports.generateLowcodeImportor = generateLowcodeImportor;
function normalizePackageName(packageName) {
    if (!packageName) {
        return packageName;
    }
    const matched = packageName.match(/packages\/(.*)?/);
    if (matched) {
        return matched[1];
    }
    return packageName;
}
exports.normalizePackageName = normalizePackageName;
