gatsby-plugin-cloudflare-pages
Version:
A Gatsby plugin for sites deployed to Cloudflare Pages
59 lines (58 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = require("fs-extra");
const constants_1 = require("./constants");
const toPagesPath = (fromPath, toPath) => {
if (fromPath.match(/\?/)) {
throw new Error(`[gatsby-plugin-cloudflare-pages] Query parameter redirects are not supported by Cloudflare Pages (fromPath: ${fromPath})`);
}
// Modifies wildcard & splat redirects, having no effect on other toPath strings
const pagesToPath = toPath.replace(/\*/, ':splat');
return [fromPath, pagesToPath];
};
// eslint-disable-next-line max-statements
async function writeRedirectsFile(pluginData, redirects, rewrites, reporter) {
const { publicFolder } = pluginData;
if (redirects.length === 0 && rewrites.length === 0) {
reporter.info(`[gatsby-plugin-cloudflare-pages] No redirects or rewrites found`);
return null;
}
const FILE_PATH = publicFolder(`_redirects`);
// Map redirect data to the format Cloudflare Pages expects
// eslint-disable-next-line max-statements
redirects = redirects
.filter((r) => !r.redirectInBrowser)
.map((redirect) => {
const { fromPath, isPermanent, redirectInBrowser, force, toPath, statusCode, ...rest } = redirect;
let status = isPermanent ? `301` : `302`;
if (statusCode)
status = String(statusCode);
if (force)
status = `${status}!`;
const [pagesFromPath, pagesToPath] = toPagesPath(fromPath, toPath);
const pieces = [pagesFromPath, pagesToPath, status];
return pieces.join(` `);
});
rewrites = rewrites.map(({ fromPath, toPath }) => `${fromPath} ${toPath} 200`);
let commentFound = false;
// Websites may also have statically defined redirects
// In that case we should append to them (not overwrite)
// Make sure we aren't just looking at previous build results though
const fileExists = (0, fs_extra_1.existsSync)(FILE_PATH);
let fileContents = ``;
if (fileExists) {
fileContents = await (0, fs_extra_1.readFile)(FILE_PATH, `utf8`);
commentFound = fileContents.includes(constants_1.HEADER_COMMENT);
}
let data;
if (commentFound) {
const [theirs] = fileContents.split(`\n${constants_1.HEADER_COMMENT}\n`);
data = theirs;
}
else {
data = fileContents;
}
reporter.info(`[gatsby-plugin-cloudflare-pages] Creating ${redirects.length} redirect${redirects.length === 1 ? `` : `s`} and ${rewrites.length} rewrite${rewrites.length === 1 ? `` : `s`}...`);
return await (0, fs_extra_1.writeFile)(FILE_PATH, [data, constants_1.HEADER_COMMENT, ...redirects, ...rewrites].join(`\n`));
}
exports.default = writeRedirectsFile;