fix: preserve historical OpenAPI redirects

This commit is contained in:
dadachann
2026-09-04 11:24:05 +00:00
parent 5fb96b2d26
commit 3422d22808
3 changed files with 40 additions and 4 deletions
+26 -3
View File
@@ -115,11 +115,33 @@ function cloudflarePattern(value, destination = false) {
return value.replace(/:([A-Za-z][A-Za-z0-9_]*)\*/g, destination ? ":splat" : "*");
}
export function renderCloudflareRedirects(docs) {
function slugifyOpenApiSummary(value) {
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
export function collectOpenApiRedirectTargets(spec) {
const targets = new Map();
for (const [apiPath, pathItem] of Object.entries(spec?.paths ?? {})) {
for (const [method, operation] of Object.entries(pathItem)) {
if (!/^(?:get|post|put|patch|delete|head|options)$/i.test(method) || !operation?.summary) continue;
const summarySlug = slugifyOpenApiSummary(operation.summary);
const routePath = apiPath.replaceAll("{", "").replaceAll("}", "");
targets.set(summarySlug, `/en/api-reference${routePath}/${method.toLowerCase()}`);
}
}
return targets;
}
export function renderCloudflareRedirects(docs, englishOpenApiSpec) {
const apiTargets = collectOpenApiRedirectTargets(englishOpenApiSpec);
const lines = ["/ /en/insight/guide 302"];
for (const redirect of docs.redirects ?? []) {
const status = redirect.permanent === false ? 307 : 308;
lines.push(`${cloudflarePattern(redirect.source)} ${cloudflarePattern(redirect.destination, true)} ${status}`);
const destinationSlug = redirect.destination.match(/^\/en\/api-reference\/[^/]+\/([^/:*]+)$/)?.[1];
const destination = destinationSlug && apiTargets.get(destinationSlug)
? apiTargets.get(destinationSlug)
: redirect.destination;
lines.push(`${cloudflarePattern(redirect.source)} ${cloudflarePattern(destination, true)} ${status}`);
}
return `${lines.join("\n")}\n`;
}
@@ -137,6 +159,7 @@ export async function prepareFumapress({ root = ROOT, outRoot = root } = {}) {
if (openapi.length !== LOCALES.length) {
throw new Error(`Expected one nested OpenAPI source per locale, found ${openapi.length}`);
}
const englishOpenApi = JSON.parse(await readFile(path.join(root, openapi.find((item) => item.locale === "en").source), "utf8"));
const contentRoot = path.join(outRoot, "content");
const publicRoot = path.join(outRoot, "public");
@@ -177,7 +200,7 @@ export async function prepareFumapress({ root = ROOT, outRoot = root } = {}) {
}
await cp(path.join(root, "robots.txt"), path.join(publicRoot, "robots.txt"), { force: true });
await writeFile(path.join(publicRoot, "_redirects"), renderCloudflareRedirects(docs));
await writeFile(path.join(publicRoot, "_redirects"), renderCloudflareRedirects(docs, englishOpenApi));
return {
documents: documents.length,