"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.routeApp = void 0;
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const cors_1 = tslib_1.__importDefault(require("@koa/cors"));
const koa_static_cache_1 = tslib_1.__importDefault(require("koa-static-cache"));
const koa_static_1 = tslib_1.__importDefault(require("koa-static"));
const koa_bodyparser_1 = tslib_1.__importDefault(require("koa-bodyparser"));
const log_1 = require("@/utils/log");
const debug_targets_1 = require("@/router/debug-targets");
const config_1 = require("@/config");
const log = new log_1.Logger('router');
const routeApp = (app) => {
    const { static: staticPath, entry } = global.debugAppArgv;
    app.use(koa_bodyparser_1.default());
    app.use(cors_1.default());
    app.use(async (ctx, next) => {
        var _a, _b;
        try {
            await next();
        }
        catch (e) {
            log.error('koa error: %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
            return (ctx.body = (_b = e) === null || _b === void 0 ? void 0 : _b.stack);
        }
    });
    const debugTargetsRouter = debug_targets_1.getDebugTargetsRouter();
    app.use(debugTargetsRouter.routes()).use(debugTargetsRouter.allowedMethods());
    const defaultStaticOption = {
        buffer: false,
        dynamic: true,
        preload: false,
    };
    // devtools frontend resources
    app.use(koa_static_cache_1.default(path_1.default.join(__dirname, '../public'), {
        ...defaultStaticOption,
        maxAge: 60 * 60,
    }));
    // hmr resources
    app.use(koa_static_1.default(config_1.config.hmrStaticPath));
    // bundle resources
    let servePath;
    if (staticPath)
        servePath = path_1.default.resolve(staticPath);
    else
        servePath = path_1.default.resolve(path_1.default.dirname(entry));
    log.info(`serve bundle: ${entry}; serve folder: ${servePath}`);
    app.use(koa_static_1.default(servePath));
};
exports.routeApp = routeApp;
