"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rawFsStaticMiddleware = exports.serveStaticMiddleware = void 0;
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const sirv_1 = __importDefault(require("sirv"));
const constants_1 = require("../../constants");
const utils_1 = require("../../utils");
const sirvOptions = { dev: true, etag: true };
function serveStaticMiddleware(dir, config) {
    const serve = sirv_1.default(dir, sirvOptions);
    return (req, res, next) => {
        const url = req.url;
        // skip import request
        if (utils_1.isImportRequest(url)) {
            return next();
        }
        // only serve the file if it's not an html request
        // so that html requests can fallthrough to our html middleware for
        // special processing
        const ext = path_1.default.extname(utils_1.cleanUrl(url));
        if (!ext || ext === '.html') {
            return next();
        }
        // apply aliases to static requests as well
        if (config) {
            let redirected;
            for (const { find, replacement } of config.alias) {
                const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
                if (matches) {
                    redirected = url.replace(find, replacement);
                    break;
                }
            }
            if (redirected) {
                // dir is pre-normalized to posix style
                if (redirected.startsWith(dir)) {
                    redirected = redirected.slice(dir.length);
                }
                req.url = redirected;
            }
        }
        serve(req, res, next);
    };
}
exports.serveStaticMiddleware = serveStaticMiddleware;
function rawFsStaticMiddleware() {
    const fsRoot = os_1.default.platform() == 'win32' ? process.cwd().split(path_1.default.sep)[0] : '/';
    const serveFromRoot = sirv_1.default(fsRoot, sirvOptions);
    return (req, res, next) => {
        const url = req.url;
        // In some cases (e.g. linked monorepos) files outside of root will
        // reference assets that are also out of served root. In such cases
        // the paths are rewritten to `/@fs/` prefixed paths and must be served by
        // searching based from fs root.
        if (url.startsWith(constants_1.FS_PREFIX)) {
            req.url = url.slice(constants_1.FS_PREFIX.length);
            serveFromRoot(req, res, next);
        }
        else {
            next();
        }
    };
}
exports.rawFsStaticMiddleware = rawFsStaticMiddleware;
//# sourceMappingURL=static.js.map