Compare commits

...

7 Commits

Author SHA1 Message Date
Steven
eed39913e1 Publish Stable
- @vercel/build-utils@4.2.0
 - vercel@25.2.0
 - @vercel/client@12.0.2
 - @vercel/edge@0.0.1
 - @vercel/frameworks@1.0.2
 - @vercel/go@2.0.2
 - @vercel/next@3.1.0
 - @vercel/node@2.3.0
 - @vercel/python@3.0.2
 - @vercel/redwood@1.0.2
 - @vercel/remix@1.0.2
 - @vercel/routing-utils@1.13.5
 - @vercel/ruby@1.3.10
 - @vercel/static-build@1.0.2
2022-06-28 10:15:33 -04:00
Gal Schlezinger
03e9047bc9 [@vercel/edge] add header helpers (#8036)
* [@vercel/edge] add header helpers

* rename getIp => ipAddress, getGeo => geolocation, as suggested by @kikobeats
2022-06-28 11:26:18 +02:00
Nathan Rajlich
0e35205bf1 [cli][dev][node] Support matchers config for Middleware in vc dev (#8033)
Adds support for `config.matchers` exported property in Middleware during `vc dev`.
2022-06-28 08:34:48 +00:00
Steven
e42fe34c4a [tests] Bump turbo to 1.3.1 (#8011)
https://turborepo.org/blog/turbo-1-3-0
2022-06-28 04:48:35 +00:00
Sean Massa
3ece7ac969 [cli][node] make error handling of edge functions consistent with serverless functions in vc dev (#8007)
When edge functions error, they were showing a basic text response instead of the error template. They were also sending a 502 status code instead of a 500.

This PR makes the error handling of Edge Functions consistent with Serverless Functions when executed through `vc dev`. If we want to update the error templates themselves, we can do that in a separate PR.

**Note:** Production currently treats Edge Function errors differently from Serverless Function errors, but that's a known issue that will be resolved.

---

*I deleted the original outputs (terminal and browser screenshots) because they are out of date and added a lot of content to this page. See my latest comment for updated examples.*
2022-06-28 04:12:21 +00:00
Nathan Rajlich
4f832acf90 [remix] Don't depend on @remix-run/vercel (#8029)
Instead, just add it to the project's `package.json` file before installing the dependencies.

Fixes warning about missing peer dependencies when installing CLI.

<img width="409" alt="CleanShot 2022-05-22 at 09 40 09@2x" src="https://user-images.githubusercontent.com/71256/176084428-79e964b3-8b20-416d-bf3f-c5bd36f4b0ff.png">

Now, a warning is shown in the Deployment build logs, saying that the dep was added, but that the user should commit the change:

<img width="931" alt="Screen Shot 2022-06-27 at 8 15 19 PM" src="https://user-images.githubusercontent.com/71256/176084377-dab5f7d3-4e9f-4bf6-baee-63708b65f218.png">
2022-06-28 03:29:50 +00:00
Matthew Stanciu
918726e01d [cli] Support "http:" scheme in vc bisect (#8023)
`vc bisect` currently prepends `https://` to a passed-in url if it doesn't begin with https—which means that if someone passes in a url that begins with `http://`, it'll turn the url into `https://http://url.com`. This PR fixes this.

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2022-06-28 02:15:59 +00:00
41 changed files with 896 additions and 758 deletions

4
.prettierignore Normal file
View File

@@ -0,0 +1,4 @@
# https://prettier.io/docs/en/ignore.html
# ignore this file with an intentional syntax error
packages/cli/test/dev/fixtures/edge-function-error/api/edge-error-syntax.js

View File

@@ -31,7 +31,7 @@
"prettier": "2.6.2",
"ts-eager": "2.0.2",
"ts-jest": "28.0.5",
"turbo": "1.2.14"
"turbo": "1.3.1"
},
"scripts": {
"lerna": "lerna",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "4.1.1-canary.1",
"version": "4.2.0",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",
@@ -31,7 +31,7 @@
"@types/node-fetch": "^2.1.6",
"@types/semver": "6.0.0",
"@types/yazl": "2.4.2",
"@vercel/frameworks": "1.0.2-canary.0",
"@vercel/frameworks": "1.0.2",
"@vercel/ncc": "0.24.0",
"aggregate-error": "3.0.1",
"async-retry": "1.2.3",

View File

@@ -1,6 +1,6 @@
{
"name": "vercel",
"version": "25.1.1-canary.11",
"version": "25.2.0",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Vercel",
@@ -42,15 +42,15 @@
"node": ">= 14"
},
"dependencies": {
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/go": "2.0.2-canary.1",
"@vercel/next": "3.0.5",
"@vercel/node": "2.2.1-canary.1",
"@vercel/python": "3.0.2-canary.1",
"@vercel/redwood": "1.0.2-canary.1",
"@vercel/remix": "1.0.2-canary.1",
"@vercel/ruby": "1.3.10-canary.1",
"@vercel/static-build": "1.0.2-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/go": "2.0.2",
"@vercel/next": "3.1.0",
"@vercel/node": "2.3.0",
"@vercel/python": "3.0.2",
"@vercel/redwood": "1.0.2",
"@vercel/remix": "1.0.2",
"@vercel/ruby": "1.3.10",
"@vercel/static-build": "1.0.2",
"update-notifier": "5.1.0"
},
"devDependencies": {
@@ -95,8 +95,8 @@
"@types/which": "1.3.2",
"@types/write-json-file": "2.2.1",
"@types/yauzl-promise": "2.1.0",
"@vercel/client": "12.0.2-canary.1",
"@vercel/frameworks": "1.0.2-canary.0",
"@vercel/client": "12.0.2",
"@vercel/frameworks": "1.0.2",
"@vercel/ncc": "0.24.0",
"@zeit/fun": "0.11.2",
"@zeit/source-map-support": "0.6.2",

View File

@@ -16,6 +16,7 @@ import Client from '../../util/client';
import { getPkgName } from '../../util/pkg-name';
import { Output } from '../../util/output';
import { Deployment, PaginationOptions } from '../../types';
import { normalizeURL } from '../../util/bisect/normalize-url';
interface DeploymentV6
extends Pick<
@@ -97,9 +98,7 @@ export default async function main(client: Client): Promise<number> {
run = resolve(run);
}
if (!bad.startsWith('https://')) {
bad = `https://${bad}`;
}
bad = normalizeURL(bad);
let parsed = parse(bad);
if (!parsed.hostname) {
output.error('Invalid input: no hostname provided');
@@ -120,9 +119,7 @@ export default async function main(client: Client): Promise<number> {
const badDeploymentPromise = getDeployment(client, bad).catch(err => err);
if (!good.startsWith('https://')) {
good = `https://${good}`;
}
good = normalizeURL(good);
parsed = parse(good);
if (!parsed.hostname) {
output.error('Invalid input: no hostname provided');

View File

@@ -0,0 +1,7 @@
function hasScheme(url: string): Boolean {
return url.startsWith('http://') || url.startsWith('https://');
}
export function normalizeURL(url: string): string {
return hasScheme(url) ? url : `https://${url}`;
}

View File

@@ -1108,6 +1108,7 @@ export default class DevServer {
view = errorTemplate({
http_status_code: statusCode,
http_status_description,
error_code,
request_id: requestId,
});
}
@@ -1405,6 +1406,7 @@ export default class DevServer {
let statusCode: number | undefined;
let prevUrl = req.url;
let prevHeaders: HttpHeadersConfig = {};
let middlewarePid: number | undefined;
// Run the middleware file, if present, and apply any
// mutations to the incoming request based on the
@@ -1428,45 +1430,25 @@ export default class DevServer {
meta: {
isDev: true,
devCacheDir,
requestUrl: req.url,
env: { ...envConfigs.runEnv },
buildEnv: { ...envConfigs.buildEnv },
},
});
} catch (err) {
// `startDevServer()` threw an error. Most likely this means the dev
// server process exited before sending the port information message
// (missing dependency at runtime, for example).
if (err.code === 'ENOENT') {
err.message = `Command not found: ${chalk.cyan(
err.path,
...err.spawnargs
)}\nPlease ensure that ${cmd(err.path)} is properly installed`;
err.link = 'https://vercel.link/command-not-found';
}
await this.sendError(
req,
res,
requestId,
'EDGE_FUNCTION_INVOCATION_FAILED',
500
);
return;
}
if (startMiddlewareResult) {
const { port, pid } = startMiddlewareResult;
middlewarePid = pid;
this.devServerPids.add(pid);
if (startMiddlewareResult) {
const { port, pid } = startMiddlewareResult;
this.devServerPids.add(pid);
const middlewareReqHeaders = nodeHeadersToFetchHeaders(req.headers);
const middlewareReqHeaders = nodeHeadersToFetchHeaders(req.headers);
// Add the Vercel platform proxy request headers
const proxyHeaders = this.getProxyHeaders(req, requestId, true);
for (const [name, value] of nodeHeadersToFetchHeaders(proxyHeaders)) {
middlewareReqHeaders.set(name, value);
}
// Add the Vercel platform proxy request headers
const proxyHeaders = this.getProxyHeaders(req, requestId, true);
for (const [name, value] of nodeHeadersToFetchHeaders(proxyHeaders)) {
middlewareReqHeaders.set(name, value);
}
try {
const middlewareRes = await fetch(
`http://127.0.0.1:${port}${parsed.path}`,
{
@@ -1547,8 +1529,30 @@ export default class DevServer {
`Rewrote incoming HTTP URL from "${beforeRewriteUrl}" to "${req.url}"`
);
}
} finally {
this.killBuilderDevServer(pid);
}
} catch (err) {
// `startDevServer()` threw an error. Most likely this means the dev
// server process exited before sending the port information message
// (missing dependency at runtime, for example).
if (err.code === 'ENOENT') {
err.message = `Command not found: ${chalk.cyan(
err.path,
...err.spawnargs
)}\nPlease ensure that ${cmd(err.path)} is properly installed`;
err.link = 'https://vercel.link/command-not-found';
}
await this.sendError(
req,
res,
requestId,
'EDGE_FUNCTION_INVOCATION_FAILED',
500
);
return;
} finally {
if (middlewarePid) {
this.killBuilderDevServer(middlewarePid);
}
}
}
@@ -1831,7 +1835,10 @@ export default class DevServer {
isDev: true,
requestPath,
devCacheDir,
env: { ...envConfigs.runEnv },
env: {
...envConfigs.runEnv,
VERCEL_BUILDER_DEBUG: this.output.debugEnabled ? '1' : undefined,
},
buildEnv: { ...envConfigs.buildEnv },
},
});
@@ -2276,13 +2283,7 @@ function proxyPass(
`Failed to complete request to ${req.url}: ${error}`
);
if (!res.headersSent) {
devServer.sendError(
req,
res,
requestId,
'NO_RESPONSE_FROM_FUNCTION',
502
);
devServer.sendError(req, res, requestId, 'FUNCTION_INVOCATION_FAILED');
}
}
);

View File

@@ -0,0 +1,7 @@
export const config = {
runtime: 'invalid-runtime-value',
};
export default async function edge(request, event) {
throw new Error('intentional runtime error');
}

View File

@@ -0,0 +1,8 @@
export const config = {
runtime: 'experimental-edge',
};
export async function notTheDefaultExport(request, event) {
// this will never be run
return new Response('some response body');
}

View File

@@ -0,0 +1,7 @@
export const config = {
runtime: 'experimental-edge',
};
export default async function edge(request, event) {
throw new Error('intentional runtime error');
}

View File

@@ -0,0 +1,10 @@
export const config = {
runtime: 'experimental-edge',
};
export default async function edge(request, event) {
// this should never be executed
return new Response('some response body');
}
throw new Error('intentional startup error');

View File

@@ -0,0 +1,9 @@
export const config = {
runtime: 'experimental-edge'
}
export default async function edge(request: Request, event: Event) {
return new Response('some response body');
// intentional missing closing bracket to produce syntax error
// }

View File

@@ -0,0 +1,9 @@
import unknownModule from 'unknown-module-893427589372458934795843';
export const config = {
runtime: 'experimental-edge',
};
export default async function edge(request, event) {
return new Response(unknownModule('some response body'));
}

View File

@@ -0,0 +1,9 @@
export const config = {
runtime: 'experimental-edge',
};
export default async function edge(request, event) {
return new Response('responding with intentional 500 from user code', {
status: 500,
});
}

View File

@@ -0,0 +1,8 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
decamelize@6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-6.0.0.tgz#8cad4d916fde5c41a264a43d0ecc56fe3d31749e"
integrity sha512-Fv96DCsdOgB6mdGl67MT5JaTNKRzrzill5OH5s8bjYJXVlcXyPYGyPsUkWyGV5p1TXI5esYIYMMeDJL0hEIwaA==

View File

@@ -0,0 +1,13 @@
// Supports both a single string value or an array of matchers
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};
export default function middleware(request, _event) {
const response = new Response('middleware response');
// Set custom header
response.headers.set('x-modified-edge', 'true');
return response;
}

View File

@@ -23,7 +23,7 @@ test('[vercel dev] should support edge functions', async () => {
const body = { hello: 'world' };
let res = await fetch(`http://localhost:${port}/api/edge-function`, {
let res = await fetch(`http://localhost:${port}/api/edge-success`, {
method: 'POST',
headers: {
'content-type': 'application/json',
@@ -36,7 +36,7 @@ test('[vercel dev] should support edge functions', async () => {
// are set up; so, we test that they are all passed through properly
expect(await res.json()).toMatchObject({
headerContentType: 'application/json',
url: `http://localhost:${port}/api/edge-function`,
url: `http://localhost:${port}/api/edge-success`,
method: 'POST',
body: '{"hello":"world"}',
decamelized: 'some_camel_case_thing',
@@ -48,6 +48,237 @@ test('[vercel dev] should support edge functions', async () => {
}
});
test(
'[vercel dev] edge functions respond properly the same as production',
testFixtureStdio('edge-function', async (testPath: any) => {
await testPath(500, '/api/edge-500-response');
await testPath(200, '/api/edge-success');
})
);
test('[vercel dev] should support edge functions returning intentional 500 responses', async () => {
const dir = fixture('edge-function');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
const body = { hello: 'world' };
let res = await fetch(`http://localhost:${port}/api/edge-500-response`, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify(body),
});
validateResponseHeaders(res);
expect(await res.status).toBe(500);
expect(await res.text()).toBe(
'responding with intentional 500 from user code'
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle runtime errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(`http://localhost:${port}/api/edge-error-runtime`, {
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
validateResponseHeaders(res);
const { stdout, stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stdout).toMatch(/Unhandled rejection: intentional runtime error/g);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-runtime: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle config errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(`http://localhost:${port}/api/edge-error-config`, {
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
validateResponseHeaders(res);
const { stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stderr).toMatch(
/Invalid function runtime "invalid-runtime-value" for "api\/edge-error-config.js". Valid runtimes are: \["experimental-edge"\]/g
);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-config: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle startup errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(`http://localhost:${port}/api/edge-error-startup`, {
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
validateResponseHeaders(res);
const { stdout, stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stdout).toMatch(
/Failed to instantiate edge runtime: intentional startup error/g
);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-startup: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle syntax errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(`http://localhost:${port}/api/edge-error-syntax`, {
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
});
validateResponseHeaders(res);
const { stdout, stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stdout).toMatch(
/Failed to instantiate edge runtime: Module parse failed: Unexpected token/g
);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-syntax: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle import errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(
`http://localhost:${port}/api/edge-error-unknown-import`,
{
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
}
);
validateResponseHeaders(res);
const { stdout, stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stdout).toMatch(
/Failed to instantiate edge runtime: Code generation from strings disallowed for this context/g
);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-unknown-import: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should handle import errors thrown in edge functions', async () => {
const dir = fixture('edge-function-error');
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
let res = await fetch(
`http://localhost:${port}/api/edge-error-no-handler`,
{
method: 'GET',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
}
);
validateResponseHeaders(res);
const { stdout, stderr } = await dev.kill('SIGTERM');
expect(await res.text()).toMatch(
/<strong>500<\/strong>: INTERNAL_SERVER_ERROR/g
);
expect(stdout).toMatch(
/No default export was found. Add a default export to handle requests./g
);
expect(stderr).toMatch(
/Failed to complete request to \/api\/edge-error-no-handler: Error: socket hang up/g
);
} finally {
await dev.kill('SIGTERM');
}
});
test('[vercel dev] should support request body', async () => {
const dir = fixture('node-request-body');
const { dev, port, readyResolver } = await testFixture(dir);

View File

@@ -505,3 +505,21 @@ test(
await testPath(500, '/', /EDGE_FUNCTION_INVOCATION_FAILED/);
})
);
test(
'[vercel dev] Middleware with `matchers` config',
testFixtureStdio(
'middleware-matchers',
async (testPath: any) => {
// TODO: remove once latest `@vercel/node` is shipped to stable with `matchers` support (fails because `directoryListing`)
//await testPath(404, '/');
await testPath(404, '/another');
await testPath(200, '/about/page', 'middleware response');
await testPath(200, '/dashboard/home', 'middleware response');
},
{
// TODO: remove once latest `@vercel/node` is shipped to stable with `matchers` support
skipDeploy: true,
}
)
);

View File

@@ -257,6 +257,10 @@ async function testFixture(directory, opts = {}, args = []) {
dev.kill = async (...args) => {
dev._kill(...args);
await exitResolver;
return {
stdout,
stderr,
};
};
return {

View File

@@ -0,0 +1,16 @@
import { normalizeURL } from '../../../../src/util/bisect/normalize-url';
describe('normalize-url', () => {
it('should add https to url without scheme', () => {
const normalizedUrl = normalizeURL('vercel.com');
expect(normalizedUrl).toEqual('https://vercel.com');
});
it('should not add anything to a url that starts with https', () => {
const normalizedUrl = normalizeURL('https://vercel.com');
expect(normalizedUrl).toEqual('https://vercel.com');
});
it('should not add anything to a url that starts with http', () => {
const normalizedUrl = normalizeURL('http://vercel.com');
expect(normalizedUrl).toEqual('http://vercel.com');
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/client",
"version": "12.0.2-canary.1",
"version": "12.0.2",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"homepage": "https://vercel.com",
@@ -42,7 +42,7 @@
]
},
"dependencies": {
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@zeit/fetch": "5.2.0",
"async-retry": "1.2.3",
"async-sema": "3.0.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/edge",
"version": "0.0.1-canary.0",
"version": "0.0.1",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.mjs",

View File

@@ -0,0 +1,82 @@
/**
* City of the original client IP calculated by Vercel Proxy.
*/
export const CITY_HEADER_NAME = 'x-vercel-ip-city';
/**
* Country of the original client IP calculated by Vercel Proxy.
*/
export const COUNTRY_HEADER_NAME = 'x-vercel-ip-country';
/**
* Ip from Vercel Proxy. Do not confuse it with the client Ip.
*/
export const IP_HEADER_NAME = 'x-real-ip';
/**
* Latitude of the original client IP calculated by Vercel Proxy.
*/
export const LATITUDE_HEADER_NAME = 'x-vercel-ip-latitude';
/**
* Longitude of the original client IP calculated by Vercel Proxy.
*/
export const LONGITUDE_HEADER_NAME = 'x-vercel-ip-longitude';
/**
* Region of the original client IP calculated by Vercel Proxy.
*/
export const REGION_HEADER_NAME = 'x-vercel-ip-country-region';
/**
* We define a new type so this function can be reused with
* the global `Request`, `node-fetch` and other types.
*/
interface Request {
headers: {
get(name: string): string | null;
};
}
/**
* The location information of a given request
*/
export interface Geo {
/** The city that the request originated from */
city?: string;
/** The country that the request originated from */
country?: string;
/** The Vercel Edge Network region that received the request */
region?: string;
/** The latitude of the client */
latitude?: string;
/** The longitude of the client */
longitude?: string;
}
function getHeader(request: Request, key: string): string | undefined {
return request.headers.get(key) ?? undefined;
}
/**
* Returns the IP address of the request from the headers.
*
* @see {@link IP_HEADER_NAME}
*/
export function ipAddress(request: Request): string | undefined {
return getHeader(request, IP_HEADER_NAME);
}
/**
* Returns the location information from for the incoming request
*
* @see {@link CITY_HEADER_NAME}
* @see {@link COUNTRY_HEADER_NAME}
* @see {@link REGION_HEADER_NAME}
* @see {@link LATITUDE_HEADER_NAME}
* @see {@link LONGITUDE_HEADER_NAME}
*/
export function geolocation(request: Request): Geo {
return {
city: getHeader(request, CITY_HEADER_NAME),
country: getHeader(request, COUNTRY_HEADER_NAME),
region: getHeader(request, REGION_HEADER_NAME),
latitude: getHeader(request, LATITUDE_HEADER_NAME),
longitude: getHeader(request, LONGITUDE_HEADER_NAME),
};
}

View File

@@ -1,2 +1,5 @@
export type { ExtraResponseInit } from './middleware-helpers';
export { next, rewrite } from './middleware-helpers';
export * from './middleware-helpers';
export type { Geo } from './edge-headers';
export * from './edge-headers';

50
packages/edge/test/edge-headers.test.ts vendored Normal file
View File

@@ -0,0 +1,50 @@
/**
* @jest-environment @edge-runtime/jest-environment
*/
import {
CITY_HEADER_NAME,
COUNTRY_HEADER_NAME,
Geo,
geolocation,
ipAddress,
IP_HEADER_NAME,
LATITUDE_HEADER_NAME,
LONGITUDE_HEADER_NAME,
REGION_HEADER_NAME,
} from '../src';
test('`ipAddress` returns the value from the header', () => {
const req = new Request('https://example.vercel.sh', {
headers: {
[IP_HEADER_NAME]: '127.0.0.1',
},
});
expect(ipAddress(req)).toBe('127.0.0.1');
});
describe('`geolocation`', () => {
test('returns an empty object if headers are not found', () => {
const req = new Request('https://example.vercel.sh');
expect(geolocation(req)).toEqual({});
});
test('reads values from headers', () => {
const req = new Request('https://example.vercel.sh', {
headers: {
[CITY_HEADER_NAME]: 'Tel Aviv',
[COUNTRY_HEADER_NAME]: 'Israel',
[LATITUDE_HEADER_NAME]: '32.109333',
[LONGITUDE_HEADER_NAME]: '34.855499',
[REGION_HEADER_NAME]: 'fra1',
},
});
expect(geolocation(req)).toEqual<Geo>({
city: 'Tel Aviv',
country: 'Israel',
latitude: '32.109333',
longitude: '34.855499',
region: 'fra1',
});
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/frameworks",
"version": "1.0.2-canary.0",
"version": "1.0.2",
"main": "./dist/frameworks.js",
"types": "./dist/frameworks.d.ts",
"files": [
@@ -21,7 +21,7 @@
"@types/js-yaml": "3.12.1",
"@types/node": "12.0.4",
"@types/node-fetch": "2.5.8",
"@vercel/routing-utils": "1.13.5-canary.0",
"@vercel/routing-utils": "1.13.5",
"ajv": "6.12.2",
"typescript": "4.3.4"
}

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/go",
"version": "2.0.2-canary.1",
"version": "2.0.2",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/go",
@@ -25,7 +25,7 @@
"@types/fs-extra": "^5.0.5",
"@types/node-fetch": "^2.3.0",
"@types/tar": "^4.0.0",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/ncc": "0.24.0",
"async-retry": "1.3.1",
"execa": "^1.0.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/next",
"version": "3.0.5",
"version": "3.1.0",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/next-js",
@@ -45,9 +45,9 @@
"@types/semver": "6.0.0",
"@types/text-table": "0.2.1",
"@types/webpack-sources": "3.2.0",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/nft": "0.19.1",
"@vercel/routing-utils": "1.13.5-canary.0",
"@vercel/routing-utils": "1.13.5",
"async-sema": "3.0.1",
"buffer-crc32": "0.2.13",
"cheerio": "1.0.0-rc.10",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/node",
"version": "2.2.1-canary.1",
"version": "2.3.0",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/node-js",
@@ -31,7 +31,7 @@
},
"dependencies": {
"@types/node": "*",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/ncc": "0.24.0",
"@vercel/node-bridge": "3.0.0",
"@vercel/static-config": "2.0.1",

View File

@@ -74,7 +74,7 @@ import { Readable } from 'stream';
import type { Bridge } from '@vercel/node-bridge/bridge';
import { getVercelLauncher } from '@vercel/node-bridge/launcher.js';
import { VercelProxyResponse } from '@vercel/node-bridge/types';
import { Config, streamToBuffer } from '@vercel/build-utils';
import { Config, streamToBuffer, debug } from '@vercel/build-utils';
import exitHook from 'exit-hook';
import { EdgeRuntime, Primitives, runServer } from 'edge-runtime';
import { getConfig } from '@vercel/static-config';
@@ -82,6 +82,17 @@ import { Project } from 'ts-morph';
import ncc from '@vercel/ncc';
import fetch from 'node-fetch';
function logError(error: Error) {
console.error(error.message);
if (error.stack) {
// only show the stack trace if debug is enabled
// because it points to internals, not user code
const errorPrefixLength = 'Error: '.length;
const errorMessageLength = errorPrefixLength + error.message.length;
debug(error.stack.substring(errorMessageLength + 1));
}
}
function listen(server: Server, port: number, host: string): Promise<void> {
return new Promise(resolve => {
server.listen(port, host, () => {
@@ -136,78 +147,151 @@ async function serializeRequest(message: IncomingMessage) {
});
}
async function compileUserCode(entrypoint: string) {
try {
const buildResult = await ncc(entrypoint, {
target: 'es2022',
});
const userCode = buildResult.code;
return `
${userCode};
addEventListener('fetch', async (event) => {
try {
let serializedRequest = await event.request.text();
let requestDetails = JSON.parse(serializedRequest);
let body;
if (requestDetails.method !== 'GET' && requestDetails.method !== 'HEAD') {
body = Uint8Array.from(atob(requestDetails.body), c => c.charCodeAt(0));
}
let requestUrl = requestDetails.headers['x-forwarded-proto'] + '://' + requestDetails.headers['x-forwarded-host'] + requestDetails.url;
let request = new Request(requestUrl, {
headers: requestDetails.headers,
method: requestDetails.method,
body: body
});
event.request = request;
let edgeHandler = module.exports.default;
if (!edgeHandler) {
throw new Error('No default export was found. Add a default export to handle requests.');
}
let response = await edgeHandler(event.request, event);
return event.respondWith(response);
} catch (error) {
// we can't easily show a meaningful stack trace
// so, stick to just the error message for now
event.respondWith(new Response(error.message, {
status: 500,
headers: {
'x-vercel-failed': 'edge-wrapper'
}
}));
}
})`;
} catch (error) {
// We can't easily show a meaningful stack trace from ncc -> edge-runtime.
// So, stick with just the message for now.
console.log(`Failed to instantiate edge runtime: ${error.message}`);
return undefined;
}
}
async function createEdgeRuntime(userCode: string | undefined) {
try {
if (!userCode) {
return undefined;
}
const edgeRuntime = new EdgeRuntime({
initialCode: userCode,
extend: (context: Primitives) => {
Object.assign(context, {
__dirname: '',
module: {
exports: {},
},
});
return context;
},
});
const server = await runServer({ runtime: edgeRuntime });
exitHook(server.close);
return server;
} catch (error) {
// We can't easily show a meaningful stack trace from ncc -> edge-runtime.
// So, stick with just the message for now.
console.log(`Failed to instantiate edge runtime: ${error.message}`);
return undefined;
}
}
async function createEdgeEventHandler(
entrypoint: string
): Promise<(request: IncomingMessage) => Promise<VercelProxyResponse>> {
const buildResult = await ncc(entrypoint, { target: 'es2022' });
const userCode = buildResult.code;
const initialCode = `
${userCode};
addEventListener('fetch', async (event) => {
let serializedRequest = await event.request.text();
let requestDetails = JSON.parse(serializedRequest);
let body;
if (requestDetails.method !== 'GET' && requestDetails.method !== 'HEAD') {
body = Uint8Array.from(atob(requestDetails.body), c => c.charCodeAt(0));
}
let requestUrl = requestDetails.headers['x-forwarded-proto'] + '://' + requestDetails.headers['x-forwarded-host'] + requestDetails.url;
let request = new Request(requestUrl, {
headers: requestDetails.headers,
method: requestDetails.method,
body: body
});
event.request = request;
let edgeHandler = module.exports.default;
let response = edgeHandler(event.request, event);
return event.respondWith(response);
})`;
const edgeRuntime = new EdgeRuntime({
initialCode,
extend: (context: Primitives) => {
Object.assign(context, {
__dirname: '',
module: {
exports: {},
},
});
return context;
},
});
const server = await runServer({ runtime: edgeRuntime });
exitHook(server.close);
const userCode = await compileUserCode(entrypoint);
const server = await createEdgeRuntime(userCode);
return async function (request: IncomingMessage) {
if (!server) {
// this error state is already logged, but we have to wait until here to exit the process
// this matches the serverless function bridge launcher's behavior when
// an error is thrown in the function
process.exit(1);
}
const response = await fetch(server.url, {
redirect: 'manual',
method: 'post',
body: await serializeRequest(request),
});
const body = await response.text();
const isUserError =
response.headers.get('x-vercel-failed') === 'edge-wrapper';
if (isUserError && response.status >= 500) {
// this error was "unhandled" from the user code's perspective
console.log(`Unhandled rejection: ${body}`);
// this matches the serverless function bridge launcher's behavior when
// an error is thrown in the function
process.exit(1);
}
return {
statusCode: response.status,
headers: response.headers.raw(),
body: await response.text(),
body,
encoding: 'utf8',
};
};
}
const validRuntimes = ['experimental-edge'];
function parseRuntime(entrypoint: string): string | undefined {
function parseRuntime(
entrypoint: string,
entryPointPath: string
): string | undefined {
const project = new Project();
const staticConfig = getConfig(project, entrypoint);
const staticConfig = getConfig(project, entryPointPath);
const runtime = staticConfig?.runtime;
if (runtime && !validRuntimes.includes(runtime)) {
throw new Error(`Invalid function runtime for "${entrypoint}": ${runtime}`);
throw new Error(
`Invalid function runtime "${runtime}" for "${entrypoint}". Valid runtimes are: ${JSON.stringify(
validRuntimes
)}`
);
}
return runtime;
@@ -218,19 +302,21 @@ async function createEventHandler(
config: Config,
options: { shouldAddHelpers: boolean }
): Promise<(request: IncomingMessage) => Promise<VercelProxyResponse>> {
const runtime = parseRuntime(entrypoint);
const entryPointPath = join(process.cwd(), entrypoint!);
const runtime = parseRuntime(entrypoint, entryPointPath);
// `middleware.js`/`middleware.ts` file is always run as
// an Edge Function, otherwise needs to be opted-in via
// `export const config = { runtime: 'experimental-edge' }`
if (config.middleware === true || runtime === 'experimental-edge') {
return createEdgeEventHandler(entrypoint);
return createEdgeEventHandler(entryPointPath);
}
return createServerlessEventHandler(entrypoint, options);
return createServerlessEventHandler(entryPointPath, options);
}
let handleEvent: (request: IncomingMessage) => Promise<VercelProxyResponse>;
let handlerEventError: Error;
async function main() {
const config = JSON.parse(process.env.VERCEL_DEV_CONFIG || '{}');
@@ -246,10 +332,14 @@ async function main() {
const proxyServer = createServer(onDevRequest);
await listen(proxyServer, 0, '127.0.0.1');
const entryPointPath = join(process.cwd(), entrypoint!);
handleEvent = await createEventHandler(entryPointPath, config, {
shouldAddHelpers,
});
try {
handleEvent = await createEventHandler(entrypoint!, config, {
shouldAddHelpers,
});
} catch (error) {
logError(error);
handlerEventError = error;
}
const address = proxyServer.address();
if (typeof process.send === 'function') {
@@ -278,6 +368,13 @@ export async function onDevRequest(
req: IncomingMessage,
res: ServerResponse
): Promise<void> {
if (handlerEventError) {
// this error state is already logged, but we have to wait until here to exit the process
// this matches the serverless function bridge launcher's behavior when
// an error is thrown in the function
process.exit(1);
}
if (!handleEvent) {
res.statusCode = 500;
res.end('Bridge is not ready, please try again');
@@ -315,6 +412,6 @@ export function fixConfigDev(config: { compilerOptions: any }): void {
}
main().catch(err => {
console.error(err);
logError(err);
process.exit(1);
});

View File

@@ -460,7 +460,26 @@ export const prepareCache: PrepareCache = ({ repoRootPath, workPath }) => {
export const startDevServer: StartDevServer = async opts => {
const { entrypoint, workPath, config, meta = {} } = opts;
const entryDir = join(workPath, dirname(entrypoint));
const entrypointPath = join(workPath, entrypoint);
if (config.middleware === true && typeof meta.requestUrl === 'string') {
// TODO: static config is also parsed in `dev-server.ts`.
// we should pass in this version as an env var instead.
const project = new Project();
const staticConfig = getConfig(project, entrypointPath);
// Middleware is a catch-all for all paths unless a `matcher` property is defined
const matchers = new RegExp(getRegExpFromMatchers(staticConfig?.matcher));
if (!matchers.test(meta.requestUrl)) {
// If the "matchers" doesn't say to handle this
// path then skip middleware invocation
return null;
}
}
const entryDir = dirname(entrypointPath);
const projectTsConfig = await walkParentDirs({
base: workPath,
start: entryDir,
@@ -492,6 +511,12 @@ export const startDevServer: StartDevServer = async opts => {
});
const { pid } = child;
if (!pid) {
throw new Error(
`Child Process has no "pid" when forking: "${devServerPath}"`
);
}
const onMessage = once<{ port: number }>(child, 'message');
const onExit = once.spread<[number, string | null]>(child, 'exit');
const result = await Promise.race([onMessage, onExit]);
@@ -514,7 +539,7 @@ export const startDevServer: StartDevServer = async opts => {
// Got "exit" event from child process
const [exitCode, signal] = result;
const reason = signal ? `"${signal}" signal` : `exit code ${exitCode}`;
throw new Error(`\`node ${entrypoint}\` failed with ${reason}`);
throw new Error(`Function \`${entrypoint}\` failed with ${reason}`);
}
};

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/python",
"version": "3.0.2-canary.1",
"version": "3.0.2",
"main": "./dist/index.js",
"license": "MIT",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/python",
@@ -23,7 +23,7 @@
"devDependencies": {
"@types/execa": "^0.9.0",
"@types/jest": "27.4.1",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/ncc": "0.24.0",
"execa": "^1.0.0",
"typescript": "4.3.4"

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/redwood",
"version": "1.0.2-canary.1",
"version": "1.0.2",
"main": "./dist/index.js",
"license": "MIT",
"homepage": "https://vercel.com/docs",
@@ -21,13 +21,13 @@
},
"dependencies": {
"@vercel/nft": "0.19.1",
"@vercel/routing-utils": "1.13.5-canary.0",
"@vercel/routing-utils": "1.13.5",
"semver": "6.1.1"
},
"devDependencies": {
"@types/aws-lambda": "8.10.19",
"@types/node": "*",
"@types/semver": "6.0.0",
"@vercel/build-utils": "4.1.1-canary.1"
"@vercel/build-utils": "4.2.0"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/remix",
"version": "1.0.2-canary.1",
"version": "1.0.2",
"license": "MIT",
"main": "./dist/index.js",
"homepage": "https://vercel.com/docs",
@@ -21,13 +21,12 @@
"default-server.js"
],
"dependencies": {
"@remix-run/vercel": "1.4.3",
"@vercel/nft": "0.19.1"
},
"devDependencies": {
"@types/jest": "27.5.1",
"@types/node": "*",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"typescript": "4.6.4"
}
}

View File

@@ -13,6 +13,7 @@ import {
runNpmInstall,
runPackageJsonScript,
scanParentDirs,
walkParentDirs,
} from '@vercel/build-utils';
import type {
BuildV2,
@@ -23,10 +24,17 @@ import type {
import { nodeFileTrace } from '@vercel/nft';
import type { AppConfig } from './types';
// Name of the Remix runtime adapter npm package for Vercel
const REMIX_RUNTIME_ADAPTER_NAME = '@remix-run/vercel';
// Pinned version of the last verified working version of the adapter
const REMIX_RUNTIME_ADAPTER_VERSION = '1.6.1';
export const build: BuildV2 = async ({
entrypoint,
files,
workPath,
repoRootPath,
config,
meta = {},
}) => {
@@ -70,6 +78,51 @@ export const build: BuildV2 = async ({
}
}
// Ensure `@remix-run/vercel` is in the project's `package.json`
const packageJsonPath = await walkParentDirs({
base: repoRootPath,
start: workPath,
filename: 'package.json',
});
if (packageJsonPath) {
const packageJson: PackageJson = JSON.parse(
await fs.readFile(packageJsonPath, 'utf8')
);
const { dependencies = {}, devDependencies = {} } = packageJson;
let modified = false;
if (REMIX_RUNTIME_ADAPTER_NAME in devDependencies) {
dependencies[REMIX_RUNTIME_ADAPTER_NAME] =
devDependencies[REMIX_RUNTIME_ADAPTER_NAME];
delete devDependencies[REMIX_RUNTIME_ADAPTER_NAME];
console.log(
`Warning: Moving "${REMIX_RUNTIME_ADAPTER_NAME}" from \`devDependencies\` to \`dependencies\`. You should commit this change.`
);
modified = true;
} else if (!(REMIX_RUNTIME_ADAPTER_NAME in dependencies)) {
dependencies[REMIX_RUNTIME_ADAPTER_NAME] = REMIX_RUNTIME_ADAPTER_VERSION;
console.log(
`Warning: Adding "${REMIX_RUNTIME_ADAPTER_NAME}" v${REMIX_RUNTIME_ADAPTER_VERSION} to \`dependencies\`. You should commit this change.`
);
modified = true;
}
if (modified) {
const packageJsonString = JSON.stringify(
{
...packageJson,
dependencies,
devDependencies,
},
null,
2
);
await fs.writeFile(packageJsonPath, `${packageJsonString}\n`);
}
} else {
debug(`Failed to find "package.json" file in project`);
}
if (typeof installCommand === 'string') {
if (installCommand.trim()) {
console.log(`Running "install" command: \`${installCommand}\`...`);
@@ -215,11 +268,8 @@ async function createRenderFunction(
base: rootDir,
});
let needsVercelAdapter = false;
for (const warning of trace.warnings) {
if (warning.message.includes("'@remix-run/vercel'")) {
needsVercelAdapter = true;
} else if (warning.stack) {
if (warning.stack) {
debug(warning.stack.replace('Error: ', 'Warning: '));
}
}
@@ -227,33 +277,6 @@ async function createRenderFunction(
files[file] = await FileFsRef.fromFsPath({ fsPath: join(rootDir, file) });
}
if (needsVercelAdapter) {
// Package in the Builder's version of `@remix-run/vercel` Runtime adapter
const remixVercelPackageJsonPath = require.resolve(
'@remix-run/vercel/package.json',
{
paths: [__dirname],
}
);
const remixVercelPackageJson: PackageJson = require(remixVercelPackageJsonPath);
const remixVercelDir = dirname(remixVercelPackageJsonPath);
const remixVercelEntrypoint = join(remixVercelDir, 'index.js');
console.log(
`Warning: Implicitly adding \`${remixVercelPackageJson.name}\` v${remixVercelPackageJson.version} to your project. You should add this dependency to your \`package.json\` file.`
);
const adapterBase = join(remixVercelDir, '../../..');
const adapterTrace = await nodeFileTrace([remixVercelEntrypoint], {
base: adapterBase,
});
for (const file of adapterTrace.fileList) {
files[file] = await FileFsRef.fromFsPath({
fsPath: join(adapterBase, file),
});
}
}
const lambda = new NodejsLambda({
files,
handler,

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/routing-utils",
"version": "1.13.5-canary.0",
"version": "1.13.5",
"description": "Vercel routing utilities",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",

View File

@@ -1,7 +1,7 @@
{
"name": "@vercel/ruby",
"author": "Nathan Cahill <nathan@nathancahill.com>",
"version": "1.3.10-canary.1",
"version": "1.3.10",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/ruby",
@@ -23,7 +23,7 @@
"devDependencies": {
"@types/fs-extra": "8.0.0",
"@types/semver": "6.0.0",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/build-utils": "4.2.0",
"@vercel/ncc": "0.24.0",
"execa": "2.0.4",
"fs-extra": "^7.0.1",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/static-build",
"version": "1.0.2-canary.1",
"version": "1.0.2",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/build-step",
@@ -37,10 +37,10 @@
"@types/ms": "0.7.31",
"@types/node-fetch": "2.5.4",
"@types/promise-timeout": "1.3.0",
"@vercel/build-utils": "4.1.1-canary.1",
"@vercel/frameworks": "1.0.2-canary.0",
"@vercel/build-utils": "4.2.0",
"@vercel/frameworks": "1.0.2",
"@vercel/ncc": "0.24.0",
"@vercel/routing-utils": "1.13.5-canary.0",
"@vercel/routing-utils": "1.13.5",
"fs-extra": "10.0.0",
"get-port": "5.0.0",
"is-port-reachable": "2.0.1",

651
yarn.lock

File diff suppressed because it is too large Load Diff