-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
edge-handler.mts
244 lines (216 loc) · 7.41 KB
/
edge-handler.mts
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { createEdgeWasmPlugin, WasmAssets } from './edge-wasm-plugin.mjs';
import {
createNodeCompatPlugin,
NodeCompatBindings,
} from './edge-node-compat-plugin.mjs';
import { EdgeRuntime, runServer } from 'edge-runtime';
import fetch, { Headers } from 'node-fetch';
import { isError } from '@vercel/error-utils';
import { readFileSync } from 'fs';
import { serializeBody, entrypointToOutputPath, logError } from '../utils.js';
import esbuild from 'esbuild';
import exitHook from 'exit-hook';
import type { HeadersInit } from 'node-fetch';
import type { VercelProxyResponse } from '../types.js';
import type { IncomingMessage } from 'http';
import { fileURLToPath } from 'url';
const NODE_VERSION_MAJOR = process.version.match(/^v(\d+)\.\d+/)?.[1];
const NODE_VERSION_IDENTIFIER = `node${NODE_VERSION_MAJOR}`;
if (!NODE_VERSION_MAJOR) {
throw new Error(
`Unable to determine current node version: process.version=${process.version}`
);
}
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const edgeHandlerTemplate = readFileSync(
`${__dirname}/edge-handler-template.js`
);
async function compileUserCode(
entrypointFullPath: string,
entrypointRelativePath: string,
isMiddleware: boolean
): Promise<
| undefined
| {
userCode: string;
wasmAssets: WasmAssets;
nodeCompatBindings: NodeCompatBindings;
}
> {
const { wasmAssets, plugin: edgeWasmPlugin } = createEdgeWasmPlugin();
const nodeCompatPlugin = createNodeCompatPlugin();
try {
const result = await esbuild.build({
// bundling behavior: use globals (like "browser") instead
// of "require" statements for core libraries (like "node")
platform: 'browser',
// target syntax: only use syntax available on the current
// version of node
target: NODE_VERSION_IDENTIFIER,
sourcemap: 'inline',
legalComments: 'none',
bundle: true,
plugins: [
edgeWasmPlugin,
nodeCompatPlugin.plugin,
{
name: 'import.meta.url',
setup({ onLoad }) {
onLoad({ filter: /\.[cm]?js$/, namespace: 'file' }, args => {
let code = readFileSync(args.path, 'utf8');
code = code.replace(
/\bimport\.meta\.url\b/g,
JSON.stringify(import.meta.url)
);
return { contents: code };
});
},
},
],
entryPoints: [entrypointFullPath],
write: false, // operate in memory
format: 'cjs',
});
const compiledFile = result.outputFiles?.[0];
if (!compiledFile) {
throw new Error(
`Compilation of ${entrypointRelativePath} produced no output files.`
);
}
const userCode = `
// strict mode
"use strict";var regeneratorRuntime;
// user code
${compiledFile.text};
const handler = module.exports;
// request metadata
const isMiddleware = ${isMiddleware};
const entrypointLabel = '${entrypointRelativePath}';
// edge handler
${edgeHandlerTemplate};
const dependencies = { Request, Response };
const options = { isMiddleware, entrypointLabel };
registerFetchListener(handler, options, dependencies);
`;
return {
userCode,
wasmAssets,
nodeCompatBindings: nodeCompatPlugin.bindings,
};
} catch (error: unknown) {
// We can't easily show a meaningful stack trace from ncc -> edge-runtime.
// So, stick with just the message for now.
console.error(`Failed to compile user code for edge runtime.`);
if (isError(error)) logError(error);
return undefined;
}
}
async function createEdgeRuntimeServer(params?: {
userCode: string;
wasmAssets: WasmAssets;
nodeCompatBindings: NodeCompatBindings;
}) {
try {
if (!params) {
return undefined;
}
const wasmBindings = await params.wasmAssets.getContext();
const nodeCompatBindings = params.nodeCompatBindings.getContext();
// @ts-ignore
const WebSocket = (await import('ws')).WebSocket;
const runtime = new EdgeRuntime({
initialCode: params.userCode,
extend: context => {
Object.assign(context, {
// This is required for esbuild wrapping logic to resolve
module: {},
WebSocket,
// This is required for environment variable access.
// In production, env var access is provided by static analysis
// so that only the used values are available.
process: {
env: process.env,
},
// These are the global bindings for Node.js compatibility
...nodeCompatBindings,
// These are the global bindings for WebAssembly module
...wasmBindings,
});
return context;
},
});
const server = await runServer({ runtime });
exitHook(() => server.close());
return server;
} catch (error: any) {
// We can't easily show a meaningful stack trace from ncc -> edge-runtime.
// So, stick with just the message for now.
console.error('Failed to instantiate edge runtime.');
logError(error);
return undefined;
}
}
export async function createEdgeEventHandler(
entrypointFullPath: string,
entrypointRelativePath: string,
isMiddleware: boolean,
isZeroConfig?: boolean
): Promise<(request: IncomingMessage) => Promise<VercelProxyResponse>> {
const userCode = await compileUserCode(
entrypointFullPath,
entrypointRelativePath,
isMiddleware
);
const server = await createEdgeRuntimeServer(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 headers = new Headers(request.headers as HeadersInit);
const body: Buffer | string | undefined = await serializeBody(request);
if (body !== undefined) headers.set('content-length', String(body.length));
const url = new URL(request.url ?? '/', server.url);
// @ts-expect-error
const response = await fetch(url, {
body,
headers,
method: request.method,
redirect: 'manual',
});
const isUserError =
response.headers.get('x-vercel-failed') === 'edge-wrapper';
if (isUserError && response.status >= 500) {
const body = await response.text();
// We can't currently get a real stack trace from the Edge Function error,
// but we can fake a basic one that is still usefult to the user.
const fakeStackTrace = ` at (${entrypointRelativePath})`;
const requestPath = entrypointToRequestPath(
entrypointRelativePath,
isZeroConfig
);
console.log(
`Error from API Route ${requestPath}: ${body}\n${fakeStackTrace}`
);
// this matches the serverless function bridge launcher's behavior when
// an error is thrown in the function
process.exit(1);
}
return {
status: response.status,
headers: response.headers,
body: response.body,
encoding: 'utf8',
};
};
}
function entrypointToRequestPath(
entrypointRelativePath: string,
isZeroConfig?: boolean
) {
// ensure the path starts with a slash to match conventions used elsewhere,
// notably when rendering serverless function paths in error messages
return '/' + entrypointToOutputPath(entrypointRelativePath, isZeroConfig);
}