Agents-Md Codemod Fails To Resolve Next.Js Version When Package.Json Uses Version Ranges
The @next/codemod agents-md transform incorrectly uses the raw version range (e.g., ^16) from package.json as the exact version, leading to attempts to download non-existent documentation for Next.js v16 instead of the installed 16.1.6.
The codemod extracts the 'next' dependency version string directly from package.json without resolving it to the actual installed version via node_modules or a lockfile. It then uses that string to construct a GitHub documentation URL, which fails for ranges like ^16 because no 'v16' tag exists in the docs repository.
1. Create a project with next: "^16" in package.json dependencies.
2. Run `npx @next/codemod@canary agents-md --output AGENTS.md`.
3. Observe the error: 'Downloading Next.js 16 documentation to .next-docs... Failed to pull docs: Could not find documentation for Next.js v16.'
Fixing Code Block
import { readFileSync } from 'fs';
import { resolve } from 'path';
function getInstalledNextVersion(): string | null {
try {
const nextPkgPath = require.resolve('next/package.json', { paths: [process.cwd()] });
const nextPkg = JSON.parse(readFileSync(nextPkgPath, 'utf8'));
return nextPkg.version;
} catch (error) {
console.warn('Could not resolve installed Next.js version from node_modules:', error);
return null;
}
}
// Usage: replace existing version detection logic with this call
const installedVersion = getInstalledNextVersion();
if (!installedVersion) {
throw new Error('Unable to determine Next.js version. Please install next locally.');
}
// Use installedVersion to fetch documentation instead of raw dependency range
Instead of parsing the version range from package.json, the fix reads the actual installed version from node_modules/next/package.json using require.resolve with paths set to the current working directory. This ensures the exact version (e.g., 16.1.6) is used for documentation retrieval.
Edge Case Audit
This fix assumes the codemod runs in a project where next is installed locally and accessible via Node resolution. In monorepos with hoisting, pnpm's strict node_modules, or when using global next installations, require.resolve may fail or resolve an unexpected instance. Consider adding a fallback to parse lockfiles (package-lock.json, yarn.lock, pnpm-lock.yaml) or prompt the user. Rollback: keep the original package.json range parsing as a fallback if require.resolve returns null.