-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathfunctions.ts
235 lines (206 loc) · 8.75 KB
/
functions.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
/* eslint-disable max-lines */
import type { NetlifyConfig, NetlifyPluginConstants } from '@netlify/build'
import bridgeFile from '@vercel/node-bridge'
import chalk from 'chalk'
import destr from 'destr'
import { copyFile, ensureDir, existsSync, readJSON, writeFile, writeJSON } from 'fs-extra'
import type { ImageConfigComplete, RemotePattern } from 'next/dist/shared/lib/image-config'
import { outdent } from 'outdent'
import { join, relative, resolve } from 'pathe'
import { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, IMAGE_FUNCTION_NAME, DEFAULT_FUNCTIONS_SRC } from '../constants'
import { getApiHandler } from '../templates/getApiHandler'
import { getHandler } from '../templates/getHandler'
import { getPageResolver, getSinglePageResolver } from '../templates/getPageResolver'
import { ApiConfig, ApiRouteType, extractConfigFromFile } from './analysis'
import { getSourceFileForPage } from './files'
import { getFunctionNameForPage } from './utils'
export interface ApiRouteConfig {
route: string
config: ApiConfig
compiled: string
}
export const generateFunctions = async (
{ FUNCTIONS_SRC = DEFAULT_FUNCTIONS_SRC, INTERNAL_FUNCTIONS_SRC, PUBLISH_DIR }: NetlifyPluginConstants,
appDir: string,
apiRoutes: Array<ApiRouteConfig>,
): Promise<void> => {
const publish = resolve(PUBLISH_DIR)
const functionsDir = resolve(INTERNAL_FUNCTIONS_SRC || FUNCTIONS_SRC)
console.log({ functionsDir })
const functionDir = join(functionsDir, HANDLER_FUNCTION_NAME)
const publishDir = relative(functionDir, publish)
for (const { route, config, compiled } of apiRoutes) {
const apiHandlerSource = await getApiHandler({
page: route,
config,
publishDir,
appDir: relative(functionDir, appDir),
})
const functionName = getFunctionNameForPage(route, config.type === ApiRouteType.BACKGROUND)
await ensureDir(join(functionsDir, functionName))
await writeFile(join(functionsDir, functionName, `${functionName}.js`), apiHandlerSource)
await copyFile(bridgeFile, join(functionsDir, functionName, 'bridge.js'))
await copyFile(
join(__dirname, '..', '..', 'lib', 'templates', 'handlerUtils.js'),
join(functionsDir, functionName, 'handlerUtils.js'),
)
const resolveSourceFile = (file: string) => join(publish, 'server', file)
const resolverSource = await getSinglePageResolver({
functionsDir,
// These extra pages are always included by Next.js
sourceFiles: [compiled, 'pages/_app.js', 'pages/_document.js', 'pages/_error.js'].map(resolveSourceFile),
})
await writeFile(join(functionsDir, functionName, 'pages.js'), resolverSource)
}
const writeHandler = async (functionName: string, isODB: boolean) => {
const handlerSource = await getHandler({ isODB, publishDir, appDir: relative(functionDir, appDir) })
await ensureDir(join(functionsDir, functionName))
await writeFile(join(functionsDir, functionName, `${functionName}.js`), handlerSource)
await copyFile(bridgeFile, join(functionsDir, functionName, 'bridge.js'))
await copyFile(
join(__dirname, '..', '..', 'lib', 'templates', 'handlerUtils.js'),
join(functionsDir, functionName, 'handlerUtils.js'),
)
}
await writeHandler(HANDLER_FUNCTION_NAME, false)
await writeHandler(ODB_FUNCTION_NAME, true)
}
/**
* Writes a file in each function directory that contains references to every page entrypoint.
* This is just so that the nft bundler knows about them. We'll eventually do this better.
*/
export const generatePagesResolver = async ({
constants: { INTERNAL_FUNCTIONS_SRC, FUNCTIONS_SRC = DEFAULT_FUNCTIONS_SRC, PUBLISH_DIR },
target,
}: {
constants: NetlifyPluginConstants
target: string
}): Promise<void> => {
const functionsPath = INTERNAL_FUNCTIONS_SRC || FUNCTIONS_SRC
const jsSource = await getPageResolver({
publish: PUBLISH_DIR,
target,
})
await writeFile(join(functionsPath, ODB_FUNCTION_NAME, 'pages.js'), jsSource)
await writeFile(join(functionsPath, HANDLER_FUNCTION_NAME, 'pages.js'), jsSource)
}
// Move our next/image function into the correct functions directory
export const setupImageFunction = async ({
constants: { INTERNAL_FUNCTIONS_SRC, FUNCTIONS_SRC = DEFAULT_FUNCTIONS_SRC, IS_LOCAL },
imageconfig = {},
netlifyConfig,
basePath,
remotePatterns,
responseHeaders,
}: {
constants: NetlifyPluginConstants
netlifyConfig: NetlifyConfig
basePath: string
imageconfig: Partial<ImageConfigComplete>
remotePatterns: RemotePattern[]
responseHeaders?: Record<string, string>
}): Promise<void> => {
const imagePath = imageconfig.path || '/_next/image'
if (destr(process.env.DISABLE_IPX)) {
// If no image loader is specified, need to redirect to a 404 page since there's no
// backing loader to serve local site images once deployed to Netlify
if (!IS_LOCAL && imageconfig.loader === 'default') {
netlifyConfig.redirects.push({
from: `${imagePath}*`,
query: { url: ':url', w: ':width', q: ':quality' },
to: '/404.html',
status: 404,
force: true,
})
}
} else {
const functionsPath = INTERNAL_FUNCTIONS_SRC || FUNCTIONS_SRC
const functionName = `${IMAGE_FUNCTION_NAME}.js`
const functionDirectory = join(functionsPath, IMAGE_FUNCTION_NAME)
await ensureDir(functionDirectory)
await writeJSON(join(functionDirectory, 'imageconfig.json'), {
...imageconfig,
basePath: [basePath, IMAGE_FUNCTION_NAME].join('/'),
remotePatterns,
responseHeaders,
})
await copyFile(join(__dirname, '..', '..', 'lib', 'templates', 'ipx.js'), join(functionDirectory, functionName))
// If we have edge functions then the request will have already been rewritten
// so this won't match. This is matched if edge is disabled or unavailable.
netlifyConfig.redirects.push({
from: `${imagePath}*`,
query: { url: ':url', w: ':width', q: ':quality' },
to: `${basePath}/${IMAGE_FUNCTION_NAME}/w_:width,q_:quality/:url`,
status: 301,
})
netlifyConfig.redirects.push({
from: `${basePath}/${IMAGE_FUNCTION_NAME}/*`,
to: `/.netlify/builders/${IMAGE_FUNCTION_NAME}`,
status: 200,
})
}
if (basePath) {
// next/image generates image static URLs that still point at the site root
netlifyConfig.redirects.push({
from: '/_next/static/image/*',
to: '/static/image/:splat',
status: 200,
})
}
}
/**
* Look for API routes, and extract the config from the source file.
*/
export const getApiRouteConfigs = async (publish: string, baseDir: string): Promise<Array<ApiRouteConfig>> => {
const pages = await readJSON(join(publish, 'server', 'pages-manifest.json'))
const apiRoutes = Object.keys(pages).filter((page) => page.startsWith('/api/'))
const pagesDir = join(baseDir, 'pages')
return await Promise.all(
apiRoutes.map(async (apiRoute) => {
const filePath = getSourceFileForPage(apiRoute, pagesDir)
return { route: apiRoute, config: await extractConfigFromFile(filePath), compiled: pages[apiRoute] }
}),
)
}
/**
* Looks for extended API routes (background and scheduled functions) and extract the config from the source file.
*/
export const getExtendedApiRouteConfigs = async (publish: string, baseDir: string): Promise<Array<ApiRouteConfig>> => {
const settledApiRoutes = await getApiRouteConfigs(publish, baseDir)
// We only want to return the API routes that are background or scheduled functions
return settledApiRoutes.filter((apiRoute) => apiRoute.config.type !== undefined)
}
interface FunctionsManifest {
functions: Array<{ name: string; schedule?: string }>
}
/**
* Warn the user of the caveats if they're using background or scheduled API routes
*/
export const warnOnApiRoutes = async ({
FUNCTIONS_DIST,
}: Pick<NetlifyPluginConstants, 'FUNCTIONS_DIST'>): Promise<void> => {
const functionsManifestPath = join(FUNCTIONS_DIST, 'manifest.json')
if (!existsSync(functionsManifestPath)) {
return
}
const { functions }: FunctionsManifest = await readJSON(functionsManifestPath)
if (functions.some((func) => func.name.endsWith('-background'))) {
console.warn(
outdent`
${chalk.yellowBright`Using background API routes`}
If your account type does not support background functions, the deploy will fail.
During local development, background API routes will run as regular API routes, but in production they will immediately return an empty "202 Accepted" response.
`,
)
}
if (functions.some((func) => func.schedule)) {
console.warn(
outdent`
${chalk.yellowBright`Using scheduled API routes`}
These are run on a schedule when deployed to production.
You can test them locally by loading them in your browser but this will not be available when deployed, and any returned value is ignored.
`,
)
}
}
/* eslint-enable max-lines */