Unverified Commit ac86a613 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Refactor extractExportedConstValue to return { value } | null instead of throwing (#90510)

## Summary

Refactors `extractExportedConstValue` and the internal `extractValue` function to use return values instead of exception-based control flow, improving performance during build analysis.

### Commit 1: Refactor `extractExportedConstValue`
- Returns `{ value: any } | null` instead of throwing `NoSuchDeclarationError`
- `null` when the exported const declaration is not found, `{ value }` when found
- Removes `NoSuchDeclarationError` class

### Commit 2: Refactor `extractValue`
- Returns `ExtractValueResult` (`{ value: any } | { unsupported: string; path?: string }`) instead of throwing `UnsupportedValueError`
- Extracts path-formatting logic from `UnsupportedValueError` constructor into a standalone `formatCodePath` helper
- All 6 throw sites become return statements; 3 recursive call sites propagate unsupported results
- Removes `UnsupportedValueError` class entirely
- Removes all try/catch blocks from the 4 callsites in `get-page-static-info.ts`
- Updates `warnAboutUnsupportedValue` to accept the result type directly

## Motivation

Both `extractExportedConstValue` and `extractValue` used throw/catch for expected control flow — a missing declaration and unsupported AST node types are normal cases during build analysis, not exceptional errors. Every page/route processed during build hits these functions multiple times. Constructing `Error` objects (which capture stack traces) and unwinding the stack is expensive in V8. Returning discriminated result types avoids this overhead entirely.

## Test Plan

- Existing unit tests pass (`test/unit/parse-page-static-info.test.ts` — 5/5)
- No behavioral change: callsites produce identical warnings/errors for unsupported values and silently skip missing declarations, same as before
parent 01d75f69
......@@ -16,8 +16,6 @@ import type {
VariableDeclaration,
} from '@swc/core'
export class NoSuchDeclarationError extends Error {}
function isExportDeclaration(node: Node): node is ExportDeclaration {
return node.type === 'ExportDeclaration'
}
......@@ -70,60 +68,52 @@ function isTsSatisfiesExpression(node: Node): node is TsSatisfiesExpression {
return node.type === 'TsSatisfiesExpression'
}
export class UnsupportedValueError extends Error {
/** @example `config.runtime[0].value` */
path?: string
constructor(message: string, paths?: string[]) {
super(message)
// Generating "path" that looks like "config.runtime[0].value"
let codePath: string | undefined
if (paths) {
codePath = ''
for (const path of paths) {
if (path[0] === '[') {
// "array" + "[0]"
codePath += path
} else {
if (codePath === '') {
codePath = path
} else {
// "object" + ".key"
codePath += `.${path}`
}
}
}
export type ExtractValueResult =
| { value: any }
| { unsupported: string; path?: string }
/** Formats a path array like `["config", "runtime", "[0]", "value"]` → `"config.runtime[0].value"` */
function formatCodePath(paths?: string[]): string | undefined {
if (!paths) return undefined
let codePath = ''
for (const path of paths) {
if (path[0] === '[') {
// "array" + "[0]"
codePath += path
} else if (codePath === '') {
codePath = path
} else {
// "object" + ".key"
codePath += `.${path}`
}
this.path = codePath
}
return codePath
}
function extractValue(node: Node, path?: string[]): any {
function extractValue(node: Node, path?: string[]): ExtractValueResult {
if (isNullLiteral(node)) {
return null
return { value: null }
} else if (isBooleanLiteral(node)) {
// e.g. true / false
return node.value
return { value: node.value }
} else if (isStringLiteral(node)) {
// e.g. "abc"
return node.value
return { value: node.value }
} else if (isNumericLiteral(node)) {
// e.g. 123
return node.value
return { value: node.value }
} else if (isRegExpLiteral(node)) {
// e.g. /abc/i
return new RegExp(node.pattern, node.flags)
return { value: new RegExp(node.pattern, node.flags) }
} else if (isIdentifier(node)) {
switch (node.value) {
case 'undefined':
return undefined
return { value: undefined }
default:
throw new UnsupportedValueError(
`Unknown identifier "${node.value}"`,
path
)
return {
unsupported: `Unknown identifier "${node.value}"`,
path: formatCodePath(path),
}
}
} else if (isArrayExpression(node)) {
// e.g. [1, 2, 3]
......@@ -133,30 +123,35 @@ function extractValue(node: Node, path?: string[]): any {
if (elem) {
if (elem.spread) {
// e.g. [ ...a ]
throw new UnsupportedValueError(
'Unsupported spread operator in the Array Expression',
path
)
return {
unsupported: 'Unsupported spread operator in the Array Expression',
path: formatCodePath(path),
}
}
arr.push(extractValue(elem.expression, path && [...path, `[${i}]`]))
const result = extractValue(
elem.expression,
path && [...path, `[${i}]`]
)
if ('unsupported' in result) return result
arr.push(result.value)
} else {
// e.g. [1, , 2]
// ^^
arr.push(undefined)
}
}
return arr
return { value: arr }
} else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 }
const obj: any = {}
for (const prop of node.properties) {
if (!isKeyValueProperty(prop)) {
// e.g. { ...a }
throw new UnsupportedValueError(
'Unsupported spread operator in the Object Expression',
path
)
return {
unsupported: 'Unsupported spread operator in the Object Expression',
path: formatCodePath(path),
}
}
let key
......@@ -167,24 +162,26 @@ function extractValue(node: Node, path?: string[]): any {
// e.g. { "a": 1, "b": 2 }
key = prop.key.value
} else {
throw new UnsupportedValueError(
`Unsupported key type "${prop.key.type}" in the Object Expression`,
path
)
return {
unsupported: `Unsupported key type "${prop.key.type}" in the Object Expression`,
path: formatCodePath(path),
}
}
obj[key] = extractValue(prop.value, path && [...path, key])
const result = extractValue(prop.value, path && [...path, key])
if ('unsupported' in result) return result
obj[key] = result.value
}
return obj
return { value: obj }
} else if (isTemplateLiteral(node)) {
// e.g. `abc`
if (node.expressions.length !== 0) {
// TODO: should we add support for `${'e'}d${'g'}'e'`?
throw new UnsupportedValueError(
'Unsupported template literal with expressions',
path
)
return {
unsupported: 'Unsupported template literal with expressions',
path: formatCodePath(path),
}
}
// When TemplateLiteral has 0 expressions, the length of quasis is always 1.
......@@ -198,21 +195,21 @@ function extractValue(node: Node, path?: string[]): any {
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
const [{ cooked, raw }] = node.quasis
return cooked ?? raw
return { value: cooked ?? raw }
} else if (isTsSatisfiesExpression(node)) {
return extractValue(node.expression)
} else {
throw new UnsupportedValueError(
`Unsupported node type "${node.type}"`,
path
)
return {
unsupported: `Unsupported node type "${node.type}"`,
path: formatCodePath(path),
}
}
}
/**
* Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError):
* The value must be one of (or returns unsupported):
* - string
* - boolean
* - number
......@@ -221,12 +218,14 @@ function extractValue(node: Node, path?: string[]): any {
* - array containing values listed in this list
* - object containing values listed in this list
*
* Throws NoSuchDeclarationError if the declaration is not found.
* Returns null if the declaration is not found.
* Returns { unsupported, path? } if the value contains unsupported nodes.
*/
export function extractExportedConstValue(
module: Module,
module: Module | null,
exportedName: string
): any {
): ExtractValueResult | null {
if (!module) return null
for (const moduleItem of module.body) {
if (!isExportDeclaration(moduleItem)) {
continue
......@@ -252,5 +251,5 @@ export function extractExportedConstValue(
}
}
throw new NoSuchDeclarationError()
return null
}
......@@ -4,10 +4,7 @@ import type { RouteHas } from '../../lib/load-custom-routes'
import { readFileSync } from 'fs'
import { relative } from 'path'
import { LRUCache } from '../../server/lib/lru-cache'
import {
extractExportedConstValue,
UnsupportedValueError,
} from './extract-const-value'
import { extractExportedConstValue } from './extract-const-value'
import { parseModule } from './parse-module'
import * as Log from '../output/log'
import {
......@@ -568,7 +565,7 @@ const warnedUnsupportedValueMap = new LRUCache<boolean>(250, () => 1)
function warnAboutUnsupportedValue(
pageFilePath: string,
page: string | undefined,
error: UnsupportedValueError
result: { unsupported: string; path?: string }
) {
hadUnsupportedValue = true
const isProductionBuild = process.env.NODE_ENV === 'production'
......@@ -587,8 +584,8 @@ function warnAboutUnsupportedValue(
`Next.js can't recognize the exported \`config\` field in ` +
(page ? `route "${page}"` : `"${pageFilePath}"`) +
':\n' +
error.message +
(error.path ? ` at "${error.path}"` : '') +
result.unsupported +
(result.path ? ` at "${result.path}"` : '') +
'.\n' +
'Read More - https://nextjs.org/docs/messages/invalid-page-config'
......@@ -648,23 +645,20 @@ export async function getAppPageStaticInfo({
const exportedConfig: Record<string, unknown> = {}
if (exports) {
for (const property of exports) {
try {
exportedConfig[property] = extractExportedConstValue(ast, property)
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
const result = extractExportedConstValue(ast, property)
if (result !== null && 'unsupported' in result) {
warnAboutUnsupportedValue(pageFilePath, page, result)
} else if (result !== null) {
exportedConfig[property] = result.value
}
}
}
try {
exportedConfig.config = extractExportedConstValue(ast, 'config')
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
const configResult = extractExportedConstValue(ast, 'config')
if (configResult !== null && 'unsupported' in configResult) {
warnAboutUnsupportedValue(pageFilePath, page, configResult)
} else if (configResult !== null) {
exportedConfig.config = configResult.value
}
const route = normalizeAppPath(page)
......@@ -749,23 +743,20 @@ export async function getPagesPageStaticInfo({
const exportedConfig: Record<string, unknown> = {}
if (exports) {
for (const property of exports) {
try {
exportedConfig[property] = extractExportedConstValue(ast, property)
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
const result = extractExportedConstValue(ast, property)
if (result !== null && 'unsupported' in result) {
warnAboutUnsupportedValue(pageFilePath, page, result)
} else if (result !== null) {
exportedConfig[property] = result.value
}
}
}
try {
exportedConfig.config = extractExportedConstValue(ast, 'config')
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
const configResult = extractExportedConstValue(ast, 'config')
if (configResult !== null && 'unsupported' in configResult) {
warnAboutUnsupportedValue(pageFilePath, page, configResult)
} else if (configResult !== null) {
exportedConfig.config = configResult.value
}
// Validate the config.
......
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