"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.app = void 0;
const body_parser_1 = __importDefault(require("body-parser"));
const dotenv_1 = __importDefault(require("dotenv"));
const express_1 = __importDefault(require("express"));
const morgan_1 = __importDefault(require("morgan"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const http_1 = __importDefault(require("http"));
const https_1 = __importDefault(require("https"));
const express_session_1 = __importDefault(require("express-session"));
const appInsights = __importStar(require("applicationinsights"));
const proxy_agent_1 = __importDefault(require("proxy-agent"));
const config_1 = require("./config");
const routes_1 = __importDefault(require("./routes"));
const httpsProxyAgent = config_1.PROXY_URL ? new proxy_agent_1.default(config_1.PROXY_URL) : null;
if (config_1.APP_INSIGHTS_CONNECTION_STRING) {
    appInsights
        .setup(config_1.APP_INSIGHTS_CONNECTION_STRING)
        .setAutoDependencyCorrelation(true)
        .setAutoCollectRequests(true)
        .setAutoCollectPerformance(true, true)
        .setAutoCollectExceptions(true)
        .setAutoCollectDependencies(true)
        .setAutoCollectConsole(true)
        .setUseDiskRetryCaching(true)
        .setSendLiveMetrics(false)
        .setDistributedTracingMode(appInsights.DistributedTracingModes.AI)
        .start();
}
if (httpsProxyAgent && process.env.NODE_ENV === 'production') {
    // NOTES:
    //
    // - `defaultClient` property on `appInsights` doesn't exist
    // until `.start` is called
    //
    // - in development on our laptop (as opposed to a server)
    // we don't need to go through a proxy.
    appInsights.defaultClient.config.httpsAgent = httpsProxyAgent;
}
const app = (0, express_1.default)();
exports.app = app;
const server = http_1.default.createServer(app);
dotenv_1.default.load({ path: '.env' });
app.set('port', process.env.PORT || 4200);
app.use('/', express_1.default.static(path_1.default.join(__dirname, '../public')));
app.use(body_parser_1.default.json());
app.use(body_parser_1.default.urlencoded({ extended: true }));
app.use((0, express_session_1.default)({
    store: config_1.SESSION_STORE,
    secret: 'helix',
    resave: true,
    saveUninitialized: true,
    cookie: { expires: new Date(2147483647000) },
}));
if (config_1.APP_INSIGHTS_CONNECTION_STRING) {
    app.use(function appInsightsMiddleWare(req, res, next) {
        appInsights.defaultClient.trackNodeHttpRequest({
            request: req,
            response: res,
        });
        next();
    });
}
app.use((0, morgan_1.default)('dev'));
app.use((req, res, next) => {
    const { headers: { cookie }, } = req;
    if (cookie) {
        const values = cookie.split(';').reduce((res, item) => {
            const data = item.trim().split('=');
            return Object.assign(Object.assign({}, res), { [data[0]]: data[1] });
        }, {});
        res.locals.cookie = values;
    }
    else
        res.locals.cookie = {};
    next();
});
(0, routes_1.default)(app);
app.get('/*', function (_req, res) {
    res.sendFile(path_1.default.join(__dirname, '../public/index.html'));
});
server.listen(app.get('port'), () => {
    console.log(`App is listening on port ${app.get('port')} as HTTP`);
});
process.on('uncaughtException', function (err) {
    console.error('uncaughtException: ' + err.message);
    console.error(err.stack);
});
// setup SSL
if (config_1.SSL.port > 0 && fs_1.default.existsSync(config_1.SSL.keyfile) && fs_1.default.existsSync(config_1.SSL.certfile)) {
    const credentials = {
        key: fs_1.default.readFileSync(config_1.SSL.keyfile, 'ascii'),
        cert: fs_1.default.readFileSync(config_1.SSL.certfile, 'ascii'),
        ca: [],
    };
    if (fs_1.default.existsSync(config_1.SSL.passfile)) {
        credentials.passphrase = fs_1.default.readFileSync(config_1.SSL.passfile, 'ascii').trim();
    }
    if (config_1.SSL.cafiles) {
        config_1.SSL.cafiles.forEach((cafile) => {
            if (fs_1.default.existsSync(cafile)) {
                credentials.ca.push(fs_1.default.readFileSync(cafile, 'ascii'));
            }
        });
    }
    const httpsServer = https_1.default.createServer(credentials, app);
    httpsServer.listen(config_1.SSL.port, () => {
        console.log(`App is listening on port ${config_1.SSL.port} as HTTPS`);
    });
}
//# sourceMappingURL=app.js.map