summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/shared.ts
blob: e4aabd8240d0dba3c4500e2532a049062ac8a949 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
import type { AstroConfig, RouteData } from 'astro';
import fs from 'node:fs';

export async function createRedirects(
	config: AstroConfig,
	routes: RouteData[],
	dir: URL,
	entryFile: string,
	type: 'functions' | 'edge-functions' | 'builders' | 'static'
) {
	const kind = type ?? 'functions';
	const dynamicTarget = `/.netlify/${kind}/${entryFile}`;
	const _redirectsURL = new URL('./_redirects', dir);

	const _redirects = createRedirectsFromAstroRoutes({
		config,
		routes,
		dir,
		dynamicTarget,
	});
	const content = _redirects.print();

	// 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, content, 'utf-8');
}