|
| 1 | +import { existsSync } from 'node:fs' |
| 2 | +import { readFile } from 'node:fs/promises' |
| 3 | +import { join } from 'node:path' |
| 4 | + |
| 5 | +import type { PluginContext } from './plugin-context.js' |
| 6 | + |
| 7 | +interface FunctionsConfigManifest { |
| 8 | + version: number |
| 9 | + functions: Record<string, Record<string, string | number>> |
| 10 | +} |
| 11 | + |
| 12 | +// eslint-disable-next-line no-shadow |
| 13 | +export const enum ApiRouteType { |
| 14 | + SCHEDULED = 'experimental-scheduled', |
| 15 | + BACKGROUND = 'experimental-background', |
| 16 | +} |
| 17 | + |
| 18 | +interface ApiStandardConfig { |
| 19 | + type?: never |
| 20 | + runtime?: 'nodejs' | 'experimental-edge' | 'edge' |
| 21 | + schedule?: never |
| 22 | +} |
| 23 | + |
| 24 | +interface ApiScheduledConfig { |
| 25 | + type: ApiRouteType.SCHEDULED |
| 26 | + runtime?: 'nodejs' |
| 27 | + schedule: string |
| 28 | +} |
| 29 | + |
| 30 | +interface ApiBackgroundConfig { |
| 31 | + type: ApiRouteType.BACKGROUND |
| 32 | + runtime?: 'nodejs' |
| 33 | + schedule?: never |
| 34 | +} |
| 35 | + |
| 36 | +type ApiConfig = ApiStandardConfig | ApiScheduledConfig | ApiBackgroundConfig |
| 37 | + |
| 38 | +export async function getAPIRoutesConfigs(ctx: PluginContext) { |
| 39 | + const functionsConfigManifestPath = join( |
| 40 | + ctx.publishDir, |
| 41 | + 'server', |
| 42 | + 'functions-config-manifest.json', |
| 43 | + ) |
| 44 | + if (!existsSync(functionsConfigManifestPath)) { |
| 45 | + // before https://github.com/vercel/next.js/pull/60163 this file might not have been produced if there were no API routes at all |
| 46 | + return [] |
| 47 | + } |
| 48 | + |
| 49 | + const functionsConfigManifest = JSON.parse( |
| 50 | + await readFile(functionsConfigManifestPath, 'utf-8'), |
| 51 | + ) as FunctionsConfigManifest |
| 52 | + |
| 53 | + const appDir = ctx.resolveFromSiteDir('.') |
| 54 | + const pagesDir = join(appDir, 'pages') |
| 55 | + const srcPagesDir = join(appDir, 'src', 'pages') |
| 56 | + const { pageExtensions } = ctx.requiredServerFiles.config |
| 57 | + |
| 58 | + return Promise.all( |
| 59 | + Object.keys(functionsConfigManifest.functions).map(async (apiRoute) => { |
| 60 | + const filePath = getSourceFileForPage(apiRoute, [pagesDir, srcPagesDir], pageExtensions) |
| 61 | + |
| 62 | + const sharedFields = { |
| 63 | + apiRoute, |
| 64 | + filePath, |
| 65 | + config: {} as ApiConfig, |
| 66 | + } |
| 67 | + |
| 68 | + if (filePath) { |
| 69 | + const config = await extractConfigFromFile(filePath, appDir) |
| 70 | + return { |
| 71 | + ...sharedFields, |
| 72 | + config, |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return sharedFields |
| 77 | + }), |
| 78 | + ) |
| 79 | +} |
| 80 | + |
| 81 | +// Next.js already defines a default `pageExtensions` array in its `required-server-files.json` file |
| 82 | +// In case it gets `undefined`, this is a fallback |
| 83 | +const SOURCE_FILE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'] |
| 84 | + |
| 85 | +/** |
| 86 | + * Find the source file for a given page route |
| 87 | + */ |
| 88 | +const getSourceFileForPage = ( |
| 89 | + page: string, |
| 90 | + roots: string[], |
| 91 | + pageExtensions = SOURCE_FILE_EXTENSIONS, |
| 92 | +) => { |
| 93 | + for (const root of roots) { |
| 94 | + for (const extension of pageExtensions) { |
| 95 | + const file = join(root, `${page}.${extension}`) |
| 96 | + if (existsSync(file)) { |
| 97 | + return file |
| 98 | + } |
| 99 | + |
| 100 | + const fileAtFolderIndex = join(root, page, `index.${extension}`) |
| 101 | + if (existsSync(fileAtFolderIndex)) { |
| 102 | + return fileAtFolderIndex |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +/** |
| 109 | + * Given an array of base paths and candidate modules, return the first one that exists |
| 110 | + */ |
| 111 | +const findModuleFromBase = ({ |
| 112 | + paths, |
| 113 | + candidates, |
| 114 | +}: { |
| 115 | + paths: string[] |
| 116 | + candidates: string[] |
| 117 | +}): string | null => { |
| 118 | + for (const candidate of candidates) { |
| 119 | + try { |
| 120 | + const modulePath = require.resolve(candidate, { paths }) |
| 121 | + if (modulePath) { |
| 122 | + return modulePath |
| 123 | + } |
| 124 | + } catch { |
| 125 | + // Ignore the error |
| 126 | + } |
| 127 | + } |
| 128 | + // if we couldn't find a module from paths, let's try to resolve from here |
| 129 | + for (const candidate of candidates) { |
| 130 | + try { |
| 131 | + const modulePath = require.resolve(candidate) |
| 132 | + if (modulePath) { |
| 133 | + return modulePath |
| 134 | + } |
| 135 | + } catch { |
| 136 | + // Ignore the error |
| 137 | + } |
| 138 | + } |
| 139 | + return null |
| 140 | +} |
| 141 | + |
| 142 | +let extractConstValue: typeof import('next/dist/build/analysis/extract-const-value.js') |
| 143 | +let parseModule: typeof import('next/dist/build/analysis/parse-module.js').parseModule |
| 144 | + |
| 145 | +const extractConfigFromFile = async (apiFilePath: string, appDir: string): Promise<ApiConfig> => { |
| 146 | + if (!apiFilePath || !existsSync(apiFilePath)) { |
| 147 | + return {} |
| 148 | + } |
| 149 | + |
| 150 | + const extractConstValueModulePath = findModuleFromBase({ |
| 151 | + paths: [appDir], |
| 152 | + candidates: ['next/dist/build/analysis/extract-const-value'], |
| 153 | + }) |
| 154 | + |
| 155 | + const parseModulePath = findModuleFromBase({ |
| 156 | + paths: [appDir], |
| 157 | + candidates: ['next/dist/build/analysis/parse-module'], |
| 158 | + }) |
| 159 | + |
| 160 | + if (!extractConstValueModulePath || !parseModulePath) { |
| 161 | + // Old Next.js version |
| 162 | + return {} |
| 163 | + } |
| 164 | + |
| 165 | + if (!extractConstValue && extractConstValueModulePath) { |
| 166 | + // eslint-disable-next-line import/no-dynamic-require, n/global-require |
| 167 | + extractConstValue = require(extractConstValueModulePath) |
| 168 | + } |
| 169 | + if (!parseModule && parseModulePath) { |
| 170 | + // eslint-disable-next-line prefer-destructuring, @typescript-eslint/no-var-requires, import/no-dynamic-require, n/global-require |
| 171 | + parseModule = require(parseModulePath).parseModule |
| 172 | + } |
| 173 | + |
| 174 | + const { extractExportedConstValue } = extractConstValue |
| 175 | + |
| 176 | + const fileContent = await readFile(apiFilePath, 'utf8') |
| 177 | + // No need to parse if there's no "config" |
| 178 | + if (!fileContent.includes('config')) { |
| 179 | + return {} |
| 180 | + } |
| 181 | + const ast = await parseModule(apiFilePath, fileContent) |
| 182 | + |
| 183 | + try { |
| 184 | + return extractExportedConstValue(ast, 'config') as ApiConfig |
| 185 | + } catch { |
| 186 | + return {} |
| 187 | + } |
| 188 | +} |
0 commit comments