Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Vercel adapter #2915

Merged
merged 26 commits into from
Apr 3, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
node_modules/
dist/
.output/
*.tsbuildinfo
.DS_Store
.vercel
Expand Down
5 changes: 4 additions & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
"htmlparser2": "^7.2.0",
"kleur": "^4.1.4",
"magic-string": "^0.25.9",
"micromatch": "^4.0.5",
"micromorph": "^0.1.2",
"mime": "^3.0.0",
"ora": "^6.1.0",
Expand Down Expand Up @@ -143,6 +144,7 @@
"@types/diff": "^5.0.2",
"@types/estree": "^0.0.51",
"@types/html-escaper": "^3.0.0",
"@types/micromatch": "^4.0.2",
"@types/mime": "^2.0.3",
"@types/mocha": "^9.1.0",
"@types/parse5": "^6.0.3",
Expand All @@ -155,7 +157,8 @@
"chai": "^4.3.6",
"cheerio": "^1.0.0-rc.10",
"mocha": "^9.2.2",
"sass": "^1.49.9"
"sass": "^1.49.9",
"type-fest": "^2.12.1"
},
"engines": {
"node": "^14.15.0 || >=16.0.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ export interface AstroConfig extends z.output<typeof AstroConfigSchema> {
adapter: AstroAdapter | undefined;
renderers: AstroRenderer[];
scripts: { stage: InjectedScriptStage; content: string }[];
ignoredPages: string[];
};
}

Expand Down Expand Up @@ -671,6 +672,7 @@ export interface AstroIntegration {
updateConfig: (newConfig: Record<string, any>) => void;
addRenderer: (renderer: AstroRenderer) => void;
injectScript: (stage: InjectedScriptStage, content: string) => void;
ignorePages: (glob: string) => void;
// TODO: Add support for `injectElement()` for full HTML element injection, not just scripts.
// This may require some refactoring of `scripts`, `styles`, and `links` into something
// more generalized. Consider the SSR use-case as well.
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface BuildOptions {

/** `astro build` */
export default async function build(config: AstroConfig, options: BuildOptions = { logging: defaultLogOptions }): Promise<void> {
config = await runHookConfigSetup({ config, command: 'build' });
const builder = new AstroBuilder(config, options);
await builder.build();
}
Expand Down Expand Up @@ -61,7 +62,6 @@ class AstroBuilder {
const timer: Record<string, number> = {};
timer.init = performance.now();
timer.viteStart = performance.now();
this.config = await runHookConfigSetup({ config: this.config, command: 'build' });
const viteConfig = await createVite(
{
mode: this.mode,
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export async function validateConfig(userConfig: any, root: string): Promise<Ast
// First-Pass Validation
const result = {
...(await AstroConfigRelativeSchema.parseAsync(userConfig)),
_ctx: { scripts: [], renderers: [], adapter: undefined },
_ctx: { scripts: [], renderers: [], adapter: undefined, ignoredPages: [] },
};
// Final-Pass Validation (perform checks that require the full config object)
if (!result.experimentalIntegrations && !result.integrations.every((int) => int.name.startsWith('@astrojs/'))) {
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/src/core/routing/manifest/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { LogOptions } from '../../logger';
import fs from 'fs';
import path from 'path';
import { compile } from 'path-to-regexp';
import micromatch from 'micromatch';
import slash from 'slash';
import { fileURLToPath } from 'url';
import { warn } from '../../logger.js';
Expand Down Expand Up @@ -178,11 +179,16 @@ export function createRouteManifest({ config, cwd }: { config: AstroConfig; cwd?
fs.readdirSync(dir).forEach((basename) => {
const resolved = path.join(dir, basename);
const file = slash(path.relative(cwd || fileURLToPath(config.projectRoot), resolved));
const pagePath = slash(path.relative(fileURLToPath(config.pages), resolved));
const isDir = fs.statSync(resolved).isDirectory();

const ext = path.extname(basename);
const name = ext ? basename.slice(0, -ext.length) : basename;

if ((config._ctx?.ignoredPages || []).length > 0 && micromatch.isMatch(pagePath, config._ctx.ignoredPages)) {
return;
}

if (name[0] === '_') {
return;
}
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/integrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ export async function runHookConfigSetup({ config: _config, command }: { config:
updateConfig: (newConfig) => {
updatedConfig = mergeConfig(updatedConfig, newConfig) as AstroConfig;
},
ignorePages: (glob: string) => {
updatedConfig._ctx.ignoredPages.push(glob);
},
});
}
}
Expand Down
44 changes: 44 additions & 0 deletions packages/integrations/vercel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# @astrojs/netlify
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved

Deploy your server-side rendered (SSR) Astro app to [Netlify](https://www.netlify.com/).

Use this adapter in your Astro configuration file:

```js
import { defineConfig } from 'astro/config';
import netlify from '@astrojs/netlify/functions';

export default defineConfig({
adapter: netlify()
});
```

After you build your site the `netlify/` folder will contain [Netlify Functions](https://docs.netlify.com/functions/overview/) in the `netlify/functions/` folder.

Now you can deploy!

```shell
netlify deploy
```

## Configuration

The output folder is configuration with the `dist` property when creating the adapter.

```js
import { defineConfig } from 'astro/config';
import netlify from '@astrojs/netlify/functions';

export default defineConfig({
adapter: netlify({
dist: new URL('./dist/', import.meta.url)
})
});
```

And then point to the dist in your `netlify.toml`:

```toml
[functions]
directory = "dist/functions"
```
33 changes: 33 additions & 0 deletions packages/integrations/vercel/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@astrojs/vercel",
"description": "Deploy your site to Vercel",
"version": "0.0.1",
"type": "module",
"types": "./dist/index.d.ts",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/astro.git",
"directory": "packages/integrations/vercel"
},
"bugs": "https://github.com/withastro/astro/issues",
"homepage": "https://astro.build",
"exports": {
".": "./dist/index.js",
"./package.json": "./package.json"
},
"scripts": {
"build": "astro-scripts build \"src/**/*.ts\" && tsc",
"dev": "astro-scripts dev \"src/**/*.ts\""
},
"dependencies": {
"@astrojs/webapi": "^0.11.0",
"esbuild": "0.14.25",
"globby": "^12.2.0"
},
"devDependencies": {
"astro": "workspace:*",
"astro-scripts": "workspace:*"
}
}
79 changes: 79 additions & 0 deletions packages/integrations/vercel/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import type { AstroIntegration, AstroConfig } from 'astro';
import type { IncomingMessage, ServerResponse } from 'http';
import type { PathLike } from 'fs';

import fs from 'fs/promises';
import { fileURLToPath } from 'url';
import { globby } from 'globby';
import esbuild from 'esbuild';

export type VercelRequest = IncomingMessage;
export type VercelResponse = ServerResponse;
export type VercelHandler = (request: VercelRequest, response: VercelResponse) => void | Promise<void>;

const writeJson = (path: PathLike, data: any) => fs.writeFile(path, JSON.stringify(data), { encoding: 'utf-8' });

const ENDPOINT_GLOB = 'api/**/*.{js,ts,tsx}';

function vercelFunctions(): AstroIntegration {
let _config: AstroConfig;
let output: URL;

return {
name: '@astrojs/vercel',
hooks: {
'astro:config:setup': ({ config, ignorePages }) => {
output = new URL('./.output/', config.projectRoot);
config.dist = new URL('./static/', output);
config.buildOptions.pageUrlFormat = 'directory';
ignorePages(ENDPOINT_GLOB);
},
'astro:config:done': async ({ config }) => {
_config = config;
},
'astro:build:start': async () => {
await fs.rm(output, { recursive: true, force: true });
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved
},
'astro:build:done': async ({ pages }) => {
// Split pages from the rest of files
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved
await Promise.all(
pages.map(async ({ pathname }) => {
const origin = new URL(`./static/${pathname}index.html`, output);
const finalDir = new URL(`./server/pages/${pathname}`, output);

await fs.mkdir(finalDir, { recursive: true });
await fs.copyFile(origin, new URL(`./index.html`, finalDir));
await fs.rm(origin);
})
);

// Routes Manifest
// https://vercel.com/docs/file-system-api#configuration/routes
await writeJson(new URL(`./routes-manifest.json`, output), {
version: 3,
basePath: '/',
pages404: false,
});

const endpoints = await globby([ENDPOINT_GLOB, '!_*'], { onlyFiles: true, cwd: _config.pages });

if (endpoints.length === 0) return;

await esbuild.build({
entryPoints: endpoints.map((endpoint) => new URL(endpoint, _config.pages)).map(fileURLToPath),
outdir: fileURLToPath(new URL('./server/pages/api/', output)),
outbase: fileURLToPath(new URL('./api/', _config.pages)),
inject: [fileURLToPath(new URL('./shims.js', import.meta.url))],
bundle: true,
target: 'node14',
platform: 'node',
format: 'cjs',
});

await writeJson(new URL(`./package.json`, output), { type: 'commonjs' });
},
},
};
}

export default vercelFunctions;
5 changes: 5 additions & 0 deletions packages/integrations/vercel/src/shims.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { polyfill } from '@astrojs/webapi';

polyfill(globalThis, {
exclude: 'window document',
});
10 changes: 10 additions & 0 deletions packages/integrations/vercel/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"allowJs": true,
"module": "ES2020",
"outDir": "./dist",
"target": "ES2020"
}
}
34 changes: 32 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.