"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanLowcodeContext = exports.applyLowcode = exports.generateLowcodeModules = exports.lowcodeContext = exports.generateStyleModuleMap = void 0;
const tslib_1 = require("tslib");
const cals_1 = require("@cloudbase/cals");
const base_1 = require("./parser/base");
const index_1 = require("./parser/index");
var lessParser_1 = require("./parser/lessParser");
Object.defineProperty(exports, "generateStyleModuleMap", { enumerable: true, get: function () { return lessParser_1.generateStyleModuleMap; } });
const moduleParsers = {
    [cals_1.ECodeType.LIFECYCLE]: new index_1.LifeCycleParser(),
    [cals_1.ECodeType.COMPUTEDN]: new index_1.ComputedParser(),
    [cals_1.ECodeType.STATE]: new index_1.StateParser(),
    [cals_1.ECodeType.NORMAL_MODULE]: new index_1.NormalModuleParser(),
    [cals_1.ECodeType.HANDLER_FN]: new index_1.HandlerParser(),
    [cals_1.ECodeType.RENDERER]: new index_1.RendererParser(),
};
// 用于页面内通信
let lastError = [];
function addError(e, file) {
    const err = { file, message: e.message || e.stack };
    lastError.push(err);
}
exports.lowcodeContext = {};
// export const widgetsContext = {} as WidgetsContext;
// Just for debug
// Object.defineProperty(window, '__widgetsContext', {
//   get: () => widgetsContext,
// });
Object.defineProperty(window, '__lowcodeContext', {
    get: () => exports.lowcodeContext,
    set: (value) => {
        console.warn('__lowcodeContext can not been set to another value');
    },
});
function quickClone(json) {
    return JSON.parse(JSON.stringify(json));
}
/**
 * Reexecute all low code when updated
 */
function generateLowcodeModules({ runtimeWindow, codeModulesMap = {}, onDependencyMiss = () => { }, dependencies = {}, externals = {}, }) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const allModules = {
            global: quickClone(filterCssCodeModules(codeModulesMap.global)),
        };
        for (let pageId in codeModulesMap) {
            let modules = pageId === 'global'
                ? codeModulesMap[pageId]
                : codeModulesMap[pageId].map((module) => {
                    var _a, _b;
                    return Object.assign(Object.assign({}, module), { path: (_b = (_a = module.path) === null || _a === void 0 ? void 0 : _a.replace) === null || _b === void 0 ? void 0 : _b.call(_a, /^.*?\//, `${pageId}/`) });
                });
            allModules[pageId] = quickClone(filterCssCodeModules(modules));
        }
        const result = yield applyLowcode(allModules, {
            dependencies,
            onDependencyMiss,
            runtimeWindow,
            externals,
        });
        Object.assign(exports.lowcodeContext, result);
        return exports.lowcodeContext;
    });
}
exports.generateLowcodeModules = generateLowcodeModules;
function applyLowcode(allModules, opts) {
    var _a;
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const innerEvalContext = {};
        for (const type in moduleParsers) {
            // eslint-disable-line
            moduleParsers[type].onStart(innerEvalContext);
        }
        (_a = opts.onBeforeParse) === null || _a === void 0 ? void 0 : _a.call(opts, innerEvalContext);
        lastError = [];
        // @ts-ignore
        opts.onCodeError = addError;
        const evaledModules = yield (0, base_1.evalCodeCodules)(allModules, opts);
        // eslint-disable-next-line no-restricted-syntax
        for (const pageId in evaledModules) {
            // eslint-disable-line
            evaledModules[pageId].forEach((m) => {
                const parser = moduleParsers[m.codeType];
                if (!parser) {
                    if (m.codeType !== 'mp_config') {
                        console.error(`Can not handle code module of type ${m.codeType}`);
                    }
                    return;
                }
                try {
                    parser.parseModule(pageId, m);
                }
                catch (e) {
                    console.error('Error parse module', m, e);
                }
            });
        }
        // eslint-disable-next-line no-restricted-syntax
        for (const type in moduleParsers) {
            try {
                moduleParsers[type].onEnd(innerEvalContext);
            }
            catch (e) {
                console.error('Module parser error', e);
            }
        }
        return innerEvalContext;
    });
}
exports.applyLowcode = applyLowcode;
// 去掉css 代码
function filterCssCodeModules(modules = []) {
    return modules.filter((module) => module.codeType !== cals_1.ECodeType.STYLE && module.codeType !== cals_1.ECodeType.THEME);
}
// export function cleanWidgetsContext() {
//   for (let key in widgetsContext) {
//     delete widgetsContext[key];
//   }
// }
function cleanLowcodeContext() {
    // @ts-ignore For debugging
    Object.keys(exports.lowcodeContext).forEach((key) => {
        delete exports.lowcodeContext[key];
    });
}
exports.cleanLowcodeContext = cleanLowcodeContext;
//# sourceMappingURL=lowcode.js.map