"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexHtmlMiddleware = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const html_1 = require("../../plugins/html");
const send_1 = require("../send");
const constants_1 = require("../../constants");
const devHtmlHook = (html, { path }) => {
    let index = -1;
    html = html
        .replace(html_1.htmlCommentRE, '')
        .replace(html_1.scriptRE, (_match, _openTag, script) => {
        index++;
        if (script) {
            // convert inline <script type="module"> into imported modules
            return `<script type="module" src="${path}?html-proxy&index=${index}.js"></script>`;
        }
        return _match;
    });
    return {
        html,
        tags: [
            {
                tag: 'script',
                attrs: { type: 'module', src: constants_1.CLIENT_PUBLIC_PATH },
                injectTo: 'head-prepend'
            }
        ]
    };
};
function indexHtmlMiddleware(server, plugins) {
    const [preHooks, postHooks] = html_1.resolveHtmlTransforms(plugins);
    return async (req, res, next) => {
        var _a;
        // spa-fallback always redirects to /index.html
        if (((_a = req.url) === null || _a === void 0 ? void 0 : _a.endsWith('.html')) &&
            req.headers['sec-fetch-dest'] !== 'script') {
            let filename;
            if (req.url.startsWith(constants_1.FS_PREFIX)) {
                filename = req.url.slice(constants_1.FS_PREFIX.length);
            }
            else {
                filename = path_1.default.join(server.config.root, req.url.slice(1));
            }
            if (fs_1.default.existsSync(filename)) {
                try {
                    let html = fs_1.default.readFileSync(filename, 'utf-8');
                    // apply transforms
                    html = await html_1.applyHtmlTransforms(html, req.url, filename, [...preHooks, devHtmlHook, ...postHooks], server);
                    return send_1.send(req, res, html, 'html');
                }
                catch (e) {
                    return next(e);
                }
            }
        }
        next();
    };
}
exports.indexHtmlMiddleware = indexHtmlMiddleware;
//# sourceMappingURL=indexHtml.js.map