-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathindex.ts
304 lines (267 loc) · 9.41 KB
/
index.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
import { join, relative } from 'path'
import type { NetlifyPlugin, NetlifyPluginOptions } from '@netlify/build/types'
import { bold, redBright } from 'chalk'
import destr from 'destr'
import { existsSync, readFileSync } from 'fs-extra'
import { outdent } from 'outdent'
import { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME } from './constants'
import { restoreCache, saveCache } from './helpers/cache'
import {
getNextConfig,
getRequiredServerFiles,
updateRequiredServerFiles,
configureHandlerFunctions,
generateCustomHeaders,
} from './helpers/config'
import { onPreDev } from './helpers/dev'
import { writeEdgeFunctions, loadMiddlewareManifest, cleanupEdgeFunctions } from './helpers/edge'
import { moveStaticPages, movePublicFiles, removeMetadataFiles } from './helpers/files'
import { bundleBasedOnNftFiles, splitApiRoutes } from './helpers/flags'
import {
generateFunctions,
setupImageFunction,
generatePagesResolver,
warnOnApiRoutes,
getAPILambdas,
packSingleFunction,
getExtendedApiRouteConfigs,
APILambda,
getSSRLambdas,
} from './helpers/functions'
import { generateRedirects, generateStaticRedirects } from './helpers/redirects'
import {
shouldSkip,
isNextAuthInstalled,
getCustomImageResponseHeaders,
getRemotePatterns,
ExperimentalConfigWithLegacy,
} from './helpers/utils'
import {
verifyNetlifyBuildVersion,
checkNextSiteHasBuilt,
checkForRootPublish,
checkZipSize,
checkForOldFunctions,
warnForProblematicUserRewrites,
warnForRootRedirects,
} from './helpers/verification'
const plugin: NetlifyPlugin = {
async onPreBuild({
constants,
netlifyConfig,
utils: {
build: { failBuild },
cache,
},
}) {
const { publish } = netlifyConfig.build
if (shouldSkip()) {
await restoreCache({ cache, publish })
console.log('Not running Next Runtime')
if (existsSync(join(constants.INTERNAL_FUNCTIONS_SRC, HANDLER_FUNCTION_NAME))) {
console.log(`Please ensure you remove any generated functions from ${constants.INTERNAL_FUNCTIONS_SRC}`)
}
return
}
checkForRootPublish({ publish, failBuild })
verifyNetlifyBuildVersion({ failBuild, ...constants })
await restoreCache({ cache, publish })
netlifyConfig.build.environment ||= {}
// eslint-disable-next-line unicorn/consistent-destructuring
netlifyConfig.build.environment.NEXT_PRIVATE_TARGET = 'server'
},
// eslint-disable-next-line max-lines-per-function
async onBuild({
constants,
netlifyConfig,
utils: {
build: { failBuild },
},
featureFlags = {},
}: NetlifyPluginOptions & { featureFlags?: Record<string, unknown> }) {
if (shouldSkip()) {
return
}
const { publish } = netlifyConfig.build
checkNextSiteHasBuilt({ publish, failBuild })
const {
appDir,
basePath,
i18n,
images,
target,
ignore,
trailingSlash,
outdir,
experimental,
routesManifest,
pageExtensions,
} = await getNextConfig({
publish,
failBuild,
})
await cleanupEdgeFunctions(constants)
const middlewareManifest = await loadMiddlewareManifest(netlifyConfig)
const config = await getRequiredServerFiles(publish)
if (
middlewareManifest?.functions &&
Object.keys(middlewareManifest.functions).length !== 0 &&
destr(process.env.NEXT_DISABLE_NETLIFY_EDGE)
) {
failBuild(outdent`
You are using Next.js experimental edge runtime, but have set NEXT_DISABLE_NETLIFY_EDGE to true. This is not supported.
To use edge runtime, remove the env var ${bold`NEXT_DISABLE_NETLIFY_EDGE`}.
`)
}
if (
middlewareManifest?.middleware &&
Object.keys(middlewareManifest.middleware).length !== 0 &&
destr(process.env.NEXT_DISABLE_NETLIFY_EDGE)
) {
console.log(
redBright(outdent`
You are using Next.js Middleware without Netlify Edge Functions.
This is deprecated because it negatively affects performance and will disable ISR and static rendering.
It also disables advanced middleware features from @netlify/next
To get the best performance and use Netlify Edge Functions, remove the env var ${bold`NEXT_DISABLE_NETLIFY_EDGE`}.
`),
)
}
if (isNextAuthInstalled()) {
const userDefinedNextAuthUrl = config.config.env.NEXTAUTH_URL
if (userDefinedNextAuthUrl) {
console.log(
`NextAuth package detected, NEXTAUTH_URL environment variable set by user in next.config.js to ${userDefinedNextAuthUrl}`,
)
} else if (process.env.NEXTAUTH_URL) {
// When the value is specified in the netlify.toml or the Netlify UI (will be evaluated in this order)
const nextAuthUrl = `${process.env.NEXTAUTH_URL}${basePath}`
console.log(
`NextAuth package detected, NEXTAUTH_URL environment variable set by user in Netlify configuration to ${nextAuthUrl}`,
)
config.config.env.NEXTAUTH_URL = nextAuthUrl
await updateRequiredServerFiles(publish, config)
} else {
// Using the deploy prime url in production leads to issues because the unique deploy ID is part of the generated URL
// and will not match the expected URL in the callback URL of an OAuth application.
const nextAuthUrl = `${
process.env.CONTEXT === 'production' ? process.env.URL : process.env.DEPLOY_PRIME_URL
}${basePath}`
console.log(`NextAuth package detected, setting NEXTAUTH_URL environment variable to ${nextAuthUrl}`)
config.config.env.NEXTAUTH_URL = nextAuthUrl
await updateRequiredServerFiles(publish, config)
}
}
const buildId = readFileSync(join(publish, 'BUILD_ID'), 'utf8').trim()
const apiLambdas: APILambda[] = splitApiRoutes(featureFlags, publish)
? await getAPILambdas(publish, appDir, pageExtensions)
: await getExtendedApiRouteConfigs(publish, appDir, pageExtensions).then((extendedRoutes) =>
extendedRoutes.map(packSingleFunction),
)
const ssrLambdas = bundleBasedOnNftFiles(featureFlags) ? await getSSRLambdas(publish) : []
await generateFunctions(constants, appDir, apiLambdas, ssrLambdas)
await generatePagesResolver(constants)
await configureHandlerFunctions({
netlifyConfig,
ignore,
publish: relative(process.cwd(), publish),
apiLambdas,
ssrLambdas,
splitApiRoutes: splitApiRoutes(featureFlags, publish),
})
await movePublicFiles({ appDir, outdir, publish, basePath })
if (!destr(process.env.SERVE_STATIC_FILES_FROM_ORIGIN)) {
await moveStaticPages({ target, netlifyConfig, i18n, basePath })
}
await generateStaticRedirects({
netlifyConfig,
nextConfig: { basePath, i18n },
})
await setupImageFunction({
constants,
imageconfig: images,
netlifyConfig,
basePath,
remotePatterns: getRemotePatterns(experimental, images),
responseHeaders: getCustomImageResponseHeaders(netlifyConfig.headers),
})
await generateRedirects({
netlifyConfig,
nextConfig: { basePath, i18n, trailingSlash, appDir },
buildId,
apiLambdas,
})
await writeEdgeFunctions({ constants, netlifyConfig, routesManifest })
},
async onPostBuild({
netlifyConfig: {
build: { publish },
redirects,
headers,
},
utils: {
status,
cache,
functions,
build: { failBuild },
},
constants: { FUNCTIONS_DIST },
}) {
await saveCache({ cache, publish })
if (shouldSkip()) {
status.show({
title: 'Next Runtime did not run',
summary: `Next cache was stored, but all other functions were skipped because ${
process.env.NETLIFY_NEXT_PLUGIN_SKIP
? `NETLIFY_NEXT_PLUGIN_SKIP is set`
: `NEXT_PLUGIN_FORCE_RUN is set to ${process.env.NEXT_PLUGIN_FORCE_RUN}`
}`,
})
return
}
await checkForOldFunctions({ functions })
await checkZipSize(join(FUNCTIONS_DIST, `${ODB_FUNCTION_NAME}.zip`))
const nextConfig = await getNextConfig({ publish, failBuild })
const {
basePath,
appDir,
experimental,
}: { basePath: string; appDir?: string; experimental: ExperimentalConfigWithLegacy } = nextConfig
generateCustomHeaders(nextConfig, headers)
warnForProblematicUserRewrites({ basePath, redirects })
warnForRootRedirects({ appDir })
await warnOnApiRoutes({ FUNCTIONS_DIST })
// we are removing metadata files from Publish directory
// we have to do this after functions were bundled as bundling still
// require those files, but we don't want to publish them
await removeMetadataFiles(publish)
if (experimental?.appDir) {
console.log(
'🧪 Thank you for testing "appDir" support on Netlify. For known issues and to give feedback, visit https://ntl.fyi/next-13-feedback',
)
}
},
}
// The types haven't been updated yet
const nextRuntime = (
_inputs,
meta: { events?: Set<string> } = {},
): NetlifyPlugin & { onPreDev?: NetlifyPlugin['onPreBuild'] } => {
if (!meta?.events?.has('onPreDev')) {
return {
...plugin,
onEnd: ({ utils }) => {
utils.status.show({
title: 'Please upgrade to the latest version of the Netlify CLI',
summary:
'To support for the latest Next.js features, please upgrade to the latest version of the Netlify CLI',
})
},
}
}
return {
...plugin,
onPreDev,
}
}
module.exports = nextRuntime