Unverified Commit b8b13af1 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Refactor TS plugin code structure (#45375)

This PR mainly refactors the TS plugin structure and moves things over the typescript/ folder under server/. I created a rules/ folder to separate different kinds of insights, current it covers:
- Intellisense for entries on the server layer:
  - Hide autocompletions for disallowed APIs such as `useState`
  - Show errors if these are used
- Intellisense for all entires:
  - Prop hints such as `params` and `searchParams` for pages, and named slots for layouts
  - Error for invalid props
- Intellisense for exported configs:
  - Autocompletion and docs for configs
  - Hover hints for configs
  - Error for invalid configs and extra exports
- Intellisense for client boundary modules
  - Warn if `"use client"` isn't on the top of other expressions
  - (**new**) Error for unserializable props passed to exported functions

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 3421b482
/** export { createTSPlugin } from './typescript'
* 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 LEGACY_CONFIG_EXPORT = 'config'
const ALLOWED_EXPORTS = [
'config',
'generateStaticParams',
'metadata',
'generateMetadata',
]
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,
INVALID_CONFIG_OPTION: 71006,
}
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 `cookies`, `headers` 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.',
'"edge"': 'Prefer the Edge 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 declaration of node.declarationList.declarations) {
if (
declaration.getFullStart() <= position &&
position <=
declaration.getFullStart() + declaration.getFullWidth()
) {
// `export const ... = ...`
const text = declaration.name.getText()
callback(text, declaration)
}
}
}
}
}
})
}
}
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, declaration) => {
if (!API_DOCS[entryConfig]) {
if (
declaration.name.getFullStart() <= position &&
position <=
declaration.name.getFullStart() + declaration.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)
) {
// Default export function might not accept parameters
const paramNode = (node as ts.FunctionDeclaration).parameters?.[0] as
| ts.ParameterDeclaration
| undefined
if (paramNode && 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, declaration) => {
if (!API_DOCS[entryConfig]) return
const name = declaration.name
const value = declaration.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 declaration of node.declarationList.declarations) {
const name = declaration.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 = declaration.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 (name.text === LEGACY_CONFIG_EXPORT) {
// export const config = { ... }
// Error if using `amp: ...`
const value = declaration.initializer
if (value && ts.isObjectLiteralExpression(value)) {
for (const prop of value.properties) {
if (
ts.isPropertyAssignment(prop) &&
ts.isIdentifier(prop.name) &&
prop.name.text === 'amp'
) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CONFIG_OPTION,
messageText: `AMP is not supported in the app directory. If you need to use AMP it will continue to be supported in the pages directory.`,
start: prop.getStart(),
length: prop.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 }
}
export const NEXT_TS_ERRORS = {
INVALID_SERVER_API: 71001,
INVALID_ENTRY_EXPORT: 71002,
INVALID_OPTION_VALUE: 71003,
MISPLACED_CLIENT_ENTRY: 71004,
INVALID_PAGE_PROP: 71005,
INVALID_CONFIG_OPTION: 71006,
INVALID_CLIENT_ENTRY_PROP: 71007,
}
export const ALLOWED_EXPORTS = [
'config',
'generateStaticParams',
'metadata',
'generateMetadata',
]
export const LEGACY_CONFIG_EXPORT = 'config'
export const DISALLOWED_SERVER_REACT_APIS: string[] = [
'useState',
'useEffect',
'useLayoutEffect',
'useDeferredValue',
'useImperativeHandle',
'useInsertionEffect',
'useReducer',
'useRef',
'useSyncExternalStore',
'useTransition',
'Component',
'PureComponent',
'createContext',
'createFactory',
]
export const ALLOWED_PAGE_PROPS = ['params', 'searchParams']
export const ALLOWED_LAYOUT_PROPS = ['params', 'children']
/**
* 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 {
init,
getIsClientEntry,
isAppEntryFile,
isDefaultFunctionExport,
isPositionInsideNode,
getSource,
} from './utils'
import { NEXT_TS_ERRORS } from './constant'
import entryConfig from './rules/config'
import serverLayer from './rules/server'
import entryDefault from './rules/entry'
import clientBoundary from './rules/client-boundary'
export function createTSPlugin(modules: {
typescript: typeof import('typescript/lib/tsserverlibrary')
}) {
const ts = modules.typescript
function create(info: ts.server.PluginCreateInfo) {
init({
ts,
info,
})
// 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 = serverLayer.filterCompletionsAtPosition(prior.entries)
}
// Add auto completions for export configs.
const entries = entryConfig.getCompletionsAtPosition(fileName, position)
prior.entries = [...prior.entries, ...entries]
const source = getSource(fileName)
if (!source) return prior
ts.forEachChild(source!, (node) => {
// Auto completion for default export function's props.
if (
isPositionInsideNode(position, node) &&
isDefaultFunctionExport(node)
) {
prior.entries.push(
...entryDefault.getCompletionsAtPosition(
fileName,
node as ts.FunctionDeclaration,
position
)
)
}
})
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
) => {
const entryCompletionEntryDetails = entryConfig.getCompletionEntryDetails(
entryName,
data
)
if (entryCompletionEntryDetails) return entryCompletionEntryDetails
return info.languageService.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
source,
preferences,
data
)
}
// 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 &&
serverLayer.hasDisallowedReactAPIDefinition(definitions)
) {
return
}
}
const overriden = entryConfig.getQuickInfoAtPosition(fileName, position)
if (overriden) return overriden
return prior
}
// Show errors for disallowed imports
proxy.getSemanticDiagnostics = (fileName: string) => {
const prior = info.languageService.getSemanticDiagnostics(fileName)
const source = getSource(fileName)
if (!source) return prior
let isClientEntry = false
const isAppEntry = isAppEntryFile(fileName)
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 (isAppEntry) {
if (!isClientEntry) {
// Check if it has valid imports in the server layer
const diagnostics =
serverLayer.getSemanticDiagnosticsForImportDeclaration(
source,
node
)
prior.push(...diagnostics)
}
}
} else if (
ts.isVariableStatement(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
// export const ...
if (isAppEntry) {
// Check if it has correct option exports
const diagnostics =
entryConfig.getSemanticDiagnosticsForExportVariableStatement(
source,
node
)
prior.push(...diagnostics)
}
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForExportVariableStatement(
source,
node
)
)
}
} else if (isDefaultFunctionExport(node)) {
// export default function ...
if (isAppEntry) {
const diagnostics = entryDefault.getSemanticDiagnostics(
fileName,
source,
node
)
prior.push(...diagnostics)
}
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
node
)
)
}
} else if (
ts.isFunctionDeclaration(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
// export function ...
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
node
)
)
}
}
})
return prior
}
return proxy
}
return { create }
}
// This module provides intellisense for all components that has the `"use client"` directive.
import { NEXT_TS_ERRORS } from '../constant'
import { getTs, getTypeChecker } from '../utils'
const clientBoundary = {
getSemanticDiagnosticsForExportVariableStatement(
source: ts.SourceFile,
node: ts.VariableStatement
) {
const ts = getTs()
const diagnostics: ts.Diagnostic[] = []
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declaration of node.declarationList.declarations) {
const initializer = declaration.initializer
if (initializer && ts.isArrowFunction(initializer)) {
diagnostics.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
initializer
)
)
}
}
}
return diagnostics
},
getSemanticDiagnosticsForFunctionExport(
source: ts.SourceFile,
node: ts.FunctionDeclaration | ts.ArrowFunction
) {
const ts = getTs()
const typeChecker = getTypeChecker()
if (!typeChecker) return []
const diagnostics: ts.Diagnostic[] = []
const props = node.parameters?.[0]?.name
if (props && ts.isObjectBindingPattern(props)) {
for (const prop of (props as ts.ObjectBindingPattern).elements) {
const type = typeChecker.getTypeAtLocation(prop)
const typeDeclarationNode = type.symbol?.getDeclarations()?.[0]
const propName = (prop.propertyName || prop.name).getText()
if (typeDeclarationNode) {
if (
// Show errors for not serializable props.
ts.isFunctionOrConstructorTypeNode(typeDeclarationNode) ||
ts.isClassDeclaration(typeDeclarationNode)
) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP,
messageText: `All props must be serializable for client components in the entry file, "${propName}" is invalid.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
}
return diagnostics
},
}
export default clientBoundary
// This module provides intellisense for page and layout's exported configs.
import {
getSource,
isPositionInsideNode,
getTs,
removeStringQuotes,
} from '../utils'
import {
NEXT_TS_ERRORS,
ALLOWED_EXPORTS,
LEGACY_CONFIG_EXPORT,
} from '../constant'
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 `cookies`, `headers` 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.',
'"edge"': 'Prefer the Edge runtime.',
'"experimental-edge"': 'Prefer the experimental Edge runtime.',
},
link: 'https://beta.nextjs.org/docs/api-reference/segment-config#runtime',
},
}
function visitEntryConfig(
fileName: string,
position: number,
callback: (entryEonfig: string, value: ts.VariableDeclaration) => void
) {
const source = getSource(fileName)
if (source) {
const ts = getTs()
ts.forEachChild(source, function visit(node) {
// Covered by this node
if (isPositionInsideNode(position, node)) {
// Export variable
if (
ts.isVariableStatement(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declaration of node.declarationList.declarations) {
if (
declaration.getFullStart() <= position &&
position <=
declaration.getFullStart() + declaration.getFullWidth()
) {
// `export const ... = ...`
const text = declaration.name.getText()
callback(text, declaration)
}
}
}
}
}
})
}
}
function createAutoCompletionOptionName(sort: number, name: string) {
const ts = getTs()
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 ts = getTs()
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 getAPIDescription(api: string): string {
return (
API_DOCS[api].description +
'\n\n' +
Object.entries(API_DOCS[api].options)
.map(([key, value]) => `- \`${key}\`: ${value}`)
.join('\n')
)
}
const config = {
// Auto completion for entry exported configs.
getCompletionsAtPosition(fileName: string, position: number) {
const entries: ts.CompletionEntry[] = []
visitEntryConfig(fileName, position, (entryConfig, declaration) => {
if (!API_DOCS[entryConfig]) {
if (
declaration.name.getFullStart() <= position &&
position <=
declaration.name.getFullStart() + declaration.name.getFullWidth()
) {
entries.push(
...Object.keys(API_DOCS).map((name, index) => {
return createAutoCompletionOptionName(index, name)
})
)
}
return
}
entries.push(
...Object.keys(API_DOCS[entryConfig].options).map((name, index) => {
return createAutoCompletionOptionValue(index, name, entryConfig)
})
)
})
return entries
},
// Show docs when hovering on the exported configs.
getQuickInfoAtPosition(fileName: string, position: number) {
const ts = getTs()
let overriden: ts.QuickInfo | undefined
visitEntryConfig(fileName, position, (entryConfig, declaration) => {
if (!API_DOCS[entryConfig]) return
const name = declaration.name
const value = declaration.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,
],
}
}
})
return overriden
},
// Show details on the side when auto completing.
getCompletionEntryDetails(entryName: string, data: ts.CompletionEntryData) {
const ts = getTs()
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,
},
],
}
}
},
// Show errors for invalid export fields.
getSemanticDiagnosticsForExportVariableStatement(
source: ts.SourceFile,
node: ts.VariableStatement
) {
const ts = getTs()
const diagnostics: ts.Diagnostic[] = []
// Check if it has correct option exports
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declaration of node.declarationList.declarations) {
const name = declaration.name
if (ts.isIdentifier(name)) {
if (!ALLOWED_EXPORTS.includes(name.text) && !API_DOCS[name.text]) {
diagnostics.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 = declaration.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) {
diagnostics.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 (name.text === LEGACY_CONFIG_EXPORT) {
// export const config = { ... }
// Error if using `amp: ...`
const value = declaration.initializer
if (value && ts.isObjectLiteralExpression(value)) {
for (const prop of value.properties) {
if (
ts.isPropertyAssignment(prop) &&
ts.isIdentifier(prop.name) &&
prop.name.text === 'amp'
) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CONFIG_OPTION,
messageText: `AMP is not supported in the app directory. If you need to use AMP it will continue to be supported in the pages directory.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
}
}
}
}
return diagnostics
},
}
export default config
import path from 'path'
import fs from 'fs'
import {
ALLOWED_LAYOUT_PROPS,
ALLOWED_PAGE_PROPS,
NEXT_TS_ERRORS,
} from '../constant'
import { getTs, isPageFile, isPositionInsideNode } from '../utils'
const entry = {
// Give auto completion for the component's props
getCompletionsAtPosition(
fileName: string,
node: ts.FunctionDeclaration,
position: number
) {
const ts = getTs()
const entries: ts.CompletionEntry[] = []
// Default export function might not accept parameters
const paramNode = node.parameters?.[0] as
| ts.ParameterDeclaration
| undefined
if (paramNode && 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) {
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) {
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 entries
},
// Give error diagnostics for the component
getSemanticDiagnostics(
fileName: string,
source: ts.SourceFile,
node: ts.FunctionDeclaration
) {
const ts = getTs()
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 diagnostics: ts.Diagnostic[] = []
const props = node.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)) {
diagnostics.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 diagnostics
},
}
export default entry
import { DISALLOWED_SERVER_REACT_APIS, NEXT_TS_ERRORS } from '../constant'
import { getTs } from '../utils'
const serverLayer = {
// On the server layer we need to filter out some invalid completion results.
filterCompletionsAtPosition(entries: ts.CompletionEntry[]) {
return entries.filter((e: ts.CompletionEntry) => {
// Remove disallowed React APIs.
if (
DISALLOWED_SERVER_REACT_APIS.includes(e.name) &&
e.kindModifiers === 'declare'
) {
return false
}
return true
})
},
// Filter out quick info for some React APIs.
hasDisallowedReactAPIDefinition(definitions: readonly ts.DefinitionInfo[]) {
return definitions?.some(
(d) =>
DISALLOWED_SERVER_REACT_APIS.includes(d.name) &&
d.containerName === 'React'
)
},
// Give errors about disallowed imports such as `useState`.
getSemanticDiagnosticsForImportDeclaration(
source: ts.SourceFile,
node: ts.ImportDeclaration
) {
const ts = getTs()
const diagnostics: ts.Diagnostic[] = []
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)) {
diagnostics.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(),
})
}
}
}
}
}
return diagnostics
},
}
export default serverLayer
import path from 'path'
type TypeScript = typeof import('typescript/lib/tsserverlibrary')
let ts: TypeScript
let info: ts.server.PluginCreateInfo
let appDirRegExp: RegExp
export function log(message: string) {
info.project.projectService.logger.info(message)
}
// This function has to be called initially.
export function init(opts: {
ts: TypeScript
info: ts.server.PluginCreateInfo
}) {
ts = opts.ts
info = opts.info
const projectDir = info.project.getCurrentDirectory()
appDirRegExp = new RegExp(
'^' + (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]')
)
log('Starting Next.js TypeScript plugin: ' + projectDir)
}
export function getTs() {
return ts
}
export function getTypeChecker() {
return info.languageService.getProgram()?.getTypeChecker()
}
export function getSource(fileName: string) {
return info.languageService.getProgram()?.getSourceFile(fileName)
}
export function removeStringQuotes(str: string): string {
return str.replace(/^['"`]|['"`]$/g, '')
}
export const isPositionInsideNode = (position: number, node: ts.Node) => {
const start = node.getFullStart()
return start <= position && position <= node.getFullWidth() + start
}
export const isDefaultFunctionExport = (
node: ts.Node
): node is ts.FunctionDeclaration => {
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
}
export const isAppEntryFile = (filePath: string) => {
return (
appDirRegExp.test(filePath) &&
/^(page|layout)\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
export const isPageFile = (filePath: string) => {
return (
appDirRegExp.test(filePath) &&
/^page\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
// Check if a module is a client entry.
export 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
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment