-
Notifications
You must be signed in to change notification settings - Fork 26k
/
sandbox.ts
67 lines (60 loc) · 1.98 KB
/
sandbox.ts
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
import type { RequestData, FetchEventResult } from '../types'
import { getServerError } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { getModuleContext } from './context'
import { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
export const ErrorSource = Symbol('SandboxError')
type RunnerFn = (params: {
name: string
env: string[]
onWarning?: (warn: Error) => void
paths: string[]
request: RequestData
useCache: boolean
edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'wasm' | 'assets'>
distDir: string
}) => Promise<FetchEventResult>
export const run = withTaggedErrors(async (params) => {
const { runtime, evaluateInContext } = await getModuleContext({
moduleName: params.name,
onWarning: params.onWarning ?? (() => {}),
useCache: params.useCache !== false,
env: params.env,
edgeFunctionEntry: params.edgeFunctionEntry,
distDir: params.distDir,
})
for (const paramPath of params.paths) {
evaluateInContext(paramPath)
}
const subreq = params.request.headers[`x-middleware-subrequest`]
const subrequests = typeof subreq === 'string' ? subreq.split(':') : []
if (subrequests.includes(params.name)) {
return {
waitUntil: Promise.resolve(),
response: new runtime.context.Response(null, {
headers: {
'x-middleware-next': '1',
},
}),
}
}
return runtime.context._ENTRIES[`middleware_${params.name}`].default({
request: params.request,
})
})
/**
* Decorates the runner function making sure all errors it can produce are
* tagged with `edge-server` so they can properly be rendered in dev.
*/
function withTaggedErrors(fn: RunnerFn): RunnerFn {
return (params) =>
fn(params)
.then((result) => ({
...result,
waitUntil: result?.waitUntil?.catch((error) => {
throw getServerError(error, 'edge-server')
}),
}))
.catch((error) => {
throw getServerError(error, 'edge-server')
})
}