astro/packages/integrations/vercel/src/index.ts

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

67 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-03-31 18:31:56 +00:00
import type { AstroAdapter, AstroConfig, AstroIntegration } from 'astro';
2022-03-28 13:05:55 +00:00
import type { PathLike } from 'fs';
2022-03-28 20:55:03 +00:00
import fs from 'fs/promises';
2022-03-31 02:08:39 +00:00
import esbuild from 'esbuild';
import { fileURLToPath } from 'url';
2022-03-28 13:05:55 +00:00
2022-04-02 21:56:13 +00:00
const writeJson = (path: PathLike, data: any) =>
fs.writeFile(path, JSON.stringify(data), { encoding: 'utf-8' });
2022-03-28 13:05:55 +00:00
2022-03-31 02:08:39 +00:00
const ENTRYFILE = '__astro_entry';
2022-03-30 02:01:37 +00:00
export function getAdapter(): AstroAdapter {
return {
name: '@astrojs/vercel',
serverEntrypoint: '@astrojs/vercel/server-entrypoint',
exports: ['_default'],
};
}
2022-03-28 18:13:14 +00:00
2022-03-30 02:01:37 +00:00
export default function vercel(): AstroIntegration {
2022-03-31 18:31:56 +00:00
let _config: AstroConfig;
2022-03-28 13:05:55 +00:00
return {
name: '@astrojs/vercel',
hooks: {
2022-03-30 02:01:37 +00:00
'astro:config:setup': ({ config }) => {
config.dist = new URL('./.output/', config.projectRoot);
2022-03-28 13:05:55 +00:00
config.buildOptions.pageUrlFormat = 'directory';
},
2022-03-31 18:31:56 +00:00
'astro:config:done': ({ setAdapter, config }) => {
2022-03-30 02:01:37 +00:00
setAdapter(getAdapter());
2022-03-31 18:31:56 +00:00
_config = config;
2022-03-28 13:05:55 +00:00
},
2022-03-31 18:31:56 +00:00
'astro:build:start': async ({ buildConfig }) => {
2022-03-31 02:08:39 +00:00
buildConfig.serverEntry = `${ENTRYFILE}.mjs`;
2022-03-31 18:31:56 +00:00
buildConfig.client = new URL('./static/', _config.dist);
buildConfig.server = new URL('./server/pages/', _config.dist);
2022-03-28 13:05:55 +00:00
},
2022-03-30 02:01:37 +00:00
'astro:build:done': async ({ dir, routes }) => {
2022-03-31 02:08:39 +00:00
const pagesDir = new URL('./server/pages/', dir);
2022-03-31 18:37:33 +00:00
// Convert server entry to CommonJS
2022-03-31 02:08:39 +00:00
await esbuild.build({
entryPoints: [fileURLToPath(new URL(`./${ENTRYFILE}.mjs`, pagesDir))],
outfile: fileURLToPath(new URL(`./${ENTRYFILE}.js`, pagesDir)),
bundle: true,
format: 'cjs',
platform: 'node',
target: 'node14',
2022-03-30 02:01:37 +00:00
});
2022-03-31 02:08:39 +00:00
await fs.rm(new URL(`./${ENTRYFILE}.mjs`, pagesDir));
2022-03-28 13:05:55 +00:00
// Routes Manifest
// https://vercel.com/docs/file-system-api#configuration/routes
2022-03-30 02:01:37 +00:00
await writeJson(new URL(`./routes-manifest.json`, dir), {
2022-03-28 13:05:55 +00:00
version: 3,
basePath: '/',
pages404: false,
2022-03-30 02:01:37 +00:00
rewrites: routes.map((route) => ({
source: route.pathname,
2022-03-31 02:08:39 +00:00
destination: `/${ENTRYFILE}`,
2022-03-30 02:01:37 +00:00
})),
2022-03-28 13:05:55 +00:00
});
},
},
};
}