"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadEsModule = exports.loadCmdModule = exports.taskCtrl = void 0;
var tslib_1 = require("tslib");
var loader_1 = require("./loader");
var module_1 = require("./module");
var task_ctrl_1 = (0, tslib_1.__importDefault)(require("./task-ctrl"));
var index_1 = require("../index");
var defaultOpts = {
    npmFilePrefix: 'https://cdn.jsdelivr.net/npm/',
    npmFilePrefixByScope: {},
    projFilePrefix: '/',
    defineFuncName: 'define',
    extensions: ['.js', '.json'],
    onDependencyMiss: function (pkgName, version) {
        console.error("The npm package " + pkgName + "@" + version + " is not in the dependency list");
    },
    debug: false,
    runtime: index_1.runtime,
    onModuleError: function (e) {
        console.error('lowcode module error ', e);
    },
    onError: function (e) {
        console.error('Error loading cmd modules', e);
    },
};
exports.taskCtrl = new task_ctrl_1.default();
function loadCmdModuleInteral(entries, opts, taskId) {
    if (opts === void 0) { opts = {}; }
    return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
        var loaded, result, defined;
        return (0, tslib_1.__generator)(this, function (_a) {
            switch (_a.label) {
                case 0:
                    opts = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, defaultOpts), opts);
                    return [4 /*yield*/, (0, loader_1.loadEntry)(entries, opts, taskId)];
                case 1:
                    loaded = _a.sent();
                    result = {};
                    if (!exports.taskCtrl.isActive(taskId)) {
                        return [2 /*return*/, result];
                    }
                    defined = (0, module_1.defineModules)(loaded, opts);
                    entries.map(function (ent) {
                        try {
                            result[ent] = defined[ent].execute();
                        }
                        catch (e) {
                            opts.onModuleError(e);
                        }
                    });
                    return [2 /*return*/, result];
            }
        });
    });
}
/**
 * Add Wrapper to be cancelable
 */
function loadCmdModule(entries, opts) {
    if (opts === void 0) { opts = {}; }
    var taskId = exports.taskCtrl.add();
    var promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise: promise,
        cancel: function () {
            exports.taskCtrl.cancel(taskId);
        },
    };
}
exports.loadCmdModule = loadCmdModule;
function loadEsModule(entries, opts) {
    if (opts === void 0) { opts = {}; }
    var taskId = exports.taskCtrl.add();
    var promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise: promise,
        cancel: function () {
            exports.taskCtrl.cancel(taskId);
        },
    };
}
exports.loadEsModule = loadEsModule;
//# sourceMappingURL=index.js.map