prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ER_PROPS_SSG_CONFLICT } from 'next/dist/lib/constants'
describe('Mixed getStaticProps and getServerSideProps error', () => {
describe('production mode', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped... | tion getStaticProps() {
return {
props: {}
}
}
`
)
await next.build()
expect(next.cliOutput).toContain(
'found page without a React Component as default export in'
)
awai | await next.patchFile('.babelrc', '{ "presets": ["next/babel"] }')
const originalContent = await next.readFile('pages/index.js')
await next.patchFile(
'pages/index.js',
`
export func | {
"filepath": "test/production/mixed-ssg-serverprops-error/mixed-ssg-serverprops-error.test.ts",
"language": "typescript",
"file_size": 3336,
"cut_index": 614,
"middle_length": 229
} |
EZE_TOKEN env`)
}
const codeFreezeRule = {
context: 'Potentially publish release',
app_id: 15368,
}
async function updateRules(newRules) {
const res = await fetch(
`https://api.github.com/repos/vercel/next.js/branches/canary/protection`,
{
method: 'PUT',
headers: {
Accept: 'applicati... | ction`,
{
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${authToken}`,
'X-GitHub-Api-Version': '2022-11-28',
},
}
)
if (!res.ok) {
throw new Error(
`Failed to check for r | throw new Error(
`Failed to check for rule ${res.status} ${await res.text()}`
)
}
}
async function getCurrentRules() {
const res = await fetch(
`https://api.github.com/repos/vercel/next.js/branches/canary/prote | {
"filepath": "scripts/code-freeze.js",
"language": "javascript",
"file_size": 3256,
"cut_index": 614,
"middle_length": 229
} |
from 'e2e-utils'
describe.skip('Invalid CSS Module Usage in node_modules', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('should fail to build', async () => {
const { exitCode, cliOutput } = await next.buil... | in.*node_modules/
)
// Skip: Rspack loaders cannot access module issuer info for location details
if (!process.env.NEXT_RSPACK) {
expect(cliOutput).toMatch(
/Location:.*node_modules[\\/]example[\\/]index\.mjs/
)
}
})
} | h(
/CSS Modules.*cannot.*be imported from with | {
"filepath": "test/production/scss-invalid-module/invalid-module.test.ts",
"language": "typescript",
"file_size": 869,
"cut_index": 559,
"middle_length": 52
} |
'child_process'
export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'
export function getPkgManager(): PackageManager {
const userAgent = process.env.npm_config_user_agent || ''
if (userAgent.startsWith('yarn')) {
return 'yarn'
}
if (userAgent.startsWith('pnpm')) {
return 'pnpm'
}
if (us... | ng | null {
const userAgent = process.env.npm_config_user_agent || ''
const userAgentMatch = userAgent.match(
new RegExp(`${packageManager}/([\\d.]+[\\w.-]*)`)
)
if (userAgentMatch) {
return userAgentMatch[1]
}
try {
const version | First tries to parse from npm_config_user_agent (e.g., "pnpm/9.13.2 npm/? ..."),
* then falls back to spawning `<packageManager> --version`.
*/
export function getPackageManagerVersion(
packageManager: PackageManager
): stri | {
"filepath": "packages/create-next-app/helpers/get-pkg-manager.ts",
"language": "typescript",
"file_size": 1639,
"cut_index": 537,
"middle_length": 229
} |
cSync } from 'node:child_process'
import { join } from 'node:path'
import { rmSync } from 'node:fs'
function isInGitRepository(): boolean {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' })
return true
} catch (_) {}
return false
}
function isInMercurialRepository(): boolean {
... | InGitRepository() || isInMercurialRepository()) {
return false
}
execSync('git init', { stdio: 'ignore' })
didInit = true
if (!isDefaultBranchSet()) {
execSync('git checkout -b main', { stdio: 'ignore' })
}
execSync(' | faultBranch', { stdio: 'ignore' })
return true
} catch (_) {}
return false
}
export function tryGitInit(root: string): boolean {
let didInit = false
try {
execSync('git --version', { stdio: 'ignore' })
if (is | {
"filepath": "packages/create-next-app/helpers/git.ts",
"language": "typescript",
"file_size": 1325,
"cut_index": 524,
"middle_length": 229
} |
sable import/no-extraneous-dependencies */
import { yellow } from 'picocolors'
import spawn from 'cross-spawn'
import type { PackageManager } from './get-pkg-manager'
/**
* Spawn a package manager installation based on user preference.
*
* @returns A Promise that resolves once the installation is finished.
*/
expo... | omise that resolves once the installation is finished.
*/
return new Promise((resolve, reject) => {
/**
* Spawn the installation process.
*/
const child = spawn(packageManager, args, {
stdio: 'inherit',
env: {
... | n
): Promise<void> {
const args: string[] = ['install']
if (!isOnline) {
console.log(
yellow('You appear to be offline.\nFalling back to the local cache.')
)
args.push('--offline')
}
/**
* Return a Pr | {
"filepath": "packages/create-next-app/helpers/install.ts",
"language": "typescript",
"file_size": 1408,
"cut_index": 524,
"middle_length": 229
} |
no-extraneous-dependencies */
import { lstatSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { green, blue } from 'picocolors'
export function isFolderEmpty(root: string, name: string): boolean {
const validFilesOrFolders = [
'.claude',
'.cursor',
'.DS_Store',
'.git',
'.... | ilesOrFolders.includes(fileOrFolder) &&
// Support IntelliJ IDEA-based editors
!/\.iml$/.test(fileOrFolder)
)
if (conflicts.length > 0) {
console.log(
`The directory ${green(name)} contains files that could conflict:`
)
c | 'Thumbs.db',
'docs',
'mkdocs.yml',
'npm-debug.log',
'yarn-debug.log',
'yarn-error.log',
'yarnrc.yml',
'.yarn',
]
const conflicts = readdirSync(root).filter(
(fileOrFolder) =>
!validF | {
"filepath": "packages/create-next-app/helpers/is-folder-empty.ts",
"language": "typescript",
"file_size": 1513,
"cut_index": 537,
"middle_length": 229
} |
{ execSync } from 'node:child_process'
import { lookup } from 'node:dns/promises'
import { URL } from 'node:url'
function getProxy(): string | undefined {
if (process.env.https_proxy) {
return process.env.https_proxy
}
try {
const httpsProxy = execSync('npm config get https-proxy').toString().trim()
... |
let url: URL
try {
url = new URL(proxy)
} catch {
// Invalid proxy URL
return false
}
const { hostname } = url
if (!hostname) {
// Invalid proxy URL
return false
}
try {
await lookup(ho |
// If DNS lookup succeeds, we are online
return true
} catch {
// The DNS lookup failed, but we are still fine as long as a proxy has been set
const proxy = getProxy()
if (!proxy) {
return false
} | {
"filepath": "packages/create-next-app/helpers/is-online.ts",
"language": "typescript",
"file_size": 1218,
"cut_index": 518,
"middle_length": 229
} |
no-extraneous-dependencies */
import spawn from 'cross-spawn'
import type { PackageManager } from './get-pkg-manager'
/**
* Runs `next typegen` using the package manager to execute the locally installed Next.js binary.
* Assumes the current working directory is the project root where Next is installed.
*/
export as... | args = ['exec', 'next', '--', 'typegen']
break
case 'pnpm':
command = 'pnpm'
args = ['exec', 'next', '--', 'typegen']
break
case 'bun':
command = 'bun'
// Bun only has `bun x` which is not |
let command: string
let args: string[]
switch (packageManager) {
case 'npm':
command = 'npm'
args = ['exec', 'next', '--', 'typegen']
break
case 'yarn':
command = 'yarn'
| {
"filepath": "packages/create-next-app/helpers/typegen.ts",
"language": "typescript",
"file_size": 1589,
"cut_index": 537,
"middle_length": 229
} |
from "async-sema";
import pkg from "../package.json";
import { Bundler, GetTemplateFileArgs, InstallTemplateArgs } from "./types";
// Do not rename or format. sync-react script relies on this line.
// prettier-ignore
const nextjsReactPeerVersion = "19.2.6";
function sorted(obj: Record<string, string>) {
return Obje... | ", "styles"];
/**
* Install a Next.js internal template to a given `root` directory.
*/
export const installTemplate = async ({
appName,
root,
packageManager,
isOnline,
template,
mode,
tailwind,
eslint,
biome,
srcDir,
importAlias,
| e, e.g. "next.config.js".
*/
export const getTemplateFile = ({
template,
mode,
file,
}: GetTemplateFileArgs): string => {
return path.join(__dirname, template, mode, file);
};
export const SRC_DIR_NAMES = ["app", "pages | {
"filepath": "packages/create-next-app/templates/index.ts",
"language": "typescript",
"file_size": 12989,
"cut_index": 921,
"middle_length": 229
} |
rt { PackageManager } from "../helpers/get-pkg-manager";
export type TemplateType =
| "app"
| "app-api"
| "app-empty"
| "app-tw"
| "app-tw-empty"
| "default"
| "default-empty"
| "default-tw"
| "default-tw-empty";
export type TemplateMode = "js" | "ts";
export interface GetTemplateFileArgs {
templa... | : boolean;
biome: boolean;
tailwind: boolean;
srcDir: boolean;
importAlias: string;
skipInstall: boolean;
bundler: Bundler;
reactCompiler: boolean;
}
export enum Bundler {
Turbopack = "turbopack",
Webpack = "webpack",
Rspack = "rspack" | mplate: TemplateType;
mode: TemplateMode;
eslint | {
"filepath": "packages/create-next-app/templates/types.ts",
"language": "typescript",
"file_size": 828,
"cut_index": 516,
"middle_length": 52
} |
xt/image";
import { Geist, Geist_Mono } from "next/font/google";
import styles from "@/styles/Home.module.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export default function Home()... | main}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className={styles.intro}>
<h | =device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div
className={`${styles.page} ${geistSans.variable} ${geistMono.variable}`}
>
<main className={styles. | {
"filepath": "packages/create-next-app/templates/default/js/pages/index.js",
"language": "javascript",
"file_size": 2809,
"cut_index": 563,
"middle_length": 229
} |
xt/image";
import { Geist, Geist_Mono } from "next/font/google";
import styles from "@/styles/Home.module.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export default function Home()... | main}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className={styles.intro}>
<h | =device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div
className={`${styles.page} ${geistSans.variable} ${geistMono.variable}`}
>
<main className={styles. | {
"filepath": "packages/create-next-app/templates/default/ts/pages/index.tsx",
"language": "tsx",
"file_size": 2810,
"cut_index": 563,
"middle_length": 229
} |
ction Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:inver... | <p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=creat | t-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.js file.
</h1>
| {
"filepath": "packages/create-next-app/templates/app-tw/js/app/page.js",
"language": "javascript",
"file_size": 2881,
"cut_index": 563,
"middle_length": 229
} |
ction Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:inver... | <p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=crea | t-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
| {
"filepath": "packages/create-next-app/templates/app-tw/ts/app/page.tsx",
"language": "tsx",
"file_size": 2882,
"cut_index": 563,
"middle_length": 229
} |
"./page.module.css";
export default function Home() {
return (
<div className={styles.page}>
<main className={styles.main}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
... | rer"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target | <a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener norefer | {
"filepath": "packages/create-next-app/templates/app/js/app/page.js",
"language": "javascript",
"file_size": 2075,
"cut_index": 563,
"middle_length": 229
} |
"./page.module.css";
export default function Home() {
return (
<div className={styles.page}>
<main className={styles.main}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
... | rrer"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
targe | <a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener norefe | {
"filepath": "packages/create-next-app/templates/app/ts/app/page.tsx",
"language": "tsx",
"file_size": 2076,
"cut_index": 563,
"middle_length": 229
} |
= Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export default function Home() {
return (
<div
className={`${geistSans.className} ${geistMono.className} flex min-h-screen items-center justify-ce... | ter gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the index.js file.
</h1>
<p className | t">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-cen | {
"filepath": "packages/create-next-app/templates/default-tw/js/pages/index.js",
"language": "javascript",
"file_size": 3201,
"cut_index": 614,
"middle_length": 229
} |
= Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export default function Home() {
return (
<div
className={`${geistSans.className} ${geistMono.className} flex min-h-screen items-center justify-ce... | ter gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the index.tsx file.
</h1>
<p classNam | t">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-cen | {
"filepath": "packages/create-next-app/templates/default-tw/ts/pages/index.tsx",
"language": "tsx",
"file_size": 3202,
"cut_index": 614,
"middle_length": 229
} |
etadata of the fallback fonts, retrieved with fontkit on system font files
// The average width is calculated with the calcAverageWidth function below
const DEFAULT_SANS_SERIF_FONT = {
name: 'Arial',
azAvgWidth: 934.5116279069767,
unitsPerEm: 2048,
}
const DEFAULT_SERIF_FONT = {
name: 'Times New Roman',
azAvg... | rage width of all characters, because we have to take letter frequency into account.
* We also have to take word length into account, because the font's space width usually differ a lot from other characters.
* The goal is to find a string that'l | th the loaded font average.
*/
function calcAverageWidth(font: Font): number | undefined {
try {
/**
* Finding the right characters to use when calculating the average width is tricky.
* We can't just use the ave | {
"filepath": "packages/font/src/local/get-fallback-metrics-from-font-file.ts",
"language": "typescript",
"file_size": 3677,
"cut_index": 614,
"middle_length": 229
} |
alFontLoader({
functionName: '',
data: [{ src: './my-font.woff2' }],
emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {
fs: {
readFile: (... | ctionName: '',
data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }],
emitFontFile: () => '/_next/static/media/my-font.woff2',
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: | url(/_next/static/media/my-font.woff2) format('woff2');
font-display: swap;
}
"
`)
})
test('Weight and style', async () => {
const { css } = await nextFontLocalFontLoader({
fun | {
"filepath": "packages/font/src/local/loader.test.ts",
"language": "typescript",
"file_size": 7120,
"cut_index": 716,
"middle_length": 229
} |
equire -- Module created during build.
const mod = require('../fontkit').default
fontFromBuffer = mod.default || mod
} catch {}
import type { AdjustFontFallback, FontLoader } from 'next/font'
import { promisify } from 'util'
import { pickFontFileForFallbackGeneration } from './pick-font-file-for-fallback-generatio... | declarations,
weight: defaultWeight,
style: defaultStyle,
} = validateLocalFontFunctionCall(functionName, data[0])
// Load all font files and emit them to the .next output directory
// Also generate a @font-face CSS for each font file
cons | alFontLoader: FontLoader = async ({
functionName,
variableName,
data,
emitFontFile,
resolve,
loaderContext,
}) => {
const {
src,
display,
fallback,
preload,
variable,
adjustFontFallback,
| {
"filepath": "packages/font/src/local/loader.ts",
"language": "typescript",
"file_size": 3725,
"cut_index": 614,
"middle_length": 229
} |
('pickFontFileForFallbackGeneration', () => {
it('should pick the weight closest to 400', () => {
expect(
pickFontFileForFallbackGeneration([
{
weight: '300',
},
{
weight: '600',
},
])
).toEqual({
weight: '300',
})
expect(
pi... | {
weight: 'bold',
},
{
weight: '900',
},
])
).toEqual({
weight: 'bold',
})
})
it('should pick the thinner weight if both have the same distance to 400', () => {
expect(
| orFallbackGeneration([
{
weight: 'normal',
},
{
weight: '700',
},
])
).toEqual({
weight: 'normal',
})
expect(
pickFontFileForFallbackGeneration([
| {
"filepath": "packages/font/src/local/pick-font-file-for-fallback-generation.test.ts",
"language": "typescript",
"file_size": 3236,
"cut_index": 614,
"middle_length": 229
} |
/**
* Convert the weight string to a number so it can be used for comparison.
* Weights can be defined as a number, 'normal' or 'bold'. https://developer.mozilla.org/docs/Web/CSS/@font-face/font-weight
*/
function getWeightNumber(weight: string) {
return weight === 'normal'
? NORMAL_WEIGHT
: weight === 'b... | ", rather than just one "400"
const [firstWeight, secondWeight] = weight
.trim()
.split(/ +/)
.map(getWeightNumber)
if (Number.isNaN(firstWeight) || Number.isNaN(secondWeight)) {
nextFontError(
`Invalid weight value in src array: | If it's a variable font we need to compare its weight range to 400.
*/
function getDistanceFromNormalWeight(weight?: string) {
if (!weight) return 0
// If it's a variable font the weight is defined with two numbers "100 900 | {
"filepath": "packages/font/src/local/pick-font-file-for-fallback-generation.ts",
"language": "typescript",
"file_size": 3672,
"cut_index": 614,
"middle_length": 229
} |
tFunctionCall } from './validate-local-font-function-call'
describe('validateLocalFontFunctionCall', () => {
test('Not using default export', async () => {
expect(() =>
validateLocalFontFunctionCall('Named', {})
).toThrowErrorMatchingInlineSnapshot(
`"next/font/local has no named exports"`
)
... | )
})
test('Invalid display value', async () => {
expect(() =>
validateLocalFontFunctionCall('', {
src: './font-file.woff2',
display: 'invalid',
})
).toThrowErrorMatchingInlineSnapshot(`
"Invalid display valu | est('Invalid file extension', async () => {
expect(() =>
validateLocalFontFunctionCall('', { src: './font/font-file.abc' })
).toThrowErrorMatchingInlineSnapshot(
`"Unexpected file \`./font/font-file.abc\`"`
| {
"filepath": "packages/font/src/local/validate-local-font-function-call.test.ts",
"language": "typescript",
"file_size": 1902,
"cut_index": 537,
"middle_length": 229
} |
import { formatAvailableValues } from '../format-available-values'
import { nextFontError } from '../next-font-error'
const extToFormat = {
woff: 'woff',
woff2: 'woff2',
ttf: 'truetype',
otf: 'opentype',
eot: 'embedded-opentype',
}
type FontOptions = {
src: Array<{
path: string
weight?: string
... | nName: string,
fontData: any
): FontOptions {
if (functionName) {
nextFontError(`next/font/local has no named exports`)
}
let {
src,
display = 'swap',
weight,
style,
fallback,
preload = true,
variable,
adjustFont | : string | false
declarations?: Array<{ prop: string; value: string }>
}
/**
* Validate the data received from next-swc next-transform-font on next/font/local calls
*/
export function validateLocalFontFunctionCall(
functio | {
"filepath": "packages/font/src/local/validate-local-font-function-call.ts",
"language": "typescript",
"file_size": 2340,
"cut_index": 563,
"middle_length": 229
} |
{ nextFontError } from '../next-font-error'
import { fetchResource } from './fetch-resource'
import { retry } from './retry'
/**
* Fetches the CSS containing the @font-face declarations from Google Fonts.
* The fetch has a user agent header with a modern browser to ensure we'll get .woff2 files.
*
* The env varia... | NSES)
const mockedResponse = mockFile[url]
if (!mockedResponse) {
nextFontError('Missing mocked response for URL: ' + url)
}
return mockedResponse
}
const buffer = await retry(async () => {
return fetchResource(
url,
| ion fetchCSSFromGoogleFonts(
url: string,
fontFamily: string,
isDev: boolean
): Promise<string> {
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
const mockFile = require(process.env.NEXT_FONT_GOOGLE_MOCKED_RESPO | {
"filepath": "packages/font/src/google/fetch-css-from-google-fonts.ts",
"language": "typescript",
"file_size": 1171,
"cut_index": 518,
"middle_length": 229
} |
tp'
import https from 'node:https'
import { getProxyAgent } from './get-proxy-agent'
/**
* Makes a simple GET request and returns the entire response as a Buffer.
* - Throws if the response status is not 200.
* - Applies a 3000 ms timeout when `isDev` is `true`.
*/
export function fetchResource(
url: string,
i... | 2 files are fetched
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/104.0.0.0 Safari/537.36',
},
},
(res) => {
| http
const timeout = isDev ? 3000 : undefined
const req = client.request(
url,
{
agent: getProxyAgent(),
headers: {
// The file format is based off of the user agent, make sure woff | {
"filepath": "packages/font/src/google/fetch-resource.ts",
"language": "typescript",
"file_size": 1630,
"cut_index": 537,
"middle_length": 229
} |
it('should find all font files and preload requested subsets', () => {
const css = `/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 300;
src: url(latin1.woff2) format('woff2');
}
/* gree... | }
/* greek */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 400;
src: url(greek2.woff2) format('woff2');
}
/* cyrilic */
| }
/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 400;
src: url(latin2.woff2) format('woff2');
| {
"filepath": "packages/font/src/google/find-font-files-in-css.test.ts",
"language": "typescript",
"file_size": 3706,
"cut_index": 614,
"middle_length": 229
} |
Find all font files in the CSS response and determine which files should be preloaded.
* In Google Fonts responses, the @font-face's subset is above it in a comment.
* Walk through the CSS from top to bottom, keeping track of the current subset.
*/
export function findFontFilesInCss(css: string, subsetsToPreload?: ... | newSubset
} else {
const googleFontFileUrl = /src: url\((.+?)\)/.exec(line)?.[1]
if (
googleFontFileUrl &&
!fontFiles.some(
(foundFile) => foundFile.googleFontFileUrl === googleFontFileUrl
)
) {
| tSubset = ''
for (const line of css.split('\n')) {
const newSubset = /\/\* (.+?) \*\//.exec(line)?.[1]
if (newSubset) {
// Found new subset in a comment above the next @font-face declaration
currentSubset = | {
"filepath": "packages/font/src/google/find-font-files-in-css.ts",
"language": "typescript",
"file_size": 1237,
"cut_index": 518,
"middle_length": 229
} |
gnore
import * as Log from 'next/dist/build/output/log'
/**
* Get precalculated fallback font metrics for the Google Fonts family.
*
* TODO:
* We might want to calculate these values with fontkit instead (like in next/font/local).
* That way we don't have to update the precalculated values every time a new font i... | Font,
ascentOverride: `${ascent}%`,
descentOverride: `${descent}%`,
lineGapOverride: `${lineGap}%`,
sizeAdjust: `${sizeAdjust}%`,
}
} catch {
Log.error(`Failed to find font override values for font \`${fontFamily}\``)
}
| AdjustValues(fontFamily)
return {
fallback | {
"filepath": "packages/font/src/google/get-fallback-font-override-metrics.ts",
"language": "typescript",
"file_size": 916,
"cut_index": 606,
"middle_length": 52
} |
rrors', () => {
test('Setting axes on font without definable axes', () => {
expect(() =>
getFontAxes('Lora', ['variable'], [], [])
).toThrowErrorMatchingInlineSnapshot(
`"Font \`Lora\` has no definable \`axes\`"`
)
})
test('Invalid axes value', async () => {
expect(() => getFontAxes('... | c () => {
expect(() => getFontAxes('Roboto Flex', ['variable'], [], ['INVALID']))
.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value \`INVALID\` for font \`Roboto Flex\`.
Available axes: \`GRAD\`, \`XOPQ\`, \`XTRA\`, \`YOPQ\`, | `)
})
test('Invalid value in axes array', asyn | {
"filepath": "packages/font/src/google/get-font-axes.test.ts",
"language": "typescript",
"file_size": 985,
"cut_index": 582,
"middle_length": 52
} |
ailable-values'
import { nextFontError } from '../next-font-error'
import { googleFontsMetadata } from './google-fonts-metadata'
/**
* Validates and gets the data for each font axis required to generate the Google Fonts URL.
*/
export function getFontAxes(
fontFamily: string,
weights: string[],
styles: string[... | ? ['0'] : []), '1'] : undefined
// Weights will always contain one element if it's a variable font
if (weights[0] === 'variable') {
// Get all the available axes for the current font from the metadata file
const allAxes = googleFontsMetadata[ | ncludes('normal')
// Make sure the order is correct, otherwise Google Fonts will return an error
// If only normal is set, we can skip returning the ital axis as normal is the default
const ital = hasItalic ? [...(hasNormal | {
"filepath": "packages/font/src/google/get-font-axes.ts",
"language": "typescript",
"file_size": 2725,
"cut_index": 563,
"middle_length": 229
} |
Values } from './sort-fonts-variant-values'
/**
* Generate the Google Fonts URL given the requested weight(s), style(s) and additional variable axes
*/
export function getGoogleFontsUrl(
fontFamily: string,
axes: {
wght?: string[]
ital?: string[]
variableAxes?: [string, string][]
},
display: stri... | ['wght', wght],
...(axes.variableAxes ?? []),
])
}
}
}
} else if (axes.variableAxes) {
// Variable fonts might not have a range of weights, just add optional variable axes in that case
variants.pu | st wght of axes.wght) {
if (!axes.ital) {
variants.push([['wght', wght], ...(axes.variableAxes ?? [])])
} else {
for (const ital of axes.ital) {
variants.push([
['ital', ital],
| {
"filepath": "packages/font/src/google/get-google-fonts-url.ts",
"language": "typescript",
"file_size": 1868,
"cut_index": 537,
"middle_length": 229
} |
.mock('./fetch-resource')
const mockFetchResource = fetchResource as jest.Mock
describe('next/font/google loader', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('URL from options', () => {
const fixtures: Array<[string, any, string]> = [
[
'Inter',
{},
'https:... | { weight: '900', display: 'auto' },
'https://fonts.googleapis.com/css2?family=Source+Sans+3:wght@900&display=auto',
],
[
'Source_Sans_3',
{ weight: '200', style: 'italic' },
'https://fonts.googleapis.com/css2?fam | 400&display=swap',
],
[
'Inter',
{ weight: '900', display: 'block' },
'https://fonts.googleapis.com/css2?family=Inter:wght@900&display=block',
],
[
'Source_Sans_3',
| {
"filepath": "packages/font/src/google/loader.test.ts",
"language": "typescript",
"file_size": 4826,
"cut_index": 614,
"middle_length": 229
} |
from 'e2e-utils'
describe('options-request', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it.each(['/app-page/dynamic', '/pages-page/dynamic'])(
'should return a 400 status code when invoking %s with an OPTIONS request (dynamic rendering)',
async (path) => {
const res = await ... | res.status).toBe(405)
expect(await res.text()).toBe('Method Not Allowed')
}
)
// In app router, OPTIONS is auto-implemented if not provided
it('should respond with a 204 No Content when invoking an app route handler with an OPTIONS request | atic', '/pages-page/static'])(
'should return a 405 status code when invoking %s with an OPTIONS request (static rendering)',
async (path) => {
const res = await next.fetch(path, { method: 'OPTIONS' })
expect( | {
"filepath": "test/production/options-request/options-request.test.ts",
"language": "typescript",
"file_size": 1890,
"cut_index": 537,
"middle_length": 229
} |
t { diff } from 'jest-diff'
const glob = promisify(globOrig)
import { FILES } from './files'
const IGNORE_CONTENT_NEXT_REGEX = new RegExp(
[
// This contains the deployment id, but these changing fields are stripped by the builder
'routes-manifest\\.json',
// These contain the build id and deployment id... | c files which aren't deployed.
const IGNORE = /^trace$|^trace-build$/
const files = (
(await glob('**/*', {
cwd: path.join(next.testDir, next.distDir),
nodir: true,
dot: true,
})) as string[]
)
.filter((f) => !IGNORE.te | \\.json',
'fallback-build-manifest\\.json',
]
.map((v) => '(?:\\/|^)' + v + '$')
.join('|')
)
async function readFilesNext(
next: NextInstance
): Promise<Map<string, Map<string, string>>> {
// These are cosmeti | {
"filepath": "test/production/deterministic-build/deployment-id.test.ts",
"language": "typescript",
"file_size": 8052,
"cut_index": 716,
"middle_length": 229
} |
busting the turbo cache un-necessarily due
to bumping the version in the repo's package.json files
*/
const path = require('path')
const fs = require('fs/promises')
const cwd = process.cwd()
const NORMALIZED_VERSION = '0.0.0'
const readJson = async (filePath) =>
JSON.parse(await fs.readFile(filePath, 'utf8'))
co... | .push(data.name)
pkgJsonData.set(pkgDir, data)
})
)
const normalizeVersions = async (filePath, data) => {
data = data || (await readJson(filePath))
const version = data.version
if (version) {
data.version = NORMALIZED_VERSI |
const pkgJsonData = new Map()
const pkgNames = []
await Promise.all(
packages.map(async (pkgDir) => {
const data = await readJson(
path.join(cwd, 'packages', pkgDir, 'package.json')
)
pkgNames | {
"filepath": "scripts/normalize-version-bump.js",
"language": "javascript",
"file_size": 2167,
"cut_index": 563,
"middle_length": 229
} |
rom 'yargs/helpers'
import path from 'path'
import { NEXT_DIR, exec, execFn, packageFiles } from './pack-util.js'
import buildNative from './build-native.js'
interface Options {
project: string
build: boolean
'build-native': boolean
verbose: number
_: string[]
}
// --- Parse command line arguments ---
cons... | -app --no-build --no-build-native',
'Patch Next.js packages in the "my-app" directory'
)
.example(
'$0 ../my-app -- --release',
'Patch using a release-mode native build. `--release` is passed through to the nap |
return yargs
.positional('project', {
type: 'string',
describe: 'Target directory of the Next.js project to patch',
demandOption: true,
})
.example(
'$0 ../my | {
"filepath": "scripts/patch-next.ts",
"language": "typescript",
"file_size": 4403,
"cut_index": 614,
"middle_length": 229
} |
ompletedAt) {
if (!startedAt || !completedAt) return 'N/A'
const start = new Date(startedAt)
const end = new Date(completedAt)
// Validate that both dates are valid (not Invalid Date objects)
if (isNaN(start.getTime()) || isNaN(end.getTime())) return 'N/A'
const seconds = Math.floor((end - start) / 1000)
... | eturn `${seconds}s`
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}m ${remainingSeconds}s`
}
function sanitizeFilename(name) {
return name
.replace(/[^a-zA-Z0-9._-]/g, '-')
.replace(/-+/g, | edTime(startedAt) {
if (!startedAt) return 'N/A'
const start = new Date(startedAt)
if (isNaN(start.getTime())) return 'N/A'
const now = new Date()
const seconds = Math.floor((now - start) / 1000)
if (seconds < 60) r | {
"filepath": "scripts/pr-status.js",
"language": "javascript",
"file_size": 51353,
"cut_index": 2151,
"middle_length": 229
} |
ire('async-sema')
const { readFile, readdir, writeFile, cp } = require('fs/promises')
const cwd = process.cwd()
;(async function () {
try {
const publishSema = new Sema(2)
let version = require('@next/swc/package.json').version
// Copy binaries to package folders, update version, and publish
let n... | kages/next-swc/native', binaryName),
path.join(nativePackagesDir, platform, binaryName)
)
let pkg = JSON.parse(
await readFile(
path.join(nativePackagesDir, platform, 'package.json')
)
| .all(
platforms.map(async (platform) => {
await publishSema.acquire()
let output = ''
try {
let binaryName = `next-swc.${platform}.node`
await cp(
path.join(cwd, 'pac | {
"filepath": "scripts/publish-native.js",
"language": "javascript",
"file_size": 4637,
"cut_index": 614,
"middle_length": 229
} |
ommit,
githubRequest,
alignLocalBranchWithSignedCommit,
} = require('./github-utils/signed-commit')
const REPO_API_PATH = '/repos/vercel/next.js'
async function git(args, options = {}) {
const { captureOutput = false, ...execaOptions } = options
const { stdout } = await execa('git', args, {
stdio: capture... | version}`
const tags = String(
await git(['tag', '--points-at', commitSha], { captureOutput: true })
)
.split('\n')
.map((tag) => tag.trim())
.filter(Boolean)
if (!tags.includes(expectedTagName)) {
throw new Error(
`Expecte | by
* lerna.json, then return that tag name for GitHub ref creation.
*/
async function getLocalReleaseTagName(commitSha) {
const { version } = JSON.parse(await fs.readFile('lerna.json', 'utf8'))
const expectedTagName = `v${ | {
"filepath": "scripts/release-github-api.js",
"language": "javascript",
"file_size": 3872,
"cut_index": 614,
"middle_length": 229
} |
= require('execa')
const REPO_URL = 'github.com/vercel/next.js.git'
function getGitHubToken() {
return process.env.RELEASE_GITHUB_TOKEN
}
function getGitHubTokenMissingMessage() {
return 'Missing RELEASE_GITHUB_TOKEN'
}
function getGitUser() {
const appSlug = process.env.RELEASE_GITHUB_APP_SLUG
const appUs... | er = getGitUser()
const remoteUrl = `https://x-access-token:${encodeURIComponent(
token
)}@${REPO_URL}`
await execa('git', ['remote', 'set-url', 'origin', remoteUrl], {
stdio: 'inherit',
})
await execa('git', ['config', 'user.name', gitU | }
}
return {
name: process.env.RELEASE_GITHUB_USER_NAME || 'nextjs-bot',
email: process.env.RELEASE_GITHUB_USER_EMAIL || 'it+nextjs-bot@vercel.com',
}
}
async function configureGitHubAuth(token) {
const gitUs | {
"filepath": "scripts/release-github-auth.js",
"language": "javascript",
"file_size": 1774,
"cut_index": 537,
"middle_length": 229
} |
Sync from a React commit (can be a commit on a PR)
// pnpm run sync-react --version vp:///commit-sha
const repoOwner = 'vercel'
const repoName = 'next.js'
const pullRequestLabels = ['type: react-sync']
const pullRequestReviewers = ['eps1lon']
/**
* Set to `null` to automatically sync the React version of Pages Rou... | hannel = 'canary'
const filesReferencingReactPeerDependencyVersion = [
'run-tests.js',
'packages/create-next-app/templates/index.ts',
'test/lib/next-modes/base.ts',
]
const libraryManifestsSupportingNextjsReact = [
'packages/third-parties/package.j | we do support
* React 18 in pages router, we don't focus our development process on it considering
* it does not receive new features.
* @type {string | null}
*/
const activePagesRouterReact = '^19.0.0'
const defaultLatestC | {
"filepath": "scripts/sync-react.js",
"language": "javascript",
"file_size": 25078,
"cut_index": 1331,
"middle_length": 229
} |
s')
const path = require('path')
const fetch = require('node-fetch')
;(async () => {
const { familyMetadataList } = await fetch(
'https://fonts.google.com/metadata/fonts'
).then((r) => r.json())
let fontFunctions = `/**
* This is an autogenerated file by scripts/update-google-fonts.js
*/
import type {... | ts = subsets.length > 0
const weights = new Set()
const styles = new Set()
for (const variant of Object.keys(fonts)) {
if (variant.endsWith('i')) {
styles.add('italic')
weights.add(variant.slice(0, -1))
continue
|
'chinese-hongkong',
'chinese-traditional',
]
for (let { family, fonts, axes, subsets } of familyMetadataList) {
subsets = subsets.filter((subset) => !ignoredSubsets.includes(subset))
const hasPreloadableSubse | {
"filepath": "scripts/update-google-fonts.js",
"language": "javascript",
"file_size": 2961,
"cut_index": 563,
"middle_length": 229
} |
at CLI startup.
* This helps identify which modules are being loaded eagerly.
*
* Usage:
* node scripts/trace-cli-startup.js [--command=dev|build|--help]
*/
const inspector = require('inspector')
const fs = require('fs')
const path = require('path')
const args = process.argv.slice(2)
const getArg = (name, defa... | og(`Output directory: ${outputDir}`)
console.log('')
// Start CPU profiling
const session = new inspector.Session()
session.connect()
// Track module loading via require hook
const Module = require('module')
const originalRequire = Module.prototype.requi | join(process.cwd(), 'profiles')
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true })
}
console.log('\x1b[34m=== Next.js CLI Startup Trace ===\x1b[0m')
console.log(`Command: next ${command}`)
console.l | {
"filepath": "scripts/trace-cli-startup.js",
"language": "javascript",
"file_size": 4079,
"cut_index": 614,
"middle_length": 229
} |
)
const fs = require('node:fs/promises')
const path = require('node:path')
/**
* Yields one entry per package tarball under `tarballDirectory`. Scoped
* packages are laid out one level deeper (e.g. `@next/env/<name>.tgz`), so the
* walk descends into any directory whose name starts with `@`.
*
* @param {string} t... | await fs.readdir(entryPath, { withFileTypes: true })
for (const scopeEntry of scopeEntries) {
if (!scopeEntry.isDirectory()) continue
const tarballPath = await findTarballInDir(
path.join(entryPath, scopeEntry.name)
| ory, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isDirectory()) continue
const entryPath = path.join(tarballDirectory, entry.name)
if (entry.name.startsWith('@')) {
const scopeEntries = | {
"filepath": "scripts/upload-preview-tarballs.js",
"language": "javascript",
"file_size": 2827,
"cut_index": 563,
"middle_length": 229
} |
`,
'X-GitHub-Api-Version': '2022-11-28',
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body: body ? JSON.stringify(body) : undefined,
})
if (!response.ok) {
const responseText = await response.text()
throw new Error(
`GitHub API ${method} ${path} failed (${response.... | aths changed between two commits, using "\0" delimiters so unusual
* file names do not affect parsing.
*/
async function getChangedFiles(baseSha, headSha) {
const stdout = await git(
['diff-tree', '-r', '--name-only', '--no-renames', '-z', baseSha, | , ...execaOptions } = options
const { stdout } = await execa('git', args, {
stdio: captureOutput ? 'pipe' : 'inherit',
...execaOptions,
})
return typeof stdout === 'string' ? stdout.trim() : stdout
}
/**
* List p | {
"filepath": "scripts/github-utils/signed-commit.js",
"language": "javascript",
"file_size": 9210,
"cut_index": 921,
"middle_length": 229
} |
h: string = ''
const handleSigTerm = () => process.exit(0)
process.on('SIGINT', handleSigTerm)
process.on('SIGTERM', handleSigTerm)
const onPromptState = (state: {
value: InitialReturnValue
aborted: boolean
exited: boolean
}) => {
if (state.aborted) {
// If we don't re-enable the terminal cursor before e... | message.')
.option('--ts, --typescript', 'Initialize as a TypeScript project. (default)')
.option('--js, --javascript', 'Initialize as a JavaScript project.')
.option('--tailwind', 'Initialize with Tailwind CSS config. (default)')
.option('--react | .name)
.version(
packageJson.version,
'-v, --version',
'Output the current version of create-next-app.'
)
.argument('[directory]')
.usage('[directory] [options]')
.helpOption('-h, --help', 'Display this help | {
"filepath": "packages/create-next-app/index.ts",
"language": "typescript",
"file_size": 25439,
"cut_index": 1331,
"middle_length": 229
} |
sable import/no-extraneous-dependencies */
import { resolve, dirname, basename, join } from 'node:path'
import { copyFile, mkdir } from 'node:fs/promises'
import { async as glob } from 'fast-glob'
interface CopyOption {
cwd?: string
rename?: (basename: string) => string
parents?: boolean
}
const identity = (x: ... | const destRelativeToCwd = cwd ? resolve(cwd, dest) : dest
return Promise.all(
sourceFiles.map(async (p) => {
const dirName = dirname(p)
const baseName = rename(basename(p))
const from = cwd ? resolve(cwd, p) : p
const to = | ' ? [src] : src
if (source.length === 0 || !dest) {
throw new TypeError('`src` and `dest` are required')
}
const sourceFiles = await glob(source, {
cwd,
dot: true,
absolute: false,
stats: false,
})
| {
"filepath": "packages/create-next-app/helpers/copy.ts",
"language": "typescript",
"file_size": 1263,
"cut_index": 524,
"middle_length": 229
} |
elease-github-auth')
const PUBLISH_RELEASE_JOB_NAME = 'Potentially publish release'
const TRIGGER_RELEASE_WORKFLOW = 'trigger_release.yml'
const RELEASE_COMMIT_REGEX = /^v\d+\.\d+\.\d+(-\w+\.\d+)?$/
// This helper is used by a workflow_run listener on build-and-deploy.
// It decides whether a successful stable backpo... | rsionString.slice(1)
: null
}
async function fetchGitHubJson(url, token) {
const headers = {
Accept: 'application/vnd.github+json',
}
if (token) {
headers.Authorization = `Bearer ${token}`
headers['X-GitHub-Api-Version'] = '2022-11- | -1 ? undefined : process.argv[index + 1]
}
function parseReleaseVersion(commitMessage) {
const versionString = commitMessage.split(' ').pop()?.trim()
return versionString && RELEASE_COMMIT_REGEX.test(versionString)
? ve | {
"filepath": "scripts/check-backport-canary-release.js",
"language": "javascript",
"file_size": 6610,
"cut_index": 716,
"middle_length": 229
} |
es the turbo-computed rust fingerprint (target/.rust-fingerprint) as
// the cache key, combined with the target triple. Run `turbo run
// rust-fingerprint` first to compute it.
//
// Usage:
// node scripts/native-cache.js --restore --target x86_64-unknown-linux-gnu
// node scripts/native-cache.js --save --target... | arget: { type: 'string', default: '' },
},
strict: false,
})
const REPO_ROOT = path.resolve(__dirname, '..')
const NATIVE_DIR = path.join(REPO_ROOT, 'packages/next-swc/native')
const FINGERPRINT = path.join(REPO_ROOT, 'target/.rust-fingerprint')
func |
const { parseArgs } = require('node:util')
const { values: flags } = parseArgs({
args: process.argv.slice(2),
options: {
restore: { type: 'boolean', default: false },
save: { type: 'boolean', default: false },
t | {
"filepath": "scripts/native-cache.js",
"language": "javascript",
"file_size": 4500,
"cut_index": 614,
"middle_length": 229
} |
ss'
import { existsSync } from 'fs'
import globOrig from 'glob'
import { join } from 'path'
import { promisify } from 'util'
export const glob = promisify(globOrig)
export const NEXT_DIR = join(__dirname, '..')
/**
* @param {string} title
* @param {string | string[]} command
* @param {ExecSyncOptions} [opts]
* @... | })
}
}
class ExecError extends Error {
code: number | null
stdout: Buffer
stderr: Buffer
}
type ExecOutput = {
stdout: Buffer
stderr: Buffer
}
/**
* @param {string} title
* @param {string | string[]} command
* @param {SpawnOptions} [o | mand[0], command.slice(1), {
stdio: 'inherit',
cwd: NEXT_DIR,
...opts,
})
} else {
logCommand(title, command)
return execSync(command, {
stdio: 'inherit',
cwd: NEXT_DIR,
...opts,
| {
"filepath": "scripts/pack-util.ts",
"language": "typescript",
"file_size": 4564,
"cut_index": 614,
"middle_length": 229
} |
default)
* --webpack Use Webpack
* --duration=MS How long to profile after ready (default: 1000)
* --cli Profile just the CLI entry point (runs next --help)
*
* Output files:
* - dev-turbopack-YYYY-MM-DDTHH-MM-SS.cpuprofile
* - cli-turbopack-YYYY-MM-DDTHH-MM-SS.cpuprofile
... | fs = require('fs')
// Parse arguments
const args = process.argv.slice(2)
const getArg = (name, defaultValue) => {
const arg = args.find((a) => a.startsWith(`--${name}=`))
return arg ? arg.split('=')[1] : defaultValue
}
const hasFlag = (name) => args. | ote: Currently profiles the parent process only. For child process profiling,
* additional Next.js changes are needed (see future PRs).
*/
const { spawn, execSync } = require('child_process')
const path = require('path')
const | {
"filepath": "scripts/profile-next-dev-boot.js",
"language": "javascript",
"file_size": 9430,
"cut_index": 921,
"middle_length": 229
} |
= require('execa')
const fs = require('node:fs/promises')
const path = require('node:path')
async function main() {
const [githubSha] = process.argv.slice(2)
if (!githubSha) {
throw new Error('Usage: set-preview-version.js <githubSha>')
}
const repoRoot = path.resolve(__dirname, '..')
const [{ stdout: ... | path.join(repoRoot, 'lerna.json')
const lernaConfig = JSON.parse(await fs.readFile(lernaConfigPath, 'utf8'))
// 15.0.0-canary.17 -> 15.0.0
// 15.0.0 -> 15.0.0
const [semverStableVersion] = lernaConfig.version.split('-')
// This can create collid | e3e8bacfc8af839/scripts/release/utils.js#L114
execa('git', [
'show',
'-s',
'--no-show-signature',
'--format=%cd',
'--date=format:%Y%m%d',
githubSha,
]),
])
const lernaConfigPath = | {
"filepath": "scripts/set-preview-version.js",
"language": "javascript",
"file_size": 1845,
"cut_index": 537,
"middle_length": 229
} |
un with tsx
import { NEXT_DIR, exec } from './pack-util'
import fs from 'fs'
import path from 'path'
const TARBALLS = `${NEXT_DIR}/tarballs`
const PROJECT_DIR = path.resolve(process.argv[2])
function realPathIfAny(path: fs.PathLike) {
try {
return fs.realpathSync(path)
} catch {
return null
}
}
const ... | dx`),
'next-bundle-analyzer': realPathIfAny(
`${PROJECT_DIR}/node_modules/@next/bundle-anlyzer`
),
}
for (const [key, path] of Object.entries(packages)) {
if (!path) continue
exec(`Unpack ${key}`, `tar -xf '${TARBALLS}/${key}.tar' -C '${path}' | odules/@next/m | {
"filepath": "scripts/unpack-next.ts",
"language": "typescript",
"file_size": 811,
"cut_index": 536,
"middle_length": 14
} |
re('fs/promises')
const prettyBytes = require('pretty-bytes')
const gzipSize = require('next/dist/compiled/gzip-size')
const { nodeFileTrace } = require('next/dist/compiled/@vercel/nft')
const { linkPackages } =
require('../.github/actions/next-stats-action/src/prepare/repo-setup')()
const MAX_COMPRESSED_SIZE = 250 ... | mp-next-${Date.now()}`)
const workDir = path.join(tmpdir, `trace-next-${Date.now()}`)
const origTestDir = path.join(origRepoDir, 'test')
const dotDir = path.join(origRepoDir, './') + '.'
await fsp.cp(origRepoDir, repoDir, {
filter: (item) => { | act and react-dom need to be traced specific to installed
// version so isn't pre-traced
async function main() {
const tmpdir = os.tmpdir()
const origRepoDir = path.join(__dirname, '..')
const repoDir = path.join(tmpdir, `t | {
"filepath": "scripts/trace-next-server.js",
"language": "javascript",
"file_size": 4153,
"cut_index": 614,
"middle_length": 229
} |
path'
import { cyan, green, red } from 'picocolors'
import type { RepoInfo } from './helpers/examples'
import {
downloadAndExtractExample,
downloadAndExtractRepo,
existsInRepo,
getRepoInfo,
hasRepo,
} from './helpers/examples'
import type { PackageManager } from './helpers/get-pkg-manager'
import { tryGitInit... | { getTemplateFile, installTemplate } from './templates'
export class DownloadError extends Error {}
export async function createApp({
appPath,
packageManager,
example,
examplePath,
typescript,
tailwind,
eslint,
biome,
app,
srcDir,
i | le } from './helpers/is-writeable'
import { generateAgentFiles } from './helpers/generate-agent-files'
import { runTypegen } from './helpers/typegen'
import type { Bundler, TemplateMode, TemplateType } from './templates'
import | {
"filepath": "packages/create-next-app/create-app.ts",
"language": "typescript",
"file_size": 8188,
"cut_index": 716,
"middle_length": 229
} |
sep, posix } from 'node:path'
import { pipeline } from 'node:stream/promises'
import { x } from 'tar'
export type RepoInfo = {
username: string
name: string
branch: string
filePath: string
}
export async function isUrlOk(url: string): Promise<boolean> {
try {
const res = await fetch(url, { method: 'HEA... | ERROR: type should be string, got " https://github.com/:username/:my-cool-nextjs-example-repo-name.\n t === undefined ||\n // Support GitHub URL that ends with a trailing slash, e.g.\n // https://github.com/:username/:my-cool-nextjs-example-repo-name/\n // In this case \"t\" will be a" | name, name, t, _branch, ...file] = url.pathname.split('/')
const filePath = examplePath ? examplePath.replace(/^\//, '') : file.join('/')
if (
// Support repos whose entire purpose is to be a Next.js example, e.g.
// | {
"filepath": "packages/create-next-app/helpers/examples.ts",
"language": "typescript",
"file_size": 4458,
"cut_index": 614,
"middle_length": 229
} |
st TARBALLS_DIRNAME = 'tarballs'
const TARBALLS = path.join(NEXT_DIR, TARBALLS_DIRNAME)
const NEXT_PACKAGES = `${NEXT_DIR}/packages`
const NEXT_TARBALL = 'next.tar'
const NEXT_SWC_TARBALL = 'next-swc.tar'
const NEXT_MDX_TARBALL = 'next-mdx.tar'
const NEXT_ENV_TARBALL = 'next-env.tar'
const NEXT_BA_TARBALL = 'next-bundl... | , {
alias: 'p',
type: 'string',
})
.option('tar', {
type: 'boolean',
describe: 'Create tarballs instead of direct reflinks',
})
.option('deployable-tar', {
type: 'boolean',
describe:
'Create tarballs in the target proj | s for testing in external projects')
.option('js-build', {
type: 'boolean',
default: true,
describe:
'Build JavaScript code (default). Use `--no-js-build` to skip building JavaScript',
})
.option('project' | {
"filepath": "scripts/pack-next.ts",
"language": "typescript",
"file_size": 10428,
"cut_index": 921,
"middle_length": 229
} |
:\d{2}:\d{2}(?:\.\d+)?Z\s?/
function execGh(args) {
try {
return execFileSync('gh', args, {
encoding: 'utf8',
maxBuffer: 50 * 1024 * 1024,
}).trim()
} catch (error) {
const command = `gh ${args.join(' ')}`
console.error(`Command failed: ${command}`)
console.error(error.stderr || err... | ', args, {
stdio: ['ignore', 'pipe', 'pipe'],
})
const chunks = []
let stderr = ''
child.stdout.on('data', (chunk) => chunks.push(chunk))
child.stderr.on('data', (chunk) => {
stderr += chunk
})
child.on('close', (co | tput) return []
return output
.split('\n')
.filter((line) => line.trim())
.map((line) => JSON.parse(line))
}
function execGhTextAsync(args) {
return new Promise((resolve, reject) => {
const child = spawn('gh | {
"filepath": "scripts/pr-logs.js",
"language": "javascript",
"file_size": 10824,
"cut_index": 921,
"middle_length": 229
} |
ca = require('execa')
const resolveFrom = require('resolve-from')
const {
configureGitHubAuth,
getGitHubToken,
getGitHubTokenMissingMessage,
verifyGitHubApiAccess,
} = require('./release-github-auth')
const { createGitHubReleaseCommit } = require('./release-github-api')
const SEMVER_TYPES = ['patch', 'minor', ... | e !== 'release-candidate' &&
releaseType !== 'beta'
) {
console.log(
`Invalid release type ${releaseType}, must be stable, canary, release-candidate, or beta`
)
return
}
if (!isCanary && !SEMVER_TYPES.includes(semverType)) {
| t isCanary = releaseType === 'canary'
const isReleaseCandidate = releaseType === 'release-candidate'
const isBeta = releaseType === 'beta'
if (
releaseType !== 'stable' &&
releaseType !== 'canary' &&
releaseTyp | {
"filepath": "scripts/start-release.js",
"language": "javascript",
"file_size": 2742,
"cut_index": 563,
"middle_length": 229
} |
string
nextEnvTarball: string
nextBundleAnalyzerTarball: string
nextSwcTarball: string
}
interface NextPeerDeps {
react: string
reactDom: string
[key: string]: unknown
}
export interface PackageJson {
dependencies?: Record<string, string>
peerDependencies?: Record<string, string>
overrides?: Record... | Promise<string> {
try {
const packageJsonPath = await findPackageJsonPath(targetProjectPath)
const packageJsonValue = await readJsonValue(packageJsonPath)
await patchWorkspacePackageJsonMap(paths, packageJsonValue)
await writeJsonValue(pa | Next.js tarball references
* @param paths Configuration options for patching
* @returns The path to the patched file
*/
export default async function patchPackageJson(
targetProjectPath: string,
paths: DependencyPaths
): | {
"filepath": "scripts/pack-utils/patch-package-json.ts",
"language": "typescript",
"file_size": 6076,
"cut_index": 716,
"middle_length": 229
} |
ocess')
const fs = require('fs')
const {
getGitHubToken,
getGitHubTokenMissingMessage,
} = require('./release-github-auth')
const cwd = process.cwd()
;(async function () {
let isCanary = true
let isReleaseCandidate = false
let isBeta = false
try {
const tagOutput = execSync(
`node ${path.join(_... | exiting...')
return
}
throw err
}
let tag = isCanary
? 'canary'
: isReleaseCandidate
? 'rc'
: isBeta
? 'beta'
: 'latest'
try {
if (!isCanary && !isReleaseCandidate && !isBeta) {
const vers | ndidate = tagOutput.includes('-rc')
isBeta = tagOutput.includes('-beta')
} catch (err) {
console.log(err)
if (err.message && err.message.includes('no tag exactly matches')) {
console.log('Nothing to publish, | {
"filepath": "scripts/publish-release.js",
"language": "javascript",
"file_size": 6048,
"cut_index": 716,
"middle_length": 229
} |
*
* Generate AGENTS.md and CLAUDE.md in the project root.
* AGENTS.md contains the instructions, CLAUDE.md references it using @ syntax.
*/
export function generateAgentFiles(root: string): void {
const agentsMdContent = `<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaki... | claudeMdContent = `@AGENTS.md
`
const agentsMdPath = path.join(root, 'AGENTS.md')
const claudeMdPath = path.join(root, 'CLAUDE.md')
fs.writeFileSync(agentsMdPath, agentsMdContent, 'utf-8')
fs.writeFileSync(claudeMdPath, claudeMdContent, 'utf-8') | notices.
<!-- END:nextjs-agent-rules -->
`
const | {
"filepath": "packages/create-next-app/helpers/generate-agent-files.ts",
"language": "typescript",
"file_size": 872,
"cut_index": 559,
"middle_length": 52
} |
const path = require('path')
const JSON5 = require('next/dist/compiled/json5')
const serverExternals = JSON5.parse(
fs.readFileSync(
path.join(
__dirname,
'../packages/next/src/lib/server-external-packages.jsonc'
),
'utf8'
)
)
function validate(docPath) {
const docContent = fs.readFileSy... | sh(docPkg)
}
}
for (const pkg of serverExternals) {
if (!docPkgs.includes(pkg)) {
missingPkgs.push(pkg)
}
}
if (extraPkgs.length || missingPkgs.length) {
console.log(
'server externals doc out of sync!\n' +
`Ex | .pop()
.split('| Version')
.shift()
.split('\n')) {
docPkg = docPkg.split('`')[1]
if (!docPkg) {
continue
}
docPkgs.push(docPkg)
if (!serverExternals.includes(docPkg)) {
extraPkgs.pu | {
"filepath": "scripts/validate-externals-doc.js",
"language": "javascript",
"file_size": 1667,
"cut_index": 537,
"middle_length": 229
} |
ion-call'
import { getFontAxes } from './get-font-axes'
import { getGoogleFontsUrl } from './get-google-fonts-url'
import { nextFontError } from '../next-font-error'
import { findFontFilesInCss } from './find-font-files-in-css'
import { getFallbackFontOverrideMetrics } from './get-fallback-font-override-metrics'
import... | ng) {
// see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23
if (reHasRegExp.test(str)) {
return str.replace(reReplaceRegExp, '\\$&')
}
return str
}
const nextFontGoogleFontLoader: FontL | <string, Buffer | null>()
// regexp is based on https://github.com/sindresorhus/escape-string-regexp
const reHasRegExp = /[|\\{}()[\]^$+*?.-]/
const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g
function escapeStringRegexp(str: stri | {
"filepath": "packages/font/src/google/loader.ts",
"language": "typescript",
"file_size": 6388,
"cut_index": 716,
"middle_length": 229
} |
disable */
import Image from "next/legacy/image";
import Named, { Blarg } from "next/legacy/image";
import type { ImageProps } from "next/legacy/image";
import { type ImageLoaderProps } from "next/legacy/image";
import Foo from "foo";
import img from "../public/img.jpg";
export default function Home() {
const myStyl... | x' }}>
<Image
alt="example alt text"
src={img}
layout="fill"
objectFit="contain"
/>
</div>
<Named src="/test.png" width="500" height="400" layout="fixed" />
<Foo bar="1" />
<Im | nsic" />
<Image src="/test.jpg" width="200" height="300" layout="responsive" />
<Image src="/test.jpg" width="200" height="300" layout="fixed" />
<div style={{ position: 'relative', width: '300px', height: '500p | {
"filepath": "packages/next-codemod/transforms/__testfixtures__/next-image-experimental/general.input.tsx",
"language": "tsx",
"file_size": 1655,
"cut_index": 537,
"middle_length": 229
} |
om "next/image";
import Named, { Blarg } from "next/image";
import type { ImageProps } from "next/image";
import { type ImageLoaderProps } from "next/image";
import Foo from "foo";
import img from "../public/img.jpg";
export default function Home() {
const myStyle = { color: 'black' };
return (
(<div>
<h... | sizes="100vw"
style={{
width: "100%",
height: "auto"
}} />
<Image src="/test.jpg" width="200" height="300" />
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
| src="/test.jpg"
width="300"
height="400"
style={{
maxWidth: "100%",
height: "auto"
}} />
<Image
src="/test.jpg"
width="200"
height="300"
| {
"filepath": "packages/next-codemod/transforms/__testfixtures__/next-image-experimental/general.output.tsx",
"language": "tsx",
"file_size": 2400,
"cut_index": 563,
"middle_length": 229
} |
-nocheck
import { unstable_cacheTag as cacheTagImport, unstable_cacheLife as cacheLifeImport } from 'next/cache'
const { unstable_cacheTag: cacheTagRequire, unstable_cacheLife: cacheLifeRequire } = require('next/cache')
// Alias with same API name, alias should be removed.
import { unstable_cacheTag as cacheTag, unstab... | ('redundant')
const cacheLifeAlias = cacheLife('redundant-time')
return (
<div>
<p>Using cache tag: {cacheTagImportTag}</p>
<p>Using cache life: {cacheLifeImportLife}</p>
<p>Using another tag: {cacheTagRequireTag}</p>
<p>Us | rtTag = cacheTagImport('foo')
const cacheLifeImportLife = cacheLifeImport('1 hour')
const cacheTagRequireTag = cacheTagRequire('bar')
const cacheLifeRequireLife = cacheLifeRequire('2 hours')
const cacheTagAlias = cacheTag | {
"filepath": "packages/next-codemod/transforms/__testfixtures__/remove-unstable-prefix/alias.input.tsx",
"language": "tsx",
"file_size": 1168,
"cut_index": 518,
"middle_length": 229
} |
/ @ts-nocheck
import { cacheTag as cacheTagImport, cacheLife as cacheLifeImport } from 'next/cache'
const { cacheTag: cacheTagRequire, cacheLife: cacheLifeRequire } = require('next/cache')
// Alias with same API name, alias should be removed.
import { cacheTag, cacheLife } from 'next/cache'
const { cacheTag, cacheLife ... | : {cacheTagImportTag}</p>
<p>Using cache life: {cacheLifeImportLife}</p>
<p>Using another tag: {cacheTagRequireTag}</p>
<p>Using another life: {cacheLifeRequireLife}</p>
<p>Using same alias tag: {cacheTagAlias}</p>
<p>Using sa | = cacheTagRequire('bar')
const cacheLifeRequireLife = cacheLifeRequire('2 hours')
const cacheTagAlias = cacheTag('redundant')
const cacheLifeAlias = cacheLife('redundant-time')
return (
<div>
<p>Using cache tag | {
"filepath": "packages/next-codemod/transforms/__testfixtures__/remove-unstable-prefix/alias.output.tsx",
"language": "tsx",
"file_size": 1050,
"cut_index": 513,
"middle_length": 229
} |
ops {
params: Promise<{
slug: string;
}>
}
export function generateMetadata(props: Props, parent: any) {
console.log({ ...parent })
}
export default async function Page(props: Props) {
const config = { /* @next-codemod-error 'props' is used with spread syntax (...). Any asynchronous properties of 'props' ... | accessed. */
...ctx }
)
}
export function POST(req, ctx) {
console.log(
{ ...req }
)
}
export function PATCH(req, ctx) {
console.log(
{ /* @next-codemod-ignore */ ...ctx }
)
}
export function PUT(req, ctx) {
console.log(
{
| en accessed. */
{...props} {...config} />)
);
}
export function GET(req, ctx) {
console.log(
{ /* @next-codemod-error 'ctx' is used with spread syntax (...). Any asynchronous properties of 'ctx' must be awaited when | {
"filepath": "packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-props/access-props-27.output.tsx",
"language": "tsx",
"file_size": 1325,
"cut_index": 524,
"middle_length": 229
} |
on getNextjsVersion(cwd: string): NextjsVersionResult {
try {
const nextPkgPath = require.resolve('next/package.json', { paths: [cwd] })
const pkg = JSON.parse(fs.readFileSync(nextPkgPath, 'utf-8'))
return { version: pkg.version }
} catch {
// Not found at root - check for monorepo workspace
con... | error: 'Next.js is not installed in this project.',
}
}
}
function versionToGitHubTag(version: string): string {
return version.startsWith('v') ? version : `v${version}`
}
interface PullOptions {
cwd: string
version?: string
docsDir?: | estVersion) {
return { version: highestVersion }
}
return {
version: null,
error: `No Next.js found in ${workspace.type} workspace packages.`,
}
}
return {
version: null,
| {
"filepath": "packages/next-codemod/lib/agents-md.ts",
"language": "typescript",
"file_size": 17089,
"cut_index": 921,
"middle_length": 229
} |
pe PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'
export function getPkgManager(baseDir: string): PackageManager {
try {
const lockFile = findUp.sync(
[
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'bun.lock',
'bun.lockb',
],
{ cwd: baseDir }
... | return 'npm'
}
}
export function uninstallPackage(
packageToUninstall: string,
pkgManager?: PackageManager
) {
pkgManager ??= getPkgManager(process.cwd())
if (!pkgManager) throw new Error('Failed to find package manager')
let command = 'un | ml':
return 'pnpm'
case 'bun.lock':
case 'bun.lockb':
return 'bun'
default:
return 'npm'
}
}
// No lock file found, default to npm
return 'npm'
} catch {
| {
"filepath": "packages/next-codemod/lib/handle-package.ts",
"language": "typescript",
"file_size": 3681,
"cut_index": 614,
"middle_length": 229
} |
ter/packages/react-dom/src/shared/possibleStandardNames.js
const possibleStandardNames = {
// HTML
accept: 'accept',
acceptcharset: 'acceptCharset',
'accept-charset': 'acceptCharset',
accesskey: 'accessKey',
action: 'action',
allowfullscreen: 'allowFullScreen',
alt: 'alt',
as: 'as',
async: 'async',
... | 'className',
cols: 'cols',
colspan: 'colSpan',
content: 'content',
contenteditable: 'contentEditable',
contextmenu: 'contextMenu',
controls: 'controls',
controlslist: 'controlsList',
coords: 'coords',
crossorigin: 'crossOrigin',
dangero | ,
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
challenge: 'challenge',
charset: 'charSet',
checked: 'checked',
children: 'children',
cite: 'cite',
class: 'className',
classid: 'classID',
classname: | {
"filepath": "packages/next-codemod/lib/html-to-react-attributes.ts",
"language": "typescript",
"file_size": 13747,
"cut_index": 921,
"middle_length": 229
} |
*/
import { yellow } from 'picocolors'
import spawn from 'cross-spawn'
interface InstallArgs {
/**
* Indicate whether to install packages using Yarn.
*/
useYarn: boolean
/**
* Indicate whether there is an active Internet connection.
*/
isOnline: boolean
/**
* Indicate whether the given depend... | lags: string[] = ['--logLevel', 'error']
/**
* Yarn-specific command-line flags.
*/
const yarnFlags: string[] = []
/**
* Return a Promise that resolves once the installation is finished.
*/
return new Promise((resolve, reject) => {
| on is finished.
*/
export function install(
root: string,
dependencies: string[] | null,
{ useYarn, isOnline, devDependencies }: InstallArgs
): Promise<void> {
/**
* NPM-specific command-line flags.
*/
const npmF | {
"filepath": "packages/next-codemod/lib/install.ts",
"language": "typescript",
"file_size": 2790,
"cut_index": 563,
"middle_length": 229
} |
tus(force) {
let clean = false
let errorMessage = 'Unable to determine if git directory is clean'
try {
clean = isGitClean.sync(process.cwd())
errorMessage = 'Git directory is not clean'
} catch (err) {
if (err && err.stderr && err.stderr.includes('Not a git repository')) {
clean = true
}
... | xit(1)
}
}
}
export function onCancel() {
process.exit(1)
}
/**
* When adding a new codemod, ensure to set the target canary version
* instead of the stable version. This is for `@next/codemod upgrade`
* to correctly pick up the codemod for th | (
yellow(
'\nBut before we continue, please stash or commit your git changes.'
)
)
console.log(
'\nYou may use the --force flag to override this safety check.'
)
process.e | {
"filepath": "packages/next-codemod/lib/utils.ts",
"language": "typescript",
"file_size": 4346,
"cut_index": 614,
"middle_length": 229
} |
h'
import type { API, FileInfo, Options } from 'jscodeshift'
import { createParserFromPath } from '../parser'
export const globalCssContext = {
cssImports: new Set<string>(),
reactSvgImports: new Set<string>(),
}
const globalStylesRegex = /(?<!\.module)\.(css|scss|sass)$/i
export default function transformer(
f... | ue
if (value.startsWith('.')) {
resolvedPath = nodePath.resolve(nodePath.dirname(file.path), value)
}
globalCssContext.cssImports.add(resolvedPath)
const { start, end } = path.node as any
if | n)
.filter((path) => {
const {
node: {
source: { value },
},
} = path
if (typeof value === 'string') {
if (globalStylesRegex.test(value)) {
let resolvedPath = val | {
"filepath": "packages/next-codemod/lib/cra-to-next/global-css-transform.ts",
"language": "typescript",
"file_size": 1790,
"cut_index": 537,
"middle_length": 229
} |
from 'jscodeshift'
import { createParserFromPath } from '../parser'
export const indexContext = {
multipleRenderRoots: false,
nestedRender: false,
}
export default function transformer(
file: FileInfo,
_api: API,
options: Options
) {
const j = createParserFromPath(file.path)
const root = j(file.source)
... | 'ImportDefaultSpecifier') {
defaultReactDomImport = specifier.local.name
}
})
}
return false
})
root
.find(j.CallExpression)
.filter((path) => {
const { node } = path
let found = false
if (
| if (path.node.source.value === 'react-dom') {
return path.node.specifiers.forEach((specifier) => {
if (specifier.local.name === 'render') {
hasRenderImport = true
}
if (specifier.type === | {
"filepath": "packages/next-codemod/lib/cra-to-next/index-to-component.ts",
"language": "typescript",
"file_size": 2716,
"cut_index": 563,
"middle_length": 229
} |
.0 --output CLAUDE.md
*/
describe('agents-md e2e (CLI invocation)', () => {
let testProjectDir
let originalConsoleLog
let consoleOutput
beforeEach(() => {
// Create isolated test project directory
const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir()
testProjectDir = path.join(
tmpBase,
... | st directory
if (testProjectDir && fs.existsSync(testProjectDir)) {
fs.rmSync(testProjectDir, { recursive: true, force: true })
}
})
it('creates CLAUDE.md and .next-docs directory when run with --version and --output', async () => {
| og = console.log
consoleOutput = []
console.log = (...args) => {
consoleOutput.push(args.join(' '))
}
})
afterEach(() => {
// Restore console.log
console.log = originalConsoleLog
// Clean up te | {
"filepath": "packages/next-codemod/lib/__tests__/agents-md-e2e.test.js",
"language": "javascript",
"file_size": 10191,
"cut_index": 921,
"middle_length": 229
} |
rs'
import { BadInput } from './shared'
import {
getNextjsVersion,
pullDocs,
collectDocFiles,
buildDocTree,
generateClaudeMdIndex,
injectIntoClaudeMd,
ensureGitignoreEntry,
} from '../lib/agents-md'
import { onCancel } from '../lib/utils'
export interface AgentsMdOptions {
version?: string
output?: s... | ompts for version + target file)
// 2. --version provided → --output is REQUIRED (error if missing)
// 3. --output alone → auto-detect version, error if not found
let nextjsVersion: string
let targetFile: string
if (options.version) {
// -- | d(1)} KB`
const mb = kb / 1024
return `${mb.toFixed(1)} MB`
}
export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
const cwd = process.cwd()
// Mode logic:
// 1. No flags → interactive mode (pr | {
"filepath": "packages/next-codemod/bin/agents-md.ts",
"language": "typescript",
"file_size": 5628,
"cut_index": 716,
"middle_length": 229
} |
nder the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// Based on https://github.com/reactjs/react-codemod/blob/dd8671c9a470a2c342b221ec903c574cf31e9f57/bin/cli.js
// @next/codemod optional-name-of-transform optional/path/to/src [...options]
import { Command } from 'comman... |
)
.argument(
'[codemod]',
'Codemod slug to run. See "https://github.com/vercel/next.js/tree/canary/packages/next-codemod".'
)
.argument(
'[source]',
'Path to source files or directory to transform including glob patterns.'
)
.u | e('../package.json')
const program = new Command(packageJson.name)
.description('Codemods for updating Next.js apps.')
.version(
packageJson.version,
'-v, --version',
'Output the current version of @next/codemod.' | {
"filepath": "packages/next-codemod/bin/next-codemod.ts",
"language": "typescript",
"file_size": 3466,
"cut_index": 614,
"middle_length": 229
} |
./lib/handle-package'
import {
checkGitStatus,
onCancel,
TRANSFORMER_INQUIRER_CHOICES,
} from '../lib/utils'
function expandFilePathsIfNeeded(filesBeforeExpansion) {
const shouldExpandFiles = filesBeforeExpansion.some((file) =>
file.includes('*')
)
return shouldExpandFiles
? globby.sync(filesBefore... | !TRANSFORMER_INQUIRER_CHOICES.find((x) => x.value === transform)
) {
console.error('Invalid transform choice, pick one of:')
console.error(
TRANSFORMER_INQUIRER_CHOICES.map((x) => '- ' + x.value).join('\n')
)
process.exit(1)
}
| rt async function runTransform(
transform: string,
path: string,
options: any
) {
let transformer = transform
let directory = path
if (!options.dry) {
checkGitStatus(options.force)
}
if (
transform &&
| {
"filepath": "packages/next-codemod/bin/transform.ts",
"language": "typescript",
"file_size": 6479,
"cut_index": 716,
"middle_length": 229
} |
e',
'@next/polyfill-nomodule',
'@next/swc',
'@next/react-refresh-utils',
'@next/third-parties',
]
/**
* @param query
* @example loadHighestNPMVersionMatching("react@^18.3.0 || ^19.0.0") === Promise<"19.0.0">
*/
async function loadHighestNPMVersionMatching(query: string) {
const versionsJSON = execSync(
... | // The last entry will be the latest version published.
// But we want the highest version.
versionOrVersions.sort(compareVersions)
return versionOrVersions[versionOrVersions.length - 1]
}
return versionOrVersions
}
function endMessage | Error(
`Found no React versions matching "${query}". This is a bug in the upgrade tool.`
)
}
// npm-view returns an array if there are multiple versions matching the query.
if (Array.isArray(versionOrVersions)) {
| {
"filepath": "packages/next-codemod/bin/upgrade.ts",
"language": "typescript",
"file_size": 25658,
"cut_index": 1331,
"middle_length": 229
} |
'
import googleFontPreconnect from './rules/google-font-preconnect'
import inlineScriptId from './rules/inline-script-id'
import nextScriptForGa from './rules/next-script-for-ga'
import noAssignModuleVariable from './rules/no-assign-module-variable'
import noAsyncClientComponent from './rules/no-async-client-component'... | nkForPages from './rules/no-html-link-for-pages'
import noImgElement from './rules/no-img-element'
import noLocationAssign from './rules/no-location-assign-relative-destination'
import noPageCustomFont from './rules/no-page-custom-font'
import noScriptComp | rules/no-document-import-in-page'
import noDuplicateHead from './rules/no-duplicate-head'
import noHeadElement from './rules/no-head-element'
import noHeadImportInDocument from './rules/no-head-import-in-document'
import noHtmlLi | {
"filepath": "packages/eslint-plugin-next/src/index.ts",
"language": "typescript",
"file_size": 4873,
"cut_index": 614,
"middle_length": 229
} |
t { globSync } from 'fast-glob'
import type { Rule } from 'eslint'
/**
* Process a Next.js root directory glob.
*/
const processRootDir = (rootDir: string): string[] => {
return globSync(rootDir.replace(/\\/g, '/'), {
onlyDirectories: true,
})
}
/**
* Gets one or more Root, returns an array of root directo... | nextSettings.rootDir
if (typeof rootDir === 'string') {
rootDirs = processRootDir(rootDir)
} else if (Array.isArray(rootDir)) {
rootDirs = rootDir
.map((dir) => (typeof dir === 'string' ? processRootDir(dir) : []))
.flat()
}
r | let rootDir = | {
"filepath": "packages/eslint-plugin-next/src/utils/get-root-dirs.ts",
"language": "typescript",
"file_size": 804,
"cut_index": 517,
"middle_length": 14
} |
values of a node in a convenient way:
/* example:
<ExampleElement attr1="15" attr2>
{ attr1: {
hasValue: true,
value: 15
},
attr2: {
hasValue: false
}
Inclusion of hasValue is in case an eslint rule cares about boolean values
explicitly assigned to ... | if (!!attribute.value) {
// hasValue
const value =
typeof attribute.value.value === 'string'
? attribute.value.value
: typeof attribute.value.expression.value !== 'undefined'
? attribute.value | ue
value: any
}
>
constructor(ASTnode) {
this.attributes = {}
ASTnode.attributes.forEach((attribute) => {
if (!attribute.type || attribute.type !== 'JSXAttribute') {
return
}
| {
"filepath": "packages/eslint-plugin-next/src/utils/node-attributes.ts",
"language": "typescript",
"file_size": 1732,
"cut_index": 537,
"middle_length": 229
} |
Recursively parse directory for page URLs.
*/
function parseUrlForPages(urlprefix: string, directory: string) {
fsReadDirSyncCache[directory] ??= fs.readdirSync(directory, {
withFileTypes: true,
})
const res = []
fsReadDirSyncCache[directory].forEach((dirent) => {
// TODO: this should account for all ... | ectory() && !dirent.isSymbolicLink()) {
res.push(...parseUrlForPages(urlprefix + dirent.name + '/', dirPath))
}
}
})
return res
}
/**
* Recursively parse app directory for URLs.
*/
function parseUrlForAppDir(urlprefix: string, dire | ent.name.replace(/^index(\.(j|t)sx?)$/, '')}`
)
}
res.push(`${urlprefix}${dirent.name.replace(/(\.(j|t)sx?)$/, '')}`)
} else {
const dirPath = path.join(directory, dirent.name)
if (dirent.isDir | {
"filepath": "packages/eslint-plugin-next/src/utils/url.ts",
"language": "typescript",
"file_size": 5615,
"cut_index": 716,
"middle_length": 229
} |
m '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'
const url = 'https://nextjs.org/docs/messages/google-font-display'
export default defineRule({
meta: {
docs: {
description: 'Enforce font-display behavior with Google Fonts.',
recommended: true,
url,
},
type... | nst isGoogleFont =
typeof hrefValue === 'string' &&
hrefValue.startsWith('https://fonts.googleapis.com/css')
if (isGoogleFont) {
const params = new URLSearchParams(hrefValue.split('?', 2)[1])
const displayVa | eturn
}
const attributes = new NodeAttributes(node)
if (!attributes.has('href') || !attributes.hasValue('href')) {
return
}
const hrefValue = attributes.value('href')
co | {
"filepath": "packages/eslint-plugin-next/src/rules/google-font-display.ts",
"language": "typescript",
"file_size": 1678,
"cut_index": 537,
"middle_length": 229
} |
{ defineRule } from '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'
const url = 'https://nextjs.org/docs/messages/google-font-preconnect'
export default defineRule({
meta: {
docs: {
description: 'Ensure `preconnect` is used with Google Fonts.',
recommended: true,
... | =
!attributes.has('rel') ||
!attributes.hasValue('rel') ||
attributes.value('rel') !== 'preconnect'
if (
typeof hrefValue === 'string' &&
hrefValue.startsWith('https://fonts.gstatic.com') &&
| const attributes = new NodeAttributes(node)
if (!attributes.has('href') || !attributes.hasValue('href')) {
return
}
const hrefValue = attributes.value('href')
const preconnectMissing | {
"filepath": "packages/eslint-plugin-next/src/rules/google-font-preconnect.ts",
"language": "typescript",
"file_size": 1215,
"cut_index": 518,
"middle_length": 229
} |
const url = 'https://nextjs.org/docs/messages/inline-script-id'
export default defineRule({
meta: {
docs: {
description:
'Enforce `id` attribute on `next/script` components with inline content.',
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) ... | extScriptImportName
) {
return
}
const attributeNames = new Set()
let hasNonCheckableSpreadAttribute = false
node.openingElement.attributes.forEach((attribute) => {
// Early return if we already | .name
}
},
JSXElement(node) {
if (nextScriptImportName == null) return
if (
node.openingElement &&
node.openingElement.name &&
node.openingElement.name.name !== n | {
"filepath": "packages/eslint-plugin-next/src/rules/inline-script-id.ts",
"language": "typescript",
"file_size": 2304,
"cut_index": 563,
"middle_length": 229
} |
'
const GOOGLE_ANALYTICS_URL = 'www.google-analytics.com/analytics.js'
const GOOGLE_TAG_MANAGER_URL = 'www.googletagmanager.com/gtag/js'
const GOOGLE_ANALYTICS_SRC = GOOGLE_ANALYTICS_URL
const GOOGLE_TAG_MANAGER_SRC = 'www.googletagmanager.com/gtm.js'
const description =
'Prefer `@next/third-parties/google` when u... | ng the inline script for Google Tag Manager. See: ${url}`
export default defineRule({
meta: {
docs: {
description,
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
return {
JSXO | omponent from \`@next/third-parties/google\` when using the inline script for Google Analytics. See: ${url}`
const ERROR_MSG_GOOGLE_TAG_MANAGER = `Prefer \`GoogleTagManager\` component from \`@next/third-parties/google\` when usi | {
"filepath": "packages/eslint-plugin-next/src/rules/next-script-for-ga.ts",
"language": "typescript",
"file_size": 3053,
"cut_index": 614,
"middle_length": 229
} |
/nextjs.org/docs/messages/no-assign-module-variable'
export default defineRule({
meta: {
docs: {
description: 'Prevent assignment to the `module` variable.',
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
return {
VariableDeclaration(node... | == 'module'
}
return false
})
// Return early if no `module` variable is found
if (!moduleVariableFound) {
return
}
context.report({
node,
message: `Do not assign t | ation.id) {
return declaration.id.name = | {
"filepath": "packages/eslint-plugin-next/src/rules/no-assign-module-variable.ts",
"language": "typescript",
"file_size": 965,
"cut_index": 582,
"middle_length": 52
} |
ync-client-component'
const description = 'Prevent Client Components from being async functions.'
const message = `${description} See: ${url}`
function isCapitalized(str: string): boolean {
return /[A-Z]/.test(str?.[0])
}
export default defineRule({
meta: {
docs: {
description,
recommended: true,
... | true
}
if (block.type === 'ExportDefaultDeclaration' && isClientComponent) {
// export default async function MyComponent() {...}
if (
block.declaration?.type === 'FunctionDeclaration' &&
| node.body) {
if (
block.type === 'ExpressionStatement' &&
block.expression.type === 'Literal' &&
block.expression.value === 'use client'
) {
isClientComponent = | {
"filepath": "packages/eslint-plugin-next/src/rules/no-async-client-component.ts",
"language": "typescript",
"file_size": 3259,
"cut_index": 614,
"middle_length": 229
} |
m '../utils/define-rule'
import * as path from 'path'
const url =
'https://nextjs.org/docs/messages/no-before-interactive-script-outside-document'
const convertToCorrectSeparator = (str: string) =>
str.replace(/[\\/]/g, path.sep)
export default defineRule({
meta: {
docs: {
description:
"Preve... | ement(node) {
const pathname = convertToCorrectSeparator(context.filename)
const isInAppDir = pathname.includes(`${path.sep}app${path.sep}`)
// This rule shouldn't fire in `app/`
if (isInAppDir) {
return
| t) {
let scriptImportName = null
return {
'ImportDeclaration[source.value="next/script"] > ImportDefaultSpecifier'(
node: any
) {
scriptImportName = node.local.name
},
JSXOpeningEl | {
"filepath": "packages/eslint-plugin-next/src/rules/no-before-interactive-script-outside-document.ts",
"language": "typescript",
"file_size": 1842,
"cut_index": 537,
"middle_length": 229
} |
{ defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-css-tags'
export default defineRule({
meta: {
docs: {
description: 'Prevent manual stylesheet tags.',
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
ret... | eet'
) &&
attributes.find(
(attr) =>
attr.name.name === 'href' &&
attr.value.type === 'Literal' &&
!/^https?/.test(attr.value.value)
)
) {
context.report( | attributes = node.attributes.filter(
(attr) => attr.type === 'JSXAttribute'
)
if (
attributes.find(
(attr) =>
attr.name.name === 'rel' && attr.value.value === 'stylesh | {
"filepath": "packages/eslint-plugin-next/src/rules/no-css-tags.ts",
"language": "typescript",
"file_size": 1142,
"cut_index": 518,
"middle_length": 229
} |
import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const url = 'https://nextjs.org/docs/messages/no-document-import-in-page'
export default defineRule({
meta: {
docs: {
description:
'Prevent importing `next/document` outside of `pages/_document.js`.',
recommended:... | th(`${path.posix.sep}_document`)
) {
return
}
context.report({
node,
message: `\`<Document />\` from \`next/document\` should not be imported outside of \`pages/_document.js\`. See: ${url}`,
}) | return
}
const paths = context.filename.split('pages')
const page = paths[paths.length - 1]
if (
!page ||
page.startsWith(`${path.sep}_document`) ||
page.startsWi | {
"filepath": "packages/eslint-plugin-next/src/rules/no-document-import-in-page.ts",
"language": "typescript",
"file_size": 1021,
"cut_index": 512,
"middle_length": 229
} |
onst url = 'https://nextjs.org/docs/messages/no-duplicate-head'
export default defineRule({
meta: {
docs: {
description:
'Prevent duplicate usage of `<Head>` in `pages/_document.js`.',
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
const... | },
ReturnStatement(node) {
const ancestors = sourceCode.getAncestors(node)
const documentClass = ancestors.find(
(ancestorNode) =>
ancestorNode.type === 'ClassDeclaration' &&
ancestorNode.superClass & | cifiers.find(
({ type }) => type === 'ImportDefaultSpecifier'
)
if (documentImport && documentImport.local) {
documentImportName = documentImport.local.name
}
}
| {
"filepath": "packages/eslint-plugin-next/src/rules/no-duplicate-head.ts",
"language": "typescript",
"file_size": 2068,
"cut_index": 563,
"middle_length": 229
} |
parameter in `Array.prototype.sort` function to ensure correct sorting.
*/
export function sortFontsVariantValues(valA: string, valB: string) {
// If both values contain commas, it indicates they are in "ital,wght" format
if (valA.includes(',') && valB.includes(',')) {
// Split the values into prefix and suf... | lues)
return parseInt(aSuffix) - parseInt(bSuffix)
} else {
// If prefixes are different, then compare the prefixes directly
return parseInt(aPrefix) - parseInt(bPrefix)
}
}
// If values are not in "ital,wght" format, then di | efixes are equal, then compare the suffixes (wght va | {
"filepath": "packages/font/src/google/sort-fonts-variant-values.ts",
"language": "typescript",
"file_size": 965,
"cut_index": 582,
"middle_length": 52
} |
vailable-values'
import { nextFontError } from '../next-font-error'
import { googleFontsMetadata } from './google-fonts-metadata'
type FontOptions = {
fontFamily: string
weights: string[]
styles: string[]
display: string
preload: boolean
selectedVariableAxes?: string[]
fallback?: string[]
adjustFontFal... | sets,
} = fontFunctionArgument || ({} as any)
if (functionName === '') {
nextFontError(`next/font/google has no default export`)
}
const fontFamily = functionName.replace(/_/g, ' ')
// Get the Google font metadata, we'll use this to validate | ctionCall(
functionName: string,
fontFunctionArgument: any
): FontOptions {
let {
weight,
style,
preload = true,
display = 'swap',
axes,
fallback,
adjustFontFallback = true,
variable,
sub | {
"filepath": "packages/font/src/google/validate-google-font-function-call.ts",
"language": "typescript",
"file_size": 4669,
"cut_index": 614,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.