This repository was archived by the owner on Mar 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmanifest.ts
342 lines (288 loc) · 10 KB
/
manifest.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { promises as fs } from 'fs'
import { join } from 'path'
import type { Bundle } from './bundle.js'
import { wrapBundleError } from './bundle_error.js'
import { Cache, FunctionConfig, Path } from './config.js'
import { Declaration, normalizePattern } from './declaration.js'
import { EdgeFunction } from './edge_function.js'
import { FeatureFlags } from './feature_flags.js'
import { Layer } from './layer.js'
import { getPackageVersion } from './package_json.js'
import { RateLimit, RateLimitAction, RateLimitAlgorithm, RateLimitAggregator } from './rate_limit.js'
import { nonNullable } from './utils/non_nullable.js'
import { ExtendedURLPattern } from './utils/urlpattern.js'
interface Route {
function: string
pattern: string
excluded_patterns: string[]
path?: string
methods?: string[]
}
interface TrafficRules {
action: {
type: string
config: {
rate_limit_config: {
algorithm: string
window_size: number
window_limit: number
}
aggregate: {
keys: {
type: string
}[]
}
to?: string
}
}
}
export interface EdgeFunctionConfig {
excluded_patterns: string[]
on_error?: string
generator?: string
name?: string
traffic_rules?: TrafficRules
}
interface Manifest {
bundler_version: string
bundles: { asset: string; format: string }[]
import_map?: string
layers: { name: string; flag: string }[]
routes: Route[]
post_cache_routes: Route[]
function_config: Record<string, EdgeFunctionConfig>
}
interface GenerateManifestOptions {
bundles?: Bundle[]
declarations?: Declaration[]
featureFlags?: FeatureFlags
functions: EdgeFunction[]
importMap?: string
internalFunctionConfig?: Record<string, FunctionConfig>
layers?: Layer[]
userFunctionConfig?: Record<string, FunctionConfig>
}
const removeEmptyConfigValues = (functionConfig: EdgeFunctionConfig) =>
Object.entries(functionConfig).reduce((acc, [key, value]) => {
if (value && !(Array.isArray(value) && value.length === 0)) {
return { ...acc, [key]: value }
}
return acc
}, {} as EdgeFunctionConfig)
// JavaScript regular expressions are converted to strings with leading and
// trailing slashes, so any slashes inside the expression itself are escaped
// as `//`. This function deserializes that back into a single slash, which
// is the format we want to use in the manifest.
const serializePattern = (pattern: string) => pattern.replace(/\\\//g, '/')
const sanitizeEdgeFunctionConfig = (config: Record<string, EdgeFunctionConfig>): Record<string, EdgeFunctionConfig> => {
const newConfig: Record<string, EdgeFunctionConfig> = {}
for (const [name, functionConfig] of Object.entries(config)) {
const newFunctionConfig = removeEmptyConfigValues(functionConfig)
if (Object.keys(newFunctionConfig).length !== 0) {
newConfig[name] = newFunctionConfig
}
}
return newConfig
}
const addExcludedPatterns = (
name: string,
manifestFunctionConfig: Record<string, EdgeFunctionConfig>,
excludedPath?: Path | Path[],
) => {
if (excludedPath) {
const paths = Array.isArray(excludedPath) ? excludedPath : [excludedPath]
const excludedPatterns = paths.map(pathToRegularExpression).filter(nonNullable).map(serializePattern)
manifestFunctionConfig[name].excluded_patterns.push(...excludedPatterns)
}
}
/**
* Normalizes method names into arrays of uppercase strings.
* (e.g. "get" becomes ["GET"])
*/
const normalizeMethods = (method: unknown, name: string): string[] | undefined => {
const methods = Array.isArray(method) ? method : [method]
return methods.map((method) => {
if (typeof method !== 'string') {
throw new TypeError(
`Could not parse method declaration of function '${name}'. Expecting HTTP Method, got ${method}`,
)
}
return method.toUpperCase()
})
}
const generateManifest = ({
bundles = [],
declarations = [],
functions,
userFunctionConfig = {},
internalFunctionConfig = {},
importMap,
layers = [],
}: GenerateManifestOptions) => {
const preCacheRoutes: Route[] = []
const postCacheRoutes: Route[] = []
const manifestFunctionConfig: Manifest['function_config'] = Object.fromEntries(
functions.map(({ name }) => [name, { excluded_patterns: [] }]),
)
const routedFunctions = new Set<string>()
const declarationsWithoutFunction = new Set<string>()
for (const [name, { excludedPath, onError, rateLimit }] of Object.entries(userFunctionConfig)) {
// If the config block is for a function that is not defined, discard it.
if (manifestFunctionConfig[name] === undefined) {
continue
}
addExcludedPatterns(name, manifestFunctionConfig, excludedPath)
manifestFunctionConfig[name] = {
...manifestFunctionConfig[name],
on_error: onError,
traffic_rules: getTrafficRulesConfig(rateLimit),
}
}
for (const [name, { excludedPath, path, onError, rateLimit, ...rest }] of Object.entries(internalFunctionConfig)) {
// If the config block is for a function that is not defined, discard it.
if (manifestFunctionConfig[name] === undefined) {
continue
}
addExcludedPatterns(name, manifestFunctionConfig, excludedPath)
manifestFunctionConfig[name] = {
...manifestFunctionConfig[name],
on_error: onError,
traffic_rules: getTrafficRulesConfig(rateLimit),
...rest,
}
}
declarations.forEach((declaration) => {
const func = functions.find(({ name }) => declaration.function === name)
if (func === undefined) {
declarationsWithoutFunction.add(declaration.function)
return
}
const pattern = getRegularExpression(declaration)
// If there is no `pattern`, the declaration will never be triggered, so we
// can discard it.
if (!pattern) {
return
}
routedFunctions.add(declaration.function)
const excludedPattern = getExcludedRegularExpressions(declaration)
const route: Route = {
function: func.name,
pattern: serializePattern(pattern),
excluded_patterns: excludedPattern.map(serializePattern),
}
if ('method' in declaration) {
route.methods = normalizeMethods(declaration.method, func.name)
}
if ('path' in declaration) {
route.path = declaration.path
}
if (declaration.cache === Cache.Manual) {
postCacheRoutes.push(route)
} else {
preCacheRoutes.push(route)
}
})
const manifestBundles = bundles.map(({ extension, format, hash }) => ({
asset: hash + extension,
format,
}))
const manifest: Manifest = {
bundles: manifestBundles,
routes: preCacheRoutes.filter(nonNullable),
post_cache_routes: postCacheRoutes.filter(nonNullable),
bundler_version: getPackageVersion(),
layers,
import_map: importMap,
function_config: sanitizeEdgeFunctionConfig(manifestFunctionConfig),
}
const unroutedFunctions = functions.filter(({ name }) => !routedFunctions.has(name)).map(({ name }) => name)
return { declarationsWithoutFunction: [...declarationsWithoutFunction], manifest, unroutedFunctions }
}
const getTrafficRulesConfig = (rl: RateLimit | undefined) => {
if (rl === undefined) {
return
}
const rateLimitAgg = Array.isArray(rl.aggregateBy) ? rl.aggregateBy : [RateLimitAggregator.Domain]
const rewriteConfig = 'to' in rl && typeof rl.to === 'string' ? { to: rl.to } : undefined
return {
action: {
type: rl.action || RateLimitAction.Limit,
config: {
...rewriteConfig,
rate_limit_config: {
window_limit: rl.windowLimit,
window_size: rl.windowSize,
algorithm: RateLimitAlgorithm.SlidingWindow,
},
aggregate: {
keys: rateLimitAgg.map((agg) => ({ type: agg })),
},
},
},
}
}
const pathToRegularExpression = (path: string) => {
if (!path) {
return null
}
try {
const pattern = new ExtendedURLPattern({ pathname: path })
// Removing the `^` and `$` delimiters because we'll need to modify what's
// between them.
const source = pattern.regexp.pathname.source.slice(1, -1)
// Wrapping the expression source with `^` and `$`. Also, adding an optional
// trailing slash, so that a declaration of `path: "/foo"` matches requests
// for both `/foo` and `/foo/`.
const normalizedSource = `^${source}\\/?$`
return normalizedSource
} catch (error) {
throw wrapBundleError(error)
}
}
const getRegularExpression = (declaration: Declaration) => {
if ('pattern' in declaration) {
try {
return normalizePattern(declaration.pattern)
} catch (error: unknown) {
throw wrapBundleError(
new Error(
`Could not parse path declaration of function '${declaration.function}': ${(error as Error).message}`,
),
)
}
}
return pathToRegularExpression(declaration.path)
}
const getExcludedRegularExpressions = (declaration: Declaration): string[] => {
if ('excludedPattern' in declaration && declaration.excludedPattern) {
const excludedPatterns: string[] = Array.isArray(declaration.excludedPattern)
? declaration.excludedPattern
: [declaration.excludedPattern]
return excludedPatterns.map((excludedPattern) => {
try {
return normalizePattern(excludedPattern)
} catch (error: unknown) {
throw wrapBundleError(
new Error(
`Could not parse path declaration of function '${declaration.function}': ${(error as Error).message}`,
),
)
}
})
}
if ('path' in declaration && declaration.excludedPath) {
const paths = Array.isArray(declaration.excludedPath) ? declaration.excludedPath : [declaration.excludedPath]
return paths.map(pathToRegularExpression).filter(nonNullable)
}
return []
}
interface WriteManifestOptions extends GenerateManifestOptions {
distDirectory: string
}
const writeManifest = async ({ distDirectory, ...rest }: WriteManifestOptions) => {
const { manifest } = generateManifest(rest)
const manifestPath = join(distDirectory, 'manifest.json')
await fs.writeFile(manifestPath, JSON.stringify(manifest))
return manifest
}
export { generateManifest, Manifest, Route, writeManifest }