"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestiaEditorModule = void 0;
var fs = __importStar(require("fs"));
var NestiaEditorModule;
(function (NestiaEditorModule) {
    var _this = this;
    NestiaEditorModule.setup = function (props) { return __awaiter(_this, void 0, void 0, function () {
        var prefix, adaptor, staticFiles, _a, _b, _c, _d, _loop_1, staticFiles_1, staticFiles_1_1, f, _e, _f, p;
        var _g, _h, e_1, _j, e_2, _k;
        return __generator(this, function (_l) {
            switch (_l.label) {
                case 0:
                    prefix = "/" +
                        [getGlobalPrefix(props.application), props.path]
                            .join("/")
                            .split("/")
                            .filter(function (str) { return str.length !== 0; })
                            .join("/");
                    adaptor = props.application.getHttpAdapter();
                    _g = {
                        path: "/index.html",
                        type: "text/html"
                    };
                    return [4 /*yield*/, getIndex(props)];
                case 1:
                    _a = [
                        (_g.content = _l.sent(),
                            _g)
                    ];
                    _h = {
                        path: "/swagger.json",
                        type: "application/json"
                    };
                    _c = (_b = JSON).stringify;
                    if (!(typeof props.swagger === "string")) return [3 /*break*/, 3];
                    return [4 /*yield*/, getSwagger(props.swagger)];
                case 2:
                    _d = _l.sent();
                    return [3 /*break*/, 4];
                case 3:
                    _d = props.swagger;
                    _l.label = 4;
                case 4:
                    _a = _a.concat([
                        (_h.content = _c.apply(_b, [_d, null,
                            2]),
                            _h)
                    ]);
                    return [4 /*yield*/, getJavaScript()];
                case 5:
                    staticFiles = _a.concat([
                        _l.sent()
                    ]);
                    _loop_1 = function (f) {
                        adaptor.get(prefix + f.path, function (_, res) {
                            res.type(f.type);
                            return res.send(f.content);
                        });
                    };
                    try {
                        for (staticFiles_1 = __values(staticFiles), staticFiles_1_1 = staticFiles_1.next(); !staticFiles_1_1.done; staticFiles_1_1 = staticFiles_1.next()) {
                            f = staticFiles_1_1.value;
                            _loop_1(f);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (staticFiles_1_1 && !staticFiles_1_1.done && (_j = staticFiles_1.return)) _j.call(staticFiles_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    try {
                        for (_e = __values(["", "/"]), _f = _e.next(); !_f.done; _f = _e.next()) {
                            p = _f.value;
                            adaptor.get(prefix + p, function (_, res) {
                                return res.redirect(prefix + "/index.html");
                            });
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    return [2 /*return*/];
            }
        });
    }); };
    var getGlobalPrefix = function (app) {
        var _a;
        return typeof ((_a = app.config) === null || _a === void 0 ? void 0 : _a.globalPrefix) === "string"
            ? app.config.globalPrefix
            : "";
    };
})(NestiaEditorModule || (exports.NestiaEditorModule = NestiaEditorModule = {}));
var getIndex = function (props) { return __awaiter(void 0, void 0, void 0, function () {
    var content;
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, fs.promises.readFile("".concat(__dirname, "/../dist/index.html"), "utf8")];
            case 1:
                content = _b.sent();
                return [2 /*return*/, content
                        .replace("\"@ORGANIZATION/PROJECT\"", JSON.stringify((_a = props.package) !== null && _a !== void 0 ? _a : "@ORGANIZATION/PROJECT"))
                        .replace("window.simulate = false", "window.simulate = ".concat(!!props.simulate))
                        .replace("window.e2e = false", "window.e2e = ".concat(!!props.e2e))];
        }
    });
}); };
var getJavaScript = function () { return __awaiter(void 0, void 0, void 0, function () {
    var directory, path;
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, fs.promises.readdir("".concat(__dirname, "/../dist/assets"))];
            case 1:
                directory = _b.sent();
                path = directory[0];
                if (path === undefined)
                    throw new Error("Unreachable code, no JS file exists.");
                _a = {
                    path: "/assets/".concat(path),
                    type: "application/javascript"
                };
                return [4 /*yield*/, fs.promises.readFile("".concat(__dirname, "/../dist/assets/").concat(path), "utf8")];
            case 2: return [2 /*return*/, (_a.content = _b.sent(),
                    _a)];
        }
    });
}); };
var getSwagger = function (url) { return __awaiter(void 0, void 0, void 0, function () {
    var response;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, fetch(url)];
            case 1:
                response = _a.sent();
                if (response.status !== 200)
                    throw new Error("Failed to fetch Swagger document from ".concat(url));
                return [2 /*return*/, response.json()];
        }
    });
}); };
//# sourceMappingURL=NestiaEditorModule.js.map