import { __assign, __awaiter, __generator } from "tslib";
import { loadEntry } from './loader';
import { defineModules } from './module';
import TaskCtrl from './task-ctrl';
import { runtime } from '../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 ".concat(pkgName, "@").concat(version, " is not in the dependency list"));
    },
    debug: false,
    runtime: runtime,
    onModuleError: function (e) {
        console.error('lowcode module error ', e);
    },
    onError: function (e) {
        try {
            console.error('Error loading cmd modules', e);
        }
        catch (e) { }
    },
    externals: {},
};
export var taskCtrl = new TaskCtrl();
function loadCmdModuleInteral(entries, opts, taskId) {
    if (opts === void 0) { opts = {}; }
    return __awaiter(this, void 0, void 0, function () {
        var loaded, result, defined;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    opts = __assign(__assign({}, defaultOpts), opts);
                    return [4 /*yield*/, loadEntry(entries, opts, taskId)];
                case 1:
                    loaded = _a.sent();
                    result = {};
                    if (!taskCtrl.isActive(taskId)) {
                        return [2 /*return*/, result];
                    }
                    defined = 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
 */
export function loadCmdModule(entries, opts) {
    if (opts === void 0) { opts = {}; }
    var taskId = taskCtrl.add();
    var promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise: promise,
        cancel: function () {
            taskCtrl.cancel(taskId);
        },
    };
}
export function loadEsModule(entries, opts) {
    if (opts === void 0) { opts = {}; }
    var taskId = taskCtrl.add();
    var promise = loadCmdModuleInteral(entries, opts, taskId);
    return {
        promise: promise,
        cancel: function () {
            taskCtrl.cancel(taskId);
        },
    };
}
//# sourceMappingURL=index.js.map