"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.serve = void 0;
const cors = require("cors");
const express = require("express");
const createError = require("http-errors");
const path_1 = require("../path");
const ip_1 = require("./ip");
const middleware_1 = require("./middleware");
const port_1 = require("./port");
const compression = require("compression");
function serve(opt = { port: port_1.PORT }) {
    const { port } = opt;
    const app = express();
    app.disable('x-powered-by');
    app.use((req, res, next) => {
        const { url, method } = req;
        console.log(method, url);
        next();
    });
    const corsOptions = {
        origin: '*',
        credentials: true,
        optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    };
    app.set('port', port);
    app.use(cors(corsOptions));
    app.use(compression());
    app.use(express.static(path_1.PATH_PUBLIC));
    app.use((0, middleware_1.files)());
    app.use('*', express.static(path_1.PATH_PUBLIC));
    app.use(function (req, res, next) {
        next(createError(404));
    });
    function onListening() {
        console.log(`http://localhost:${port}`);
        console.log(`http://${ip_1.LOCAL_IP_ADDRESS}:${port}`);
    }
    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }
        const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }
    const server = app.listen(port, onListening);
    server.on('error', onError);
    return server;
}
exports.serve = serve;
//# sourceMappingURL=serve.js.map