/
next-typescript.ts
855 lines (793 loc) · 30.5 KB
/
next-typescript.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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/**
* This is a TypeScript language service plugin for Next.js app directory,
* it provides the following features:
*
* - Warns about disallowed React APIs in server components.
* - Warns about disallowed layout and page exports.
* - Autocompletion for entry configurations.
* - Hover hint and docs for entry configurations.
*/
import path from 'path'
import fs from 'fs'
const DISALLOWED_SERVER_REACT_APIS: string[] = [
'useState',
'useEffect',
'useLayoutEffect',
'useDeferredValue',
'useImperativeHandle',
'useInsertionEffect',
'useReducer',
'useRef',
'useSyncExternalStore',
'useTransition',
'Component',
'PureComponent',
'createContext',
'createFactory',
]
const ALLOWED_EXPORTS = ['config', 'generateStaticParams']
const ALLOWED_PAGE_PROPS = ['params', 'searchParams']
const ALLOWED_LAYOUT_PROPS = ['params', 'children']
const NEXT_TS_ERRORS = {
INVALID_SERVER_API: 71001,
INVALID_ENTRY_EXPORT: 71002,
INVALID_OPTION_VALUE: 71003,
MISPLACED_CLIENT_ENTRY: 71004,
INVALID_PAGE_PROP: 71005,
}
const API_DOCS: Record<
string,
{
description: string
options: Record<string, string>
link: string
type?: string
isValid?: (value: string) => boolean
getHint?: (value: any) => string
}
> = {
dynamic: {
description:
'The `dynamic` option provides a few ways to opt in or out of dynamic behavior.',
options: {
'"auto"':
'Heuristic to cache as much as possible but doesn’t prevent any component to opt-in to dynamic behavior.',
'"force-dynamic"':
'This disables all caching of fetches and always revalidates. (This is equivalent to `getServerSideProps`.)',
'"error"':
'This errors if any dynamic Hooks or fetches are used. (This is equivalent to `getStaticProps`.)',
'"force-static"':
'This forces caching of all fetches and returns empty values from `useCookies`, `useHeaders` and `useSearchParams`.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#dynamic',
},
fetchCache: {
description:
'The `fetchCache` option controls how Next.js statically caches fetches. By default it statically caches fetches reachable before any dynamic Hooks are used, and it doesn’t cache fetches that are discovered after that.',
options: {
'"force-no-store"':
"This lets you intentionally opt-out of all caching of data. This option forces all fetches to be refetched every request even if the `cache: 'force-cache'` option is passed to `fetch()`.",
'"only-no-store"':
"This lets you enforce that all data opts out of caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `no-store`.",
'"default-no-store"':
"Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'no-store'`. This means that even fetches before a dynamic Hook are considered dynamic.",
'"auto"':
'This is the default option. It caches any fetches with the default `cache` option provided, that happened before a dynamic Hook is used and don’t cache any such fetches if they’re issued after a dynamic Hook.',
'"default-cache"':
"Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'force-cache'`. This means that even fetches before a dynamic Hook are considered dynamic.",
'"only-cache"':
"This lets you enforce that all data opts into caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `force-cache`. This error can be discovered early during static builds - or dynamically during Edge rendering.",
'"force-cache"':
"This lets you intentionally opt-in to all caching of data. This option forces all fetches to be cache even if the `cache: 'no-store'` option is passed to `fetch()`.",
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#fetchcache',
},
preferredRegion: {
description:
'Specify the perferred region that this layout or page should be deployed to. If the region option is not specified, it inherits the option from the nearest parent layout. The root defaults to `"auto"`.',
options: {
'"auto"':
'Next.js will first deploy to the `"home"` region. Then if it doesn’t detect any waterfall requests after a few requests, it can upgrade that route, to be deployed globally to `"edge"`. If it detects any waterfall requests after that, it can eventually downgrade back to `"home`".',
'"home"': 'Prefer deploying to the Home region.',
'"edge"': 'Prefer deploying to the Edge globally.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#preferredregion',
},
revalidate: {
description:
'The `revalidate` option sets the default revalidation time for that layout or page. Note that it doesn’t override the value specify by each `fetch()`.',
type: 'mixed',
options: {
false:
'This is the default and changes the fetch cache to indefinitely cache anything that uses force-cache or is fetched before a dynamic Hook/fetch.',
0: 'Specifying `0` implies that this layout or page should never be static.',
30: 'Set the revalidation time to `30` seconds. The value can be `0` or any positive number.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#revalidate',
isValid: (value: string) => {
return value === 'false' || Number(value) >= 0
},
getHint: (value: any) => {
return `Set the default revalidation time to \`${value}\` seconds.`
},
},
dynamicParams: {
description:
'`dynamicParams` replaces the `fallback` option of `getStaticPaths`. It controls whether we allow `dynamicParams` beyond the generated static params from `generateStaticParams`.',
options: {
true: 'Allow rendering dynamic params that are not generated by `generateStaticParams`.',
false:
'Disallow rendering dynamic params that are not generated by `generateStaticParams`.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#dynamicparams',
},
runtime: {
description:
'The `runtime` option controls the preferred runtime to render this route.',
options: {
'"nodejs"': 'Prefer the Node.js runtime.',
'"experimental-edge"': 'Prefer the experimental Edge runtime.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#runtime',
},
}
function getAPIDescription(api: string): string {
return (
API_DOCS[api].description +
'\n\n' +
Object.entries(API_DOCS[api].options)
.map(([key, value]) => `- \`${key}\`: ${value}`)
.join('\n')
)
}
function removeStringQuotes(str: string): string {
return str.replace(/^['"`]|['"`]$/g, '')
}
export function createTSPlugin(modules: {
typescript: typeof import('typescript/lib/tsserverlibrary')
}) {
const ts = modules.typescript
function createAutoCompletionOptionName(sort: number, name: string) {
return {
name,
sortText: '' + sort,
kind: ts.ScriptElementKind.unknown,
kindModifiers: ts.ScriptElementKindModifier.exportedModifier,
labelDetails: {
description: `Next.js ${name} option`,
},
data: {
exportName: name,
moduleSpecifier: 'next/typescript/entry_option_name',
},
} as ts.CompletionEntry
}
function createAutoCompletionOptionValue(
sort: number,
name: string,
apiName: string
) {
const isString = name.startsWith('"')
return {
name,
insertText: removeStringQuotes(name),
sortText: '' + sort,
kind: isString
? ts.ScriptElementKind.string
: ts.ScriptElementKind.unknown,
kindModifiers: ts.ScriptElementKindModifier.none,
labelDetails: {
description: `Next.js ${apiName} option`,
},
data: {
exportName: apiName,
moduleSpecifier: 'next/typescript/entry_option_value',
},
} as ts.CompletionEntry
}
function create(info: ts.server.PluginCreateInfo) {
const projectDir = info.project.getCurrentDirectory()
const appDir = new RegExp(
'^' + (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]')
)
const isPositionInsideNode = (position: number, node: ts.Node) => {
const start = node.getFullStart()
return start <= position && position <= node.getFullWidth() + start
}
const isAppEntryFile = (filePath: string) => {
return (
appDir.test(filePath) &&
/^(page|layout)\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
const isPageFile = (filePath: string) => {
return (
appDir.test(filePath) &&
/^page\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
const isDefaultFunctionExport = (node: ts.Node) => {
if (ts.isFunctionDeclaration(node)) {
let hasExportKeyword = false
let hasDefaultKeyword = false
if (node.modifiers) {
for (const modifier of node.modifiers) {
if (modifier.kind === ts.SyntaxKind.ExportKeyword) {
hasExportKeyword = true
} else if (modifier.kind === ts.SyntaxKind.DefaultKeyword) {
hasDefaultKeyword = true
}
}
}
// `export default function`
if (hasExportKeyword && hasDefaultKeyword) {
return true
}
}
return false
}
function getIsClientEntry(
fileName: string,
throwOnInvalidDirective?: boolean
) {
const source = info.languageService.getProgram()?.getSourceFile(fileName)
if (source) {
let isClientEntry = false
let isDirective = true
ts.forEachChild(source!, (node) => {
if (
ts.isExpressionStatement(node) &&
ts.isStringLiteral(node.expression)
) {
if (node.expression.text === 'use client') {
if (isDirective) {
isClientEntry = true
} else {
if (throwOnInvalidDirective) {
const e = {
messageText:
'The `"use client"` directive must be put at the top of the file.',
start: node.expression.getStart(),
length: node.expression.getWidth(),
}
throw e
}
}
}
} else {
isDirective = false
}
})
return isClientEntry
}
return false
}
function visitEntryConfig(
fileName: string,
position: number,
callback: (entryEonfig: string, value: ts.VariableDeclaration) => void
) {
const source = info.languageService.getProgram()?.getSourceFile(fileName)
if (source) {
ts.forEachChild(source, function visit(node) {
// Covered by this node
if (
node.getFullStart() <= position &&
position <= node.getFullStart() + node.getFullWidth()
) {
// Export variable
if (
ts.isVariableStatement(node) &&
node.modifiers?.some(
(m) => m.kind === ts.SyntaxKind.ExportKeyword
)
) {
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declarartion of node.declarationList.declarations) {
if (
declarartion.getFullStart() <= position &&
position <=
declarartion.getFullStart() + declarartion.getFullWidth()
) {
// `export const ... = ...`
const text = declarartion.name.getText()
callback(text, declarartion)
}
}
}
}
}
})
}
}
function log(message: string) {
info.project.projectService.logger.info(message)
}
log('Starting Next.js TypeScript plugin: ' + projectDir)
// Set up decorator object
const proxy = Object.create(null)
for (let k of Object.keys(info.languageService)) {
const x = (info.languageService as any)[k]
proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args)
}
// Auto completion
proxy.getCompletionsAtPosition = (
fileName: string,
position: number,
options: any
) => {
let prior = info.languageService.getCompletionsAtPosition(
fileName,
position,
options
) || {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: [],
}
if (!isAppEntryFile(fileName)) return prior
// Remove specified entries from completion list if it's a server entry.
if (!getIsClientEntry(fileName)) {
prior.entries = prior.entries.filter((e: ts.CompletionEntry) => {
// Remove disallowed React APIs.
if (
DISALLOWED_SERVER_REACT_APIS.includes(e.name) &&
e.kindModifiers === 'declare'
) {
return false
}
return true
})
}
// Auto completion for entry exported configs.
visitEntryConfig(fileName, position, (entryConfig, declarartion) => {
if (!API_DOCS[entryConfig]) {
if (
declarartion.name.getFullStart() <= position &&
position <=
declarartion.name.getFullStart() +
declarartion.name.getFullWidth()
) {
prior.entries = [
...prior.entries,
...Object.keys(API_DOCS).map((name, index) => {
return createAutoCompletionOptionName(index, name)
}),
] as ts.CompletionEntry[]
}
return
}
prior.entries = [
...prior.entries,
...Object.keys(API_DOCS[entryConfig].options).map((name, index) => {
return createAutoCompletionOptionValue(index, name, entryConfig)
}),
] as ts.CompletionEntry[]
})
const program = info.languageService.getProgram()
const source = program?.getSourceFile(fileName)
if (!source || !program) return prior
ts.forEachChild(source!, (node) => {
// Auto completion for default export function's props.
if (
isDefaultFunctionExport(node) &&
isPositionInsideNode(position, node)
) {
const paramNode = (node as ts.FunctionDeclaration).parameters?.[0]
if (isPositionInsideNode(position, paramNode)) {
const props = paramNode?.name
if (props && ts.isObjectBindingPattern(props)) {
let validProps = []
let validPropsWithType = []
let type: string
if (isPageFile(fileName)) {
// For page entries (page.js), it can only have `params` and `searchParams`
// as the prop names.
validProps = ALLOWED_PAGE_PROPS
validPropsWithType = ALLOWED_PAGE_PROPS
type = 'page'
} else {
// For layout entires, check if it has any named slots.
const currentDir = path.dirname(fileName)
const items = fs.readdirSync(currentDir, {
withFileTypes: true,
})
const slots = []
for (const item of items) {
if (item.isDirectory() && item.name.startsWith('@')) {
slots.push(item.name.slice(1))
}
}
validProps = ALLOWED_LAYOUT_PROPS.concat(slots)
validPropsWithType = ALLOWED_LAYOUT_PROPS.concat(
slots.map((s) => `${s}: React.ReactNode`)
)
type = 'layout'
}
// Auto completion for props
for (const element of props.elements) {
if (isPositionInsideNode(position, element)) {
const nameNode = element.propertyName || element.name
if (isPositionInsideNode(position, nameNode)) {
for (const name of validProps) {
prior.entries.push({
name,
insertText: name,
sortText: '_' + name,
kind: ts.ScriptElementKind.memberVariableElement,
kindModifiers: ts.ScriptElementKindModifier.none,
labelDetails: {
description: `Next.js ${type} prop`,
},
} as ts.CompletionEntry)
}
}
break
}
}
// Auto completion for types
if (paramNode.type && ts.isTypeLiteralNode(paramNode.type)) {
for (const member of paramNode.type.members) {
if (isPositionInsideNode(position, member)) {
for (const name of validPropsWithType) {
prior.entries.push({
name,
insertText: name,
sortText: '_' + name,
kind: ts.ScriptElementKind.memberVariableElement,
kindModifiers: ts.ScriptElementKindModifier.none,
labelDetails: {
description: `Next.js ${type} prop type`,
},
} as ts.CompletionEntry)
}
break
}
}
}
}
}
}
})
return prior
}
// Show auto completion details
proxy.getCompletionEntryDetails = (
fileName: string,
position: number,
entryName: string,
formatOptions: ts.FormatCodeOptions,
source: string,
preferences: ts.UserPreferences,
data: ts.CompletionEntryData
) => {
if (
data &&
data.moduleSpecifier &&
data.moduleSpecifier.startsWith('next/typescript')
) {
let content = ''
if (data.moduleSpecifier === 'next/typescript/entry_option_name') {
content = getAPIDescription(entryName)
} else {
content = API_DOCS[data.exportName].options[entryName]
}
return {
name: entryName,
kind: ts.ScriptElementKind.enumElement,
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts: [],
documentation: [
{
kind: 'text',
text: content,
},
],
}
}
const prior = info.languageService.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
source,
preferences,
data
)
return prior
}
// Quick info
proxy.getQuickInfoAtPosition = (fileName: string, position: number) => {
const prior = info.languageService.getQuickInfoAtPosition(
fileName,
position
)
if (!isAppEntryFile(fileName)) return prior
// Remove type suggestions for disallowed APIs in server components.
if (!getIsClientEntry(fileName)) {
const definitions = info.languageService.getDefinitionAtPosition(
fileName,
position
)
if (
definitions?.some(
(d) =>
DISALLOWED_SERVER_REACT_APIS.includes(d.name) &&
d.containerName === 'React'
)
) {
return
}
}
let overriden: ts.QuickInfo | undefined
visitEntryConfig(fileName, position, (entryConfig, declarartion) => {
if (!API_DOCS[entryConfig]) return
const name = declarartion.name
const value = declarartion.initializer
const docsLink = {
kind: 'text',
text:
`\n\nRead more about the "${entryConfig}" option: ` +
API_DOCS[entryConfig].link,
}
if (
value &&
value.getFullStart() <= position &&
value.getFullStart() + value.getFullWidth() >= position
) {
// Hovers the value of the config
const isString = ts.isStringLiteral(value)
const text = removeStringQuotes(value.getText())
const key = isString ? `"${text}"` : text
const isValid = API_DOCS[entryConfig].isValid
? API_DOCS[entryConfig].isValid?.(key)
: !!API_DOCS[entryConfig].options[key]
if (isValid) {
overriden = {
kind: ts.ScriptElementKind.enumElement,
kindModifiers: ts.ScriptElementKindModifier.none,
textSpan: {
start: value.getStart(),
length: value.getWidth(),
},
displayParts: [],
documentation: [
{
kind: 'text',
text:
API_DOCS[entryConfig].options[key] ||
API_DOCS[entryConfig].getHint?.(key) ||
'',
},
docsLink,
],
}
} else {
// Wrong value, display the docs link
overriden = {
kind: ts.ScriptElementKind.enumElement,
kindModifiers: ts.ScriptElementKindModifier.none,
textSpan: {
start: value.getStart(),
length: value.getWidth(),
},
displayParts: [],
documentation: [docsLink],
}
}
} else {
// Hovers the name of the config
overriden = {
kind: ts.ScriptElementKind.enumElement,
kindModifiers: ts.ScriptElementKindModifier.none,
textSpan: {
start: name.getStart(),
length: name.getWidth(),
},
displayParts: [],
documentation: [
{
kind: 'text',
text: getAPIDescription(entryConfig),
},
docsLink,
],
}
}
})
if (overriden) return overriden
return prior
}
// Show errors for disallowed imports
proxy.getSemanticDiagnostics = (fileName: string) => {
const prior = info.languageService.getSemanticDiagnostics(fileName)
if (!isAppEntryFile(fileName)) return prior
const program = info.languageService.getProgram()
const source = program?.getSourceFile(fileName)
if (!source || !program) return prior
let isClientEntry = false
try {
isClientEntry = getIsClientEntry(fileName, true)
} catch (e: any) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.MISPLACED_CLIENT_ENTRY,
...e,
})
isClientEntry = false
}
ts.forEachChild(source!, (node) => {
if (ts.isImportDeclaration(node)) {
if (!isClientEntry) {
const importPath = node.moduleSpecifier.getText(source!)
if (importPath === "'react'" || importPath === '"react"') {
// Check if it imports "useState"
const importClause = node.importClause
if (importClause) {
const namedBindings = importClause.namedBindings
if (namedBindings && ts.isNamedImports(namedBindings)) {
const elements = namedBindings.elements
for (const element of elements) {
const name = element.name.getText(source!)
if (DISALLOWED_SERVER_REACT_APIS.includes(name)) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_SERVER_API,
messageText: `"${name}" is not allowed in Server Components.`,
start: element.name.getStart(),
length: element.name.getWidth(),
})
}
}
}
}
}
}
} else if (
ts.isVariableStatement(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
// Check if it has correct option exports
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declarartion of node.declarationList.declarations) {
const name = declarartion.name
if (ts.isIdentifier(name)) {
if (
!ALLOWED_EXPORTS.includes(name.text) &&
!API_DOCS[name.text]
) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_ENTRY_EXPORT,
messageText: `"${name.text}" is not a valid Next.js entry export value.`,
start: name.getStart(),
length: name.getWidth(),
})
} else if (API_DOCS[name.text]) {
// Check if the value is valid
const value = declarartion.initializer
if (value) {
let displayedValue = ''
let errorMessage = ''
let isInvalid = false
if (
ts.isStringLiteral(value) ||
ts.isNoSubstitutionTemplateLiteral(value)
) {
const text = removeStringQuotes(value.getText())
const allowedValues = Object.keys(
API_DOCS[name.text].options
)
.filter((v) => /^['"]/.test(v))
.map(removeStringQuotes)
if (!allowedValues.includes(text)) {
isInvalid = true
displayedValue = `'${text}'`
}
} else if (
ts.isNumericLiteral(value) ||
(ts.isPrefixUnaryExpression(value) &&
ts.isMinusToken((value as any).operator) &&
(ts.isNumericLiteral((value as any).operand.kind) ||
(ts.isIdentifier((value as any).operand.kind) &&
(value as any).operand.kind.getText() ===
'Infinity'))) ||
(ts.isIdentifier(value) && value.getText() === 'Infinity')
) {
const v = value.getText()
if (API_DOCS[name.text].isValid?.(v) === false) {
isInvalid = true
displayedValue = v
}
} else if (
value.kind === ts.SyntaxKind.TrueKeyword ||
value.kind === ts.SyntaxKind.FalseKeyword
) {
const v = value.getText()
if (API_DOCS[name.text].isValid?.(v) === false) {
isInvalid = true
displayedValue = v
}
} else if (
// Other literals
ts.isBigIntLiteral(value) ||
ts.isArrayLiteralExpression(value) ||
ts.isObjectLiteralExpression(value) ||
ts.isRegularExpressionLiteral(value) ||
ts.isPrefixUnaryExpression(value)
) {
isInvalid = true
displayedValue = value.getText()
} else {
// Not a literal, error because it's not statically analyzable
isInvalid = true
displayedValue = value.getText()
errorMessage = `"${displayedValue}" is not a valid value for the "${name.text}" option. The configuration must be statically analyzable.`
}
if (isInvalid) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_OPTION_VALUE,
messageText:
errorMessage ||
`"${displayedValue}" is not a valid value for the "${name.text}" option.`,
start: value.getStart(),
length: value.getWidth(),
})
}
}
}
}
}
}
} else if (isDefaultFunctionExport(node)) {
// `export default function`
let validProps = []
let type: string
if (isPageFile(fileName)) {
// For page entries (page.js), it can only have `params` and `searchParams`
// as the prop names.
validProps = ALLOWED_PAGE_PROPS
type = 'page'
} else {
// For layout entires, check if it has any named slots.
const currentDir = path.dirname(fileName)
const items = fs.readdirSync(currentDir, { withFileTypes: true })
const slots = []
for (const item of items) {
if (item.isDirectory() && item.name.startsWith('@')) {
slots.push(item.name.slice(1))
}
}
validProps = ALLOWED_LAYOUT_PROPS.concat(slots)
type = 'layout'
}
const props = (node as ts.FunctionDeclaration).parameters?.[0]?.name
if (props && ts.isObjectBindingPattern(props)) {
for (const prop of (props as ts.ObjectBindingPattern).elements) {
const propName = (prop.propertyName || prop.name).getText()
if (!validProps.includes(propName)) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_PAGE_PROP,
messageText: `"${propName}" is not a valid ${type} prop.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
}
})
return prior
}
return proxy
}
return { create }
}