-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathedge.ts
277 lines (244 loc) · 8.4 KB
/
edge.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/* eslint-disable max-lines */
import { promises as fs, existsSync } from 'fs'
import { resolve, join } from 'path'
import type { NetlifyConfig, NetlifyPluginConstants } from '@netlify/build'
import { greenBright } from 'chalk'
import destr from 'destr'
import { copy, copyFile, emptyDir, ensureDir, readJSON, readJson, writeJSON, writeJson } from 'fs-extra'
import type { MiddlewareManifest } from 'next/dist/build/webpack/plugins/middleware-plugin'
import type { RouteHas } from 'next/dist/lib/load-custom-routes'
import { outdent } from 'outdent'
import { getRequiredServerFiles } from './config'
// This is the format as of [email protected]
interface EdgeFunctionDefinitionV1 {
env: string[]
files: string[]
name: string
page: string
regexp: string
}
export interface MiddlewareMatcher {
regexp: string
locale?: false
has?: RouteHas[]
}
// This is the format after [email protected]
interface EdgeFunctionDefinitionV2 {
env: string[]
files: string[]
name: string
page: string
matchers: MiddlewareMatcher[]
}
type EdgeFunctionDefinition = EdgeFunctionDefinitionV1 | EdgeFunctionDefinitionV2
export interface FunctionManifest {
version: 1
functions: Array<
| {
function: string
path: string
}
| {
function: string
pattern: string
}
>
import_map?: string
}
export const loadMiddlewareManifest = (netlifyConfig: NetlifyConfig): Promise<MiddlewareManifest | null> => {
const middlewarePath = resolve(netlifyConfig.build.publish, 'server', 'middleware-manifest.json')
if (!existsSync(middlewarePath)) {
return null
}
return readJson(middlewarePath)
}
/**
* Convert the Next middleware name into a valid Edge Function name
*/
const sanitizeName = (name: string) => `next_${name.replace(/\W/g, '_')}`
/**
* Initialization added to the top of the edge function bundle
*/
const bootstrap = /* js */ `
globalThis.process = { env: {...Deno.env.toObject(), NEXT_RUNTIME: 'edge', 'NEXT_PRIVATE_MINIMAL_MODE': '1' } }
globalThis._ENTRIES ||= {}
// Deno defines "window", but naughty libraries think this means it's a browser
delete globalThis.window
`
/**
* Concatenates the Next edge function code with the required chunks and adds an export
*/
const getMiddlewareBundle = async ({
edgeFunctionDefinition,
netlifyConfig,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
netlifyConfig: NetlifyConfig
}): Promise<string> => {
const { publish } = netlifyConfig.build
const chunks: Array<string> = [bootstrap]
for (const file of edgeFunctionDefinition.files) {
const filePath = join(publish, file)
const data = await fs.readFile(filePath, 'utf8')
chunks.push('{', data, '}')
}
const middleware = await fs.readFile(join(publish, `server`, `${edgeFunctionDefinition.name}.js`), 'utf8')
chunks.push(middleware)
const exports = /* js */ `export default _ENTRIES["middleware_${edgeFunctionDefinition.name}"].default;`
chunks.push(exports)
return chunks.join('\n')
}
const getEdgeTemplatePath = (file: string) => join(__dirname, '..', '..', 'src', 'templates', 'edge', file)
const copyEdgeSourceFile = ({
file,
target,
edgeFunctionDir,
}: {
file: string
edgeFunctionDir: string
target?: string
}) => fs.copyFile(getEdgeTemplatePath(file), join(edgeFunctionDir, target ?? file))
const writeEdgeFunction = async ({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
edgeFunctionRoot: string
netlifyConfig: NetlifyConfig
}): Promise<
Array<{
function: string
pattern: string
}>
> => {
const name = sanitizeName(edgeFunctionDefinition.name)
const edgeFunctionDir = join(edgeFunctionRoot, name)
const bundle = await getMiddlewareBundle({
edgeFunctionDefinition,
netlifyConfig,
})
await ensureDir(edgeFunctionDir)
await fs.writeFile(join(edgeFunctionDir, 'bundle.js'), bundle)
await copyEdgeSourceFile({
edgeFunctionDir,
file: 'runtime.ts',
target: 'index.ts',
})
const matchers: EdgeFunctionDefinitionV2['matchers'] = []
// The v1 middleware manifest has a single regexp, but the v2 has an array of matchers
if ('regexp' in edgeFunctionDefinition) {
matchers.push({ regexp: edgeFunctionDefinition.regexp })
} else {
matchers.push(...edgeFunctionDefinition.matchers)
}
await writeJson(join(edgeFunctionDir, 'matchers.json'), matchers)
// We add a defintion for each matching path
return matchers.map((matcher) => {
const pattern = matcher.regexp
return { function: name, pattern }
})
}
export const cleanupEdgeFunctions = ({
INTERNAL_EDGE_FUNCTIONS_SRC = '.netlify/edge-functions',
}: NetlifyPluginConstants) => emptyDir(INTERNAL_EDGE_FUNCTIONS_SRC)
export const writeDevEdgeFunction = async ({
INTERNAL_EDGE_FUNCTIONS_SRC = '.netlify/edge-functions',
}: NetlifyPluginConstants) => {
const manifest: FunctionManifest = {
functions: [
{
function: 'next-dev',
path: '/*',
},
],
version: 1,
}
const edgeFunctionRoot = resolve(INTERNAL_EDGE_FUNCTIONS_SRC)
await emptyDir(edgeFunctionRoot)
await writeJson(join(edgeFunctionRoot, 'manifest.json'), manifest)
await copy(getEdgeTemplatePath('../edge-shared'), join(edgeFunctionRoot, 'edge-shared'))
const edgeFunctionDir = join(edgeFunctionRoot, 'next-dev')
await ensureDir(edgeFunctionDir)
await copyEdgeSourceFile({ edgeFunctionDir, file: 'next-dev.js', target: 'index.js' })
}
/**
* Writes Edge Functions for the Next middleware
*/
export const writeEdgeFunctions = async (netlifyConfig: NetlifyConfig) => {
const manifest: FunctionManifest = {
functions: [],
version: 1,
}
const edgeFunctionRoot = resolve('.netlify', 'edge-functions')
await emptyDir(edgeFunctionRoot)
const { publish } = netlifyConfig.build
const nextConfigFile = await getRequiredServerFiles(publish)
const nextConfig = nextConfigFile.config
await copy(getEdgeTemplatePath('../edge-shared'), join(edgeFunctionRoot, 'edge-shared'))
await writeJSON(join(edgeFunctionRoot, 'edge-shared', 'nextConfig.json'), nextConfig)
if (
!destr(process.env.NEXT_DISABLE_EDGE_IMAGES) &&
!destr(process.env.NEXT_DISABLE_NETLIFY_EDGE) &&
!destr(process.env.DISABLE_IPX)
) {
console.log(
'Using Netlify Edge Functions for image format detection. Set env var "NEXT_DISABLE_EDGE_IMAGES=true" to disable.',
)
const edgeFunctionDir = join(edgeFunctionRoot, 'ipx')
await ensureDir(edgeFunctionDir)
await copyEdgeSourceFile({ edgeFunctionDir, file: 'ipx.ts', target: 'index.ts' })
await copyFile(
join('.netlify', 'functions-internal', '_ipx', 'imageconfig.json'),
join(edgeFunctionDir, 'imageconfig.json'),
)
manifest.functions.push({
function: 'ipx',
path: '/_next/image*',
})
}
if (!destr(process.env.NEXT_DISABLE_NETLIFY_EDGE)) {
const middlewareManifest = await loadMiddlewareManifest(netlifyConfig)
if (!middlewareManifest) {
console.error("Couldn't find the middleware manifest")
return
}
let usesEdge = false
for (const middleware of middlewareManifest.sortedMiddleware) {
usesEdge = true
const edgeFunctionDefinition = middlewareManifest.middleware[middleware]
const functionDefinitions = await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
})
manifest.functions.push(...functionDefinitions)
}
// Older versions of the manifest format don't have the functions field
// No, the version field was not incremented
if (typeof middlewareManifest.functions === 'object') {
for (const edgeFunctionDefinition of Object.values(middlewareManifest.functions)) {
usesEdge = true
const functionDefinitions = await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
})
manifest.functions.push(...functionDefinitions)
}
}
if (usesEdge) {
console.log(outdent`
✨ Deploying middleware and functions to ${greenBright`Netlify Edge Functions`} ✨
This feature is in beta. Please share your feedback here: https://ntl.fyi/next-netlify-edge
`)
}
}
await writeJson(join(edgeFunctionRoot, 'manifest.json'), manifest)
}
export const enableEdgeInNextConfig = async (publish: string) => {
const configFile = join(publish, 'required-server-files.json')
const config = await readJSON(configFile)
await writeJSON(configFile, config)
}
/* eslint-enable max-lines */