0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/packages/integrations/netlify/src/index.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

62 lines
1.7 KiB
TypeScript
Raw Normal View History

import type { AstroAdapter, AstroIntegration, AstroConfig } from 'astro';
import fs from 'fs';
export function getAdapter(site: string | undefined): AstroAdapter {
return {
name: '@astrojs/netlify',
serverEntrypoint: '@astrojs/netlify/netlify-functions.js',
exports: ['handler'],
2022-03-25 11:08:51 -05:00
args: { site },
};
}
interface NetlifyFunctionsOptions {
dist?: URL;
}
function netlifyFunctions({ dist }: NetlifyFunctionsOptions = {}): AstroIntegration {
let _config: AstroConfig;
let entryFile: string;
return {
name: '@astrojs/netlify',
hooks: {
'astro:config:setup': ({ config }) => {
2022-03-25 11:08:51 -05:00
if (dist) {
config.dist = dist;
} else {
config.dist = new URL('./netlify/', config.projectRoot);
}
},
'astro:config:done': ({ config, setAdapter }) => {
setAdapter(getAdapter(config.buildOptions.site));
_config = config;
},
2022-03-25 11:08:51 -05:00
'astro:build:start': async ({ buildConfig }) => {
entryFile = buildConfig.serverEntry.replace(/\.m?js/, '');
buildConfig.client = _config.dist;
buildConfig.server = new URL('./functions/', _config.dist);
},
'astro:build:done': async ({ routes, dir }) => {
const _redirectsURL = new URL('./_redirects', dir);
// Create the redirects file that is used for routing.
let _redirects = '';
2022-03-25 11:08:51 -05:00
for (const route of routes) {
if (route.pathname) {
_redirects += `
2022-03-25 11:08:51 -05:00
${route.pathname} /.netlify/functions/${entryFile} 200`;
}
}
2022-03-25 11:08:51 -05:00
if (fs.existsSync(_redirects)) {
await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8');
} else {
await fs.promises.writeFile(_redirectsURL, _redirects, 'utf-8');
}
2022-03-25 11:08:51 -05:00
},
},
};
}
2022-03-25 11:08:51 -05:00
export { netlifyFunctions, netlifyFunctions as default };