import { __awaiter } from "tslib";
import { loadEntry } from './loader';
import { defineModules } from './module';
import TaskCtrl from './task-ctrl';
import { runtime } from '../index';
const defaultOpts = {
    npmFilePrefix: 'https://cdn.jsdelivr.net/npm/',
    npmFilePrefixByScope: {},
    projFilePrefix: '/',
    defineFuncName: 'define',
    extensions: ['.js', '.json'],
    onDependencyMiss: (pkgName, version) => {
        console.error(`The npm package ${pkgName}@${version} is not in the dependency list`);
    },
    debug: false,
    runtime,
    onModuleError: (e) => {
        console.error('lowcode module error ', e);
    },
    onError: (e) => {
        try {
            console.error('Error loading cmd modules', e);
        }
        catch (e) { }
    },
    externals: {},
};
export const taskCtrl = new TaskCtrl();
function loadCmdModuleInteral(entries, opts = {}, taskId) {
    return __awaiter(this, void 0, void 0, function* () {
        opts = Object.assign(Object.assign({}, defaultOpts), opts);
        const loaded = yield loadEntry(entries, opts, taskId);
        const result = {};
        if (!taskCtrl.isActive(taskId)) {
            return result;
        }
        const defined = defineModules(loaded, opts);
        entries.map((ent) => {
            try {
                result[ent] = defined[ent].execute();
            }
            catch (e) {
                opts.onModuleError(e);
            }
        });
        return result;
    });
}
/**
 * Add Wrapper to be cancelable
 */
export function loadCmdModule(entries, opts = {}) {
    const taskId = taskCtrl.add();
    const promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise,
        cancel() {
            taskCtrl.cancel(taskId);
        },
    };
}
export function loadEsModule(entries, opts = {}) {
    const taskId = taskCtrl.add();
    const promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise,
        cancel() {
            taskCtrl.cancel(taskId);
        },
    };
}
