@web/dev-server-core
Version:
42 lines • 1.83 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.historyApiFallbackMiddleware = void 0;
const path_1 = __importDefault(require("path"));
const utils_js_1 = require("../utils.js");
/**
* Serves index.html when a non-file request within the scope of the app index is made.
* This allows SPA routing.
*/
function historyApiFallbackMiddleware(appIndex, rootDir, logger) {
const resolvedAppIndex = path_1.default.resolve(appIndex);
const relativeAppIndex = path_1.default.relative(rootDir, resolvedAppIndex);
const appIndexBrowserPath = `/${(0, utils_js_1.toBrowserPath)(relativeAppIndex)}`;
const appIndexBrowserPathPrefix = path_1.default.dirname(appIndexBrowserPath);
return (ctx, next) => {
if (ctx.method !== 'GET' || path_1.default.extname(ctx.path)) {
// not a GET, or a direct file request
return next();
}
if (!ctx.headers || typeof ctx.headers.accept !== 'string') {
return next();
}
if (ctx.headers.accept.includes('application/json')) {
return next();
}
if (!(ctx.headers.accept.includes('text/html') || ctx.headers.accept.includes('*/*'))) {
return next();
}
if (!ctx.url.startsWith(appIndexBrowserPathPrefix)) {
return next();
}
// rewrite url and let static serve take it further
logger.debug(`Rewriting ${ctx.url} to app index ${appIndexBrowserPath}`);
ctx.url = appIndexBrowserPath;
return next();
};
}
exports.historyApiFallbackMiddleware = historyApiFallbackMiddleware;
//# sourceMappingURL=historyApiFallbackMiddleware.js.map
;