2022-05-11 10:13:23 -05:00
|
|
|
import type { RouteData } from 'astro';
|
|
|
|
import fs from 'fs';
|
|
|
|
|
|
|
|
export async function createRedirects(
|
2022-05-11 10:14:43 -05:00
|
|
|
routes: RouteData[],
|
|
|
|
dir: URL,
|
|
|
|
entryFile: string,
|
|
|
|
edge: boolean
|
|
|
|
) {
|
|
|
|
const _redirectsURL = new URL('./_redirects', dir);
|
|
|
|
const kind = edge ? 'edge-functions' : 'functions';
|
2022-05-11 10:13:23 -05:00
|
|
|
|
2022-05-11 10:14:43 -05:00
|
|
|
// Create the redirects file that is used for routing.
|
|
|
|
let _redirects = '';
|
|
|
|
for (const route of routes) {
|
|
|
|
if (route.pathname) {
|
|
|
|
_redirects += `
|
2022-05-11 10:13:23 -05:00
|
|
|
${route.pathname} /.netlify/${kind}/${entryFile} 200`;
|
2022-08-11 18:26:32 -05:00
|
|
|
|
2022-08-11 18:29:45 -05:00
|
|
|
if (route.route === '/404') {
|
2022-08-11 18:26:32 -05:00
|
|
|
_redirects += `
|
|
|
|
/* /.netlify/${kind}/${entryFile} 404`;
|
|
|
|
}
|
2022-05-11 10:14:43 -05:00
|
|
|
} else {
|
|
|
|
const pattern =
|
|
|
|
'/' + route.segments.map(([part]) => (part.dynamic ? '*' : part.content)).join('/');
|
|
|
|
_redirects += `
|
2022-05-11 10:13:23 -05:00
|
|
|
${pattern} /.netlify/${kind}/${entryFile} 200`;
|
2022-05-11 10:14:43 -05:00
|
|
|
}
|
|
|
|
}
|
2022-05-11 10:13:23 -05:00
|
|
|
|
2022-05-11 10:14:43 -05:00
|
|
|
// Always use appendFile() because the redirects file could already exist,
|
|
|
|
// e.g. due to a `/public/_redirects` file that got copied to the output dir.
|
|
|
|
// If the file does not exist yet, appendFile() automatically creates it.
|
|
|
|
await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8');
|
|
|
|
}
|