-
Notifications
You must be signed in to change notification settings - Fork 26k
/
get-page-static-info.ts
649 lines (576 loc) · 19.1 KB
/
get-page-static-info.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import type { NextConfig } from '../../server/config-shared'
import type { Middleware, RouteHas } from '../../lib/load-custom-routes'
import { promises as fs } from 'fs'
import LRUCache from 'next/dist/compiled/lru-cache'
import { matcher } from 'next/dist/compiled/micromatch'
import { ServerRuntime } from 'next/types'
import {
extractExportedConstValue,
UnsupportedValueError,
} from './extract-const-value'
import { parseModule } from './parse-module'
import * as Log from '../output/log'
import { SERVER_RUNTIME } from '../../lib/constants'
import { checkCustomRoutes } from '../../lib/load-custom-routes'
import { tryToParsePath } from '../../lib/try-to-parse-path'
import { isAPIRoute } from '../../lib/is-api-route'
import { isEdgeRuntime } from '../../lib/is-edge-runtime'
import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
import type { RSCMeta } from '../webpack/loaders/get-module-build-info'
// TODO: migrate preferredRegion here
// Don't forget to update the next-types-plugin file as well
const AUTHORIZED_EXTRA_PROPS = ['maxDuration']
export interface MiddlewareConfig {
matchers?: MiddlewareMatcher[]
unstable_allowDynamicGlobs?: string[]
regions?: string[] | string
}
export interface MiddlewareMatcher {
regexp: string
locale?: false
has?: RouteHas[]
missing?: RouteHas[]
originalSource: string
}
export interface PageStaticInfo {
runtime?: ServerRuntime
preferredRegion?: string | string[]
ssg?: boolean
ssr?: boolean
rsc?: RSCModuleType
generateStaticParams?: boolean
middleware?: MiddlewareConfig
amp?: boolean | 'hybrid'
extraConfig?: Record<string, any>
}
const CLIENT_MODULE_LABEL =
/\/\* __next_internal_client_entry_do_not_use__ ([^ ]*) (cjs|auto) \*\//
const ACTION_MODULE_LABEL =
/\/\* __next_internal_action_entry_do_not_use__ ([^ ]+) \*\//
const CLIENT_DIRECTIVE = 'use client'
const SERVER_ACTION_DIRECTIVE = 'use server'
export type RSCModuleType = 'server' | 'client'
export function getRSCModuleInformation(
source: string,
isServerLayer: boolean
): RSCMeta {
const actions = source.match(ACTION_MODULE_LABEL)?.[1]?.split(',')
const clientInfoMatch = source.match(CLIENT_MODULE_LABEL)
const isClientRef = !!clientInfoMatch
if (!isServerLayer) {
return {
type: RSC_MODULE_TYPES.client,
actions,
isClientRef,
}
}
const clientRefs = clientInfoMatch?.[1]?.split(',')
const clientEntryType = clientInfoMatch?.[2] as 'cjs' | 'auto'
const type = clientRefs ? RSC_MODULE_TYPES.client : RSC_MODULE_TYPES.server
return {
type,
actions,
clientRefs,
clientEntryType,
isClientRef,
}
}
const warnedInvalidValueMap = {
runtime: new Map<string, boolean>(),
preferredRegion: new Map<string, boolean>(),
} as const
function warnInvalidValue(
pageFilePath: string,
key: keyof typeof warnedInvalidValueMap,
message: string
): void {
if (warnedInvalidValueMap[key].has(pageFilePath)) return
Log.warn(
`Next.js can't recognize the exported \`${key}\` field in "${pageFilePath}" as ${message}.` +
'\n' +
'The default runtime will be used instead.'
)
warnedInvalidValueMap[key].set(pageFilePath, true)
}
/**
* Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are:
* - Modules with `export function getStaticProps | getServerSideProps`
* - Modules with `export { getStaticProps | getServerSideProps } <from ...>`
* - Modules with `export const runtime = ...`
*/
function checkExports(
swcAST: any,
pageFilePath: string
): {
ssr: boolean
ssg: boolean
runtime?: string
preferredRegion?: string | string[]
generateImageMetadata?: boolean
generateSitemaps?: boolean
generateStaticParams: boolean
extraProperties?: Set<string>
directives?: Set<string>
} {
const exportsSet = new Set<string>([
'getStaticProps',
'getServerSideProps',
'generateImageMetadata',
'generateSitemaps',
'generateStaticParams',
])
if (Array.isArray(swcAST?.body)) {
try {
let runtime: string | undefined
let preferredRegion: string | string[] | undefined
let ssr: boolean = false
let ssg: boolean = false
let generateImageMetadata: boolean = false
let generateSitemaps: boolean = false
let generateStaticParams = false
let extraProperties = new Set<string>()
let directives = new Set<string>()
let hasLeadingNonDirectiveNode = false
for (const node of swcAST.body) {
// There should be no non-string literals nodes before directives
if (
node.type === 'ExpressionStatement' &&
node.expression.type === 'StringLiteral'
) {
if (!hasLeadingNonDirectiveNode) {
const directive = node.expression.value
if (CLIENT_DIRECTIVE === directive) {
directives.add('client')
}
if (SERVER_ACTION_DIRECTIVE === directive) {
directives.add('server')
}
}
} else {
hasLeadingNonDirectiveNode = true
}
if (
node.type === 'ExportDeclaration' &&
node.declaration?.type === 'VariableDeclaration'
) {
for (const declaration of node.declaration?.declarations) {
if (declaration.id.value === 'runtime') {
runtime = declaration.init.value
} else if (declaration.id.value === 'preferredRegion') {
if (declaration.init.type === 'ArrayExpression') {
const elements: string[] = []
for (const element of declaration.init.elements) {
const { expression } = element
if (expression.type !== 'StringLiteral') {
continue
}
elements.push(expression.value)
}
preferredRegion = elements
} else {
preferredRegion = declaration.init.value
}
} else {
extraProperties.add(declaration.id.value)
}
}
}
if (
node.type === 'ExportDeclaration' &&
node.declaration?.type === 'FunctionDeclaration' &&
exportsSet.has(node.declaration.identifier?.value)
) {
const id = node.declaration.identifier.value
ssg = id === 'getStaticProps'
ssr = id === 'getServerSideProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
generateStaticParams = id === 'generateStaticParams'
}
if (
node.type === 'ExportDeclaration' &&
node.declaration?.type === 'VariableDeclaration'
) {
const id = node.declaration?.declarations[0]?.id.value
if (exportsSet.has(id)) {
ssg = id === 'getStaticProps'
ssr = id === 'getServerSideProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
generateStaticParams = id === 'generateStaticParams'
}
}
if (node.type === 'ExportNamedDeclaration') {
const values = node.specifiers.map(
(specifier: any) =>
specifier.type === 'ExportSpecifier' &&
specifier.orig?.type === 'Identifier' &&
specifier.orig?.value
)
for (const value of values) {
if (!ssg && value === 'getStaticProps') ssg = true
if (!ssr && value === 'getServerSideProps') ssr = true
if (!generateImageMetadata && value === 'generateImageMetadata')
generateImageMetadata = true
if (!generateSitemaps && value === 'generateSitemaps')
generateSitemaps = true
if (!generateStaticParams && value === 'generateStaticParams')
generateStaticParams = true
if (!runtime && value === 'runtime')
warnInvalidValue(
pageFilePath,
'runtime',
'it was not assigned to a string literal'
)
if (!preferredRegion && value === 'preferredRegion')
warnInvalidValue(
pageFilePath,
'preferredRegion',
'it was not assigned to a string literal or an array of string literals'
)
}
}
}
return {
ssr,
ssg,
runtime,
preferredRegion,
generateImageMetadata,
generateSitemaps,
generateStaticParams,
extraProperties,
directives,
}
} catch (err) {}
}
return {
ssg: false,
ssr: false,
runtime: undefined,
preferredRegion: undefined,
generateImageMetadata: false,
generateSitemaps: false,
generateStaticParams: false,
extraProperties: undefined,
directives: undefined,
}
}
async function tryToReadFile(filePath: string, shouldThrow: boolean) {
try {
return await fs.readFile(filePath, {
encoding: 'utf8',
})
} catch (error: any) {
if (shouldThrow) {
error.message = `Next.js ERROR: Failed to read file ${filePath}:\n${error.message}`
throw error
}
}
}
export function getMiddlewareMatchers(
matcherOrMatchers: unknown,
nextConfig: NextConfig
): MiddlewareMatcher[] {
let matchers: unknown[] = []
if (Array.isArray(matcherOrMatchers)) {
matchers = matcherOrMatchers
} else {
matchers.push(matcherOrMatchers)
}
const { i18n } = nextConfig
const originalSourceMap = new Map<Middleware, string>()
let routes = matchers.map((m) => {
let middleware = (typeof m === 'string' ? { source: m } : m) as Middleware
if (middleware) {
originalSourceMap.set(middleware, middleware.source)
}
return middleware
})
// check before we process the routes and after to ensure
// they are still valid
checkCustomRoutes(routes, 'middleware')
routes = routes.map((r) => {
let { source } = r
const isRoot = source === '/'
if (i18n?.locales && r.locale !== false) {
source = `/:nextInternalLocale((?!_next/)[^/.]{1,})${
isRoot ? '' : source
}`
}
source = `/:nextData(_next/data/[^/]{1,})?${source}${
isRoot
? `(${nextConfig.i18n ? '|\\.json|' : ''}/?index|/?index\\.json)?`
: '(.json)?'
}`
if (nextConfig.basePath) {
source = `${nextConfig.basePath}${source}`
}
r.source = source
return r
})
checkCustomRoutes(routes, 'middleware')
return routes.map((r) => {
const { source, ...rest } = r
const parsedPage = tryToParsePath(source)
if (parsedPage.error || !parsedPage.regexStr) {
throw new Error(`Invalid source: ${source}`)
}
const originalSource = originalSourceMap.get(r)
return {
...rest,
regexp: parsedPage.regexStr,
originalSource: originalSource || source,
}
})
}
function getMiddlewareConfig(
pageFilePath: string,
config: any,
nextConfig: NextConfig
): Partial<MiddlewareConfig> {
const result: Partial<MiddlewareConfig> = {}
if (config.matcher) {
result.matchers = getMiddlewareMatchers(config.matcher, nextConfig)
}
if (typeof config.regions === 'string' || Array.isArray(config.regions)) {
result.regions = config.regions
} else if (typeof config.regions !== 'undefined') {
Log.warn(
`The \`regions\` config was ignored: config must be empty, a string or an array of strings. (${pageFilePath})`
)
}
if (config.unstable_allowDynamic) {
result.unstable_allowDynamicGlobs = Array.isArray(
config.unstable_allowDynamic
)
? config.unstable_allowDynamic
: [config.unstable_allowDynamic]
for (const glob of result.unstable_allowDynamicGlobs ?? []) {
try {
matcher(glob)
} catch (err) {
throw new Error(
`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${
(err as Error).message
}`
)
}
}
}
return result
}
const apiRouteWarnings = new LRUCache({ max: 250 })
function warnAboutExperimentalEdge(apiRoute: string | null) {
if (
process.env.NODE_ENV === 'production' &&
process.env.NEXT_PRIVATE_BUILD_WORKER === '1'
) {
return
}
if (apiRouteWarnings.has(apiRoute)) {
return
}
Log.warn(
apiRoute
? `${apiRoute} provided runtime 'experimental-edge'. It can be updated to 'edge' instead.`
: `You are using an experimental edge runtime, the API might change.`
)
apiRouteWarnings.set(apiRoute, 1)
}
const warnedUnsupportedValueMap = new LRUCache<string, boolean>({ max: 250 })
function warnAboutUnsupportedValue(
pageFilePath: string,
page: string | undefined,
error: UnsupportedValueError
) {
if (warnedUnsupportedValueMap.has(pageFilePath)) {
return
}
Log.warn(
`Next.js can't recognize the exported \`config\` field in ` +
(page ? `route "${page}"` : `"${pageFilePath}"`) +
':\n' +
error.message +
(error.path ? ` at "${error.path}"` : '') +
'.\n' +
'The default config will be used instead.\n' +
'Read More - https://nextjs.org/docs/messages/invalid-page-config'
)
warnedUnsupportedValueMap.set(pageFilePath, true)
}
// Detect if metadata routes is a dynamic route, which containing
// generateImageMetadata or generateSitemaps as export
export async function isDynamicMetadataRoute(
pageFilePath: string
): Promise<boolean> {
const fileContent = (await tryToReadFile(pageFilePath, true)) || ''
if (!/generateImageMetadata|generateSitemaps/.test(fileContent)) return false
const swcAST = await parseModule(pageFilePath, fileContent)
const exportsInfo = checkExports(swcAST, pageFilePath)
return !exportsInfo.generateImageMetadata || !exportsInfo.generateSitemaps
}
/**
* For a given pageFilePath and nextConfig, if the config supports it, this
* function will read the file and return the runtime that should be used.
* It will look into the file content only if the page *requires* a runtime
* to be specified, that is, when gSSP or gSP is used.
* Related discussion: https://github.com/vercel/next.js/discussions/34179
*/
export async function getPageStaticInfo(params: {
pageFilePath: string
nextConfig: Partial<NextConfig>
isDev?: boolean
page?: string
pageType: 'pages' | 'app' | 'root'
}): Promise<PageStaticInfo> {
const { isDev, pageFilePath, nextConfig, page, pageType } = params
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if (
/runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const/.test(
fileContent
)
) {
const swcAST = await parseModule(pageFilePath, fileContent)
const {
ssg,
ssr,
runtime,
preferredRegion,
generateStaticParams,
extraProperties,
directives,
} = checkExports(swcAST, pageFilePath)
const rscInfo = getRSCModuleInformation(fileContent, true)
const rsc = rscInfo.type
// default / failsafe value for config
let config: any
try {
config = extractExportedConstValue(swcAST, 'config')
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
// `export config` doesn't exist, or other unknown error throw by swc, silence them
}
let extraConfig: Record<string, any> | undefined
if (extraProperties) {
extraConfig = {}
for (const prop of extraProperties) {
if (!AUTHORIZED_EXTRA_PROPS.includes(prop)) continue
try {
extraConfig[prop] = extractExportedConstValue(swcAST, prop)
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
}
}
}
if (pageType === 'app') {
if (config) {
let message = `Page config in ${pageFilePath} is deprecated. Replace \`export const config=…\` with the following:`
if (config.runtime) {
message += `\n - \`export const runtime = ${JSON.stringify(
config.runtime
)}\``
}
if (config.regions) {
message += `\n - \`export const preferredRegion = ${JSON.stringify(
config.regions
)}\``
}
message += `\nVisit https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config for more information.`
if (isDev) {
Log.warnOnce(message)
} else {
throw new Error(message)
}
config = {}
}
}
if (!config) config = {}
// We use `export const config = { runtime: '...' }` to specify the page runtime for pages/.
// In the new app directory, we prefer to use `export const runtime = '...'`
// and deprecate the old way. To prevent breaking changes for `pages`, we use the exported config
// as the fallback value.
let resolvedRuntime
if (pageType === 'app') {
resolvedRuntime = runtime
} else {
resolvedRuntime = runtime || config.runtime
}
if (
typeof resolvedRuntime !== 'undefined' &&
resolvedRuntime !== SERVER_RUNTIME.nodejs &&
!isEdgeRuntime(resolvedRuntime)
) {
const options = Object.values(SERVER_RUNTIME).join(', ')
const message =
typeof resolvedRuntime !== 'string'
? `The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}`
: `Provided runtime "${resolvedRuntime}" is not supported. Please leave it empty or choose one of: ${options}`
if (isDev) {
Log.error(message)
} else {
throw new Error(message)
}
}
const requiresServerRuntime = ssr || ssg || pageType === 'app'
const isAnAPIRoute = isAPIRoute(page?.replace(/^(?:\/src)?\/pages\//, '/'))
resolvedRuntime =
isEdgeRuntime(resolvedRuntime) || requiresServerRuntime
? resolvedRuntime
: undefined
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page! : null)
}
if (
resolvedRuntime === SERVER_RUNTIME.edge &&
pageType === 'pages' &&
page &&
!isAnAPIRoute
) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`
if (isDev) {
Log.error(message)
} else {
throw new Error(message)
}
}
const middlewareConfig = getMiddlewareConfig(
page ?? 'middleware/edge API route',
config,
nextConfig
)
if (
pageType === 'app' &&
directives?.has('client') &&
generateStaticParams
) {
throw new Error(
`Page "${page}" cannot use both "use client" and export function "generateStaticParams()".`
)
}
return {
ssr,
ssg,
rsc,
generateStaticParams,
amp: config.amp || false,
...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }),
preferredRegion,
extraConfig,
}
}
return {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
generateStaticParams: false,
amp: false,
runtime: undefined,
}
}