Skip to content

Commit 34a039e

Browse files
authored
fix: gracefully handle missing static analysis tools (#1691)
1 parent 0ca3e77 commit 34a039e

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

packages/runtime/src/helpers/analysis.ts

+27-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import fs, { existsSync } from 'fs'
22

3-
import { extractExportedConstValue, UnsupportedValueError } from 'next/dist/build/analysis/extract-const-value'
4-
import { parseModule } from 'next/dist/build/analysis/parse-module'
53
import { relative } from 'pathe'
64

75
// I have no idea what eslint is up to here but it gives an error
@@ -81,13 +79,39 @@ export const validateConfigValue = (config: ApiConfig, apiFilePath: string): con
8179
return false
8280
}
8381

82+
let extractConstValue
83+
let parseModule
84+
let hasWarnedAboutNextVersion = false
8485
/**
8586
* Uses Next's swc static analysis to extract the config values from a file.
8687
*/
8788
export const extractConfigFromFile = async (apiFilePath: string): Promise<ApiConfig> => {
8889
if (!apiFilePath || !existsSync(apiFilePath)) {
8990
return {}
9091
}
92+
93+
try {
94+
if (!extractConstValue) {
95+
extractConstValue = require('next/dist/build/analysis/extract-const-value')
96+
}
97+
if (!parseModule) {
98+
// eslint-disable-next-line prefer-destructuring, @typescript-eslint/no-var-requires
99+
parseModule = require('next/dist/build/analysis/parse-module').parseModule
100+
}
101+
} catch (error) {
102+
if (error.code === 'MODULE_NOT_FOUND') {
103+
if (!hasWarnedAboutNextVersion) {
104+
console.log("This version of Next.js doesn't support advanced API routes. Skipping...")
105+
hasWarnedAboutNextVersion = true
106+
}
107+
// Old Next.js version
108+
return {}
109+
}
110+
throw error
111+
}
112+
113+
const { extractExportedConstValue, UnsupportedValueError } = extractConstValue
114+
91115
const fileContent = await fs.promises.readFile(apiFilePath, 'utf8')
92116
// No need to parse if there's no "config"
93117
if (!fileContent.includes('config')) {
@@ -99,7 +123,7 @@ export const extractConfigFromFile = async (apiFilePath: string): Promise<ApiCon
99123
try {
100124
config = extractExportedConstValue(ast, 'config')
101125
} catch (error) {
102-
if (error instanceof UnsupportedValueError) {
126+
if (UnsupportedValueError && error instanceof UnsupportedValueError) {
103127
console.warn(`Unsupported config value in ${relative(process.cwd(), apiFilePath)}`)
104128
}
105129
return {}

0 commit comments

Comments
 (0)