prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
time,
} from '../server/config-shared'
function errorIfEnvConflicted(
config: NextConfigComplete | NextConfigRuntime,
key: string
) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
const hasNextRuntimeKey = key === 'NEXT_RUNTIME'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
... | _')) {
const value = process.env[key]
if (value != null) {
defineEnv.push([`process.env.${key}`, value])
}
}
}
defineEnv.sort((a, b) => a[0].localeCompare(b[0]))
return Object.fromEntries(defineEnv)
}
/**
* Collects th | les that are using the `NEXT_PUBLIC_` prefix.
*/
export function getNextPublicEnvironmentVariables() {
const defineEnv: [string, string | undefined][] = []
for (const key in process.env) {
if (key.startsWith('NEXT_PUBLIC | {
"filepath": "packages/next/src/lib/static-env.ts",
"language": "typescript",
"file_size": 2316,
"cut_index": 563,
"middle_length": 229
} |
-to-regexp'
import { parse, tokensToRegexp } from 'next/dist/compiled/path-to-regexp'
import isError from './is-error'
import { normalizeTokensForRegexp } from './route-pattern-normalizer'
interface ParseResult {
error?: any
parsedPath: string
regexStr?: string
route: string
tokens?: Token[]
}
/**
* If the... | te-source\n` +
`Reason: ${err.message}\n\n` +
` ${parsedPath}\n` +
` ${new Array(position).fill(' ').join('')}^\n`
)
} else {
console.error(
`\nError parsing ${route} https://nextjs.org/docs/messages/invalid-route- | (isError(err) && (errMatches = err.message.match(/at (\d{0,})/))) {
const position = parseInt(errMatches[1], 10)
console.error(
`\nError parsing \`${route}\` ` +
`https://nextjs.org/docs/messages/invalid-rou | {
"filepath": "packages/next/src/lib/try-to-parse-path.ts",
"language": "typescript",
"file_size": 2540,
"cut_index": 563,
"middle_length": 229
} |
Left to be implemented (priority)
// 'experimental.clientRouterFilter',
// 'experimental.optimizePackageImports',
// 'compiler.emotion',
// 'compiler.reactRemoveProperties',
// 'compiler.relay',
// 'compiler.removeConsole',
// 'compiler.styledComponents',
'experimental.fetchCacheKeyPrefix',
// Left ... | needed for Turbopack)
'experimental.craCompat',
'experimental.disablePostcssPresetEnv',
'experimental.esmExternals',
// This is used to force swc-loader to run regardless of finding Babel.
'experimental.forceSwcTransforms',
'experimental.fullyS | erimental.serverSourceMaps',
'experimental.allowedRevalidateHeaderKeys',
'experimental.extensionAlias',
'experimental.fallbackNodePolyfills',
'experimental.swcTraceProfiling',
// Left to be implemented (Might not be | {
"filepath": "packages/next/src/lib/turbopack-warning.ts",
"language": "typescript",
"file_size": 6073,
"cut_index": 716,
"middle_length": 229
} |
{ UrlWithParsedQuery } from 'url'
import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
const DUMMY_ORIGIN = 'http://n'
export function isFullStringUrl(url: string) {
return /https?:\/\//.test(url)
}
export function parseUrl(url: string): URL | undefined {
let parsed: URL | undefined = u... | ry[key] = values.length > 1 ? values : values[0]
}
const legacyUrl: UrlWithParsedQuery = {
query,
hash: parsedUrl.hash,
search: parsedUrl.search,
path: parsedUrl.pathname,
pathname: parsedUrl.pathname,
href: `${parsedUrl.pathna | efined = parseUrl(url)
if (!parsedUrl) {
return
}
const query: Record<string, string | string[]> = {}
for (const key of parsedUrl.searchParams.keys()) {
const values = parsedUrl.searchParams.getAll(key)
que | {
"filepath": "packages/next/src/lib/url.ts",
"language": "typescript",
"file_size": 1411,
"cut_index": 524,
"middle_length": 229
} |
red } from './picocolors'
import path from 'path'
import { hasNecessaryDependencies } from './has-necessary-dependencies'
import type { NecessaryDependencies } from './has-necessary-dependencies'
import { fileExists, FileType } from './file-exists'
import * as Log from '../build/output/log'
import { getPkgManager } fr... | (
(packageManager === 'yarn'
? 'yarn add --dev'
: packageManager === 'pnpm'
? 'pnpm install --save-dev'
: 'npm install --save-dev') + ' @builder.io/partytown'
)
)}` +
'\n\n' | you're trying to use Partytown with next/script but do not have the required package(s) installed."
)
) +
'\n\n' +
bold(`Please install Partytown by running:`) +
'\n\n' +
`\t${bold(
cyan | {
"filepath": "packages/next/src/lib/verify-partytown-setup.ts",
"language": "typescript",
"file_size": 2489,
"cut_index": 563,
"middle_length": 229
} |
import { bold } from './picocolors'
import { APP_DIR_ALIAS } from './constants'
import type { PageExtensions } from '../build/page-extensions-type'
const globOrig =
require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
const glob = (cwd: string, pattern: string): Promise<string[]> => {
re... | eturn (
<html lang="en">
<body>{children}</body>
</html>
)
}
`
}
return `export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html la | tLayout(isTs: boolean) {
if (isTs) {
return `export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
r | {
"filepath": "packages/next/src/lib/verify-root-layout.ts",
"language": "typescript",
"file_size": 3968,
"cut_index": 614,
"middle_length": 229
} |
} from 'fs'
import { promises, constants } from 'fs'
import { Sema } from 'next/dist/compiled/async-sema'
import isError from './is-error'
const COPYFILE_EXCL = constants.COPYFILE_EXCL
export async function recursiveCopy(
source: string,
dest: string,
{
concurrency = 32,
overwrite = false,
filter =... | t = item.replace(from, to)
await sema.acquire()
if (!lstats) {
// after lock on first run
lstats = await promises.lstat(from)
}
// readdir & lstat do not follow symbolic links
// if part is a symbolic link, follow it with | lve(cwdPath, source)
const to = path.resolve(cwdPath, dest)
const sema = new Sema(concurrency)
// deep copy the file/directory
async function _copy(item: string, lstats?: Stats | Dirent): Promise<void> {
const targe | {
"filepath": "packages/next/src/lib/recursive-copy.ts",
"language": "typescript",
"file_size": 2308,
"cut_index": 563,
"middle_length": 229
} |
s from 'node:fs'
import { join } from 'node:path'
import isError from './is-error'
import { wait } from './wait'
// We use an exponential backoff. See the unit test for example values.
//
// - Node's `fs` module uses a linear backoff, starting with 100ms.
// - Rust tries 64 times with only a `thread::yield_now` in bet... | Dir = false,
attempt = 0
): Promise<void> | void {
try {
if (isDir) {
fs.rmdirSync(p)
} else {
fs.unlinkSync(p)
}
} catch (e) {
const code = isError(e) && e.code
if (
(code === 'EBUSY' ||
code === 'ENOTEM | MAX_RETRIES = 6
/**
* Used in unit test.
* @ignore
*/
export function calcBackoffMs(attempt: number): number {
return Math.min(INITIAL_RETRY_MS * Math.pow(2, attempt), MAX_RETRY_MS)
}
function unlinkPath(
p: string,
is | {
"filepath": "packages/next/src/lib/recursive-delete.ts",
"language": "typescript",
"file_size": 2915,
"cut_index": 563,
"middle_length": 229
} |
This module imports the client instrumentation hook from the project root.
*
* The `private-next-instrumentation-client` module is automatically aliased to
* the `instrumentation-client.ts` file in the project root by webpack or turbopack.
*/
if (process.env.NODE_ENV === 'development') {
const measureName = 'Cli... | on
// could potentially cause frame drops during development.
const THRESHOLD = 16
if (duration > THRESHOLD) {
console.log(
`[${measureName}] Slow execution detected: ${duration.toFixed(0)}ms (Note: Code download overhead is not included in | umentation-client')
const endTime = performance.now()
const duration = endTime - startTime
// Using 16ms threshold as it represents one frame (1000ms/60fps)
// This helps identify if the instrumentation hook initializati | {
"filepath": "packages/next/src/lib/require-instrumentation-client.ts",
"language": "typescript",
"file_size": 1192,
"cut_index": 518,
"middle_length": 229
} |
ttps://github.com/sindresorhus/resolve-from
import path from 'path'
import isError from './is-error'
import { realpathSync } from './realpath'
const Module = require('module') as typeof import('module')
export const resolveFrom = (
fromDirectory: string,
moduleId: string,
silent?: boolean
) => {
if (typeof fr... | ror.code === 'ENOENT') {
fromDirectory = path.resolve(fromDirectory)
} else if (silent) {
return
} else {
throw error
}
}
const fromFile = path.join(fromDirectory, 'noop.js')
const resolveFileName = () =>
// @ts-ex | throw new TypeError(
`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``
)
}
try {
fromDirectory = realpathSync(fromDirectory)
} catch (error: unknown) {
if (isError(error) && er | {
"filepath": "packages/next/src/lib/resolve-from.ts",
"language": "typescript",
"file_size": 1335,
"cut_index": 524,
"middle_length": 229
} |
a given page can have.
*/
export const enum FallbackMode {
/**
* A BLOCKING_STATIC_RENDER fallback will block the request until the page is
* generated. No fallback page will be rendered, and users will have to wait
* to render the page.
*/
BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',
/**
*... | StaticPaths` function.
*/
export type GetStaticPathsFallback = boolean | 'blocking'
/**
* Parses the fallback field from the prerender manifest.
*
* @param fallbackField The fallback field from the prerender manifest.
* @returns The fallback mode.
* | /
PRERENDER = 'PRERENDER',
/**
* When set to NOT_FOUND, pages that are not already prerendered will result
* in a not found response.
*/
NOT_FOUND = 'NOT_FOUND',
}
/**
* The fallback value returned from the `get | {
"filepath": "packages/next/src/lib/fallback.ts",
"language": "typescript",
"file_size": 2616,
"cut_index": 563,
"middle_length": 229
} |
next/dist/compiled/find-up'
import * as Log from '../build/output/log'
function findWorkRoot(cwd: string) {
// Find-up evaluates the list of files at each level.
// For pnpm-workspace.yaml we first want to look up before searching for lockfiles as those can be included in the application directory by accident.
c... | g
} {
const lockFile = findWorkRoot(cwd)
if (!lockFile)
return {
lockFiles: [],
rootDir: cwd,
}
const lockFiles = [lockFile]
while (true) {
const lastLockFile = lockFiles[lockFiles.length - 1]
const currentDir = dirname | pm-lock.yaml',
'package-lock.json',
'yarn.lock',
'bun.lock',
'bun.lockb',
],
{
cwd,
}
)
}
export function findRootDirAndLockFiles(cwd: string): {
lockFiles: string[]
rootDir: strin | {
"filepath": "packages/next/src/lib/find-root.ts",
"language": "typescript",
"file_size": 2992,
"cut_index": 563,
"middle_length": 229
} |
from 'path'
import { pathToFileURL, fileURLToPath } from 'url'
/**
* Converts a cache handler path to a filesystem path.
* ESM's import.meta.resolve() returns file:// URLs which break when concatenated
* with .next/ or used with path.join/path.relative.
* @param filePath - Absolute path, relative path, or file:// ... | eginning of the path as a protocol (`C:`).
* Therefore, it is important to always construct a complete path.
* @param dir File directory
* @param filePath Absolute or relative path, or file:// URL (e.g. from import.meta.resolve)
*/
export const formatD | h.startsWith('file://')) {
return fileURLToPath(filePath)
}
return filePath
}
/**
* The path for a dynamic route must be URLs with a valid scheme.
*
* When an absolute Windows path is passed to it, it interprets the b | {
"filepath": "packages/next/src/lib/format-dynamic-import-path.ts",
"language": "typescript",
"file_size": 1363,
"cut_index": 524,
"middle_length": 229
} |
{ formatServerError } from './format-server-error'
describe('formatServerError', () => {
it('should not append message several times', () => {
const err = new Error(
'Class extends value undefined is not a constructor or null'
)
// Before
expect(err.message).toMatchInlineSnapshot(
`"Cla... | ponent-in-server-component"
`)
// After second
formatServerError(err)
expect(err.message).toMatchInlineSnapshot(`
"Class extends value undefined is not a constructor or null
This might be caused by a React Class Component bein | not a constructor or null
This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-com | {
"filepath": "packages/next/src/lib/format-server-error.test.ts",
"language": "typescript",
"file_size": 1189,
"cut_index": 518,
"middle_length": 229
} |
/ From root
expect(headerRegex.test('/groups')).toBe(true) // From /groups
expect(headerRegex.test('/groups/123')).toBe(true) // From /groups/123 (THE BUG FIX!)
expect(headerRegex.test('/groups/123/settings')).toBe(true) // From any nested route
expect(headerRegex.test('/other/route/deep')).toBe... | ntercepting-routes/feed/photos/:nxtPid')
// Destination should be the intercepting route with the same named parameter
expect(rewrite.destination).toBe(
'/intercepting-routes/feed/(.)photos/:nxtPid'
)
// Verify the regex i | ercepting-routes/feed/(.)photos/[id]',
])
expect(rewrites).toHaveLength(1)
const rewrite = rewrites[0]
// Source should be the intercepted route with named parameter
expect(rewrite.source).toBe('/i | {
"filepath": "packages/next/src/lib/generate-interception-routes-rewrites.test.ts",
"language": "typescript",
"file_size": 90813,
"cut_index": 3790,
"middle_length": 229
} |
: string[] {
const interfaces = os.networkInterfaces()
const hosts: string[] = []
Object.keys(interfaces).forEach((key) => {
interfaces[key]
?.filter((networkInterface) => {
switch (networkInterface.family) {
case 'IPv6':
return (
family === 'IPv6' &&
... | n false
}
})
.forEach((networkInterface) => {
if (networkInterface.address) {
hosts.push(networkInterface.address)
}
})
})
return hosts
}
export function getNetworkHost(family: 'IPv4' | 'IPv6'): str | !== '127.0.0.1'
default:
retur | {
"filepath": "packages/next/src/lib/get-network-host.ts",
"language": "typescript",
"file_size": 971,
"cut_index": 582,
"middle_length": 52
} |
from 'fs'
import findUp from 'next/dist/compiled/find-up'
import JSON5 from 'next/dist/compiled/json5'
import * as path from 'path'
type PackageJsonDependencies = {
dependencies: Record<string, string>
devDependencies: Record<string, string>
}
let cachedDeps: Promise<PackageJsonDependencies>
export function get... |
const packageJson: any = JSON5.parse(content)
const { dependencies = {}, devDependencies = {} } = packageJson || {}
return { dependencies, devDependencies }
})())
}
export async function getPackageVersion({
cwd,
name,
}: {
cwd: strin | : string | undefined = await findUp('package.json', {
cwd,
})
if (!configurationPath) {
return { dependencies: {}, devDependencies: {} }
}
const content = await fs.readFile(configurationPath, 'utf-8') | {
"filepath": "packages/next/src/lib/get-package-version.ts",
"language": "typescript",
"file_size": 1585,
"cut_index": 537,
"middle_length": 229
} |
t { resolveFrom } from './resolve-from'
import { dirname, join, relative } from 'path'
export interface MissingDependency {
file: string
/**
* The package's package.json (e.g. require(`${pkg}/package.json`)) MUST resolve.
* If `exportsRestrict` is false, `${file}` MUST also resolve.
*/
pkg: string
/**... | s')`.
*
* If false, will resolve `file` relative to the baseDir.
* ForFor example, `{ file: '@types/react/index.d.ts', pkg: '@types/react', exportsRestrict: true }`
* will try to resolve `@types/react/index.d.ts` directly.
*/
exportsRestri | ex.d.ts', pkg: '@types/react', exportsRestrict: true }`
* will try to resolve '@types/react/package.json' first and then assume `@types/react/index.d.ts`
* resolves to `path.join(dirname(resolvedPackageJsonPath), 'index.d.t | {
"filepath": "packages/next/src/lib/has-necessary-dependencies.ts",
"language": "typescript",
"file_size": 2300,
"cut_index": 563,
"middle_length": 229
} |
pe { MissingDependency } from './has-necessary-dependencies'
import { getPkgManager } from './helpers/get-pkg-manager'
import { install } from './helpers/install'
import { getOnline } from './helpers/get-online'
export type Dependencies = {
resolved: Map<string, string>
}
export async function installDependencies(
... | ndencies' : 'dependencies'
} (${packageManager}):`
)
for (const dep of deps) {
console.log(`- ${cyan(dep.pkg)}`)
}
console.log()
await install(
path.resolve(baseDir),
deps.map((dep: MissingDependency) => dep.pkg | ole.log(
`Installing ${
dev ? 'devDepe | {
"filepath": "packages/next/src/lib/install-dependencies.ts",
"language": "typescript",
"file_size": 980,
"cut_index": 582,
"middle_length": 52
} |
= await loadCustomRoutes({})
expect(customRoutes.rewrites.beforeFiles).toEqual([])
expect(customRoutes.rewrites.afterFiles).toEqual([])
expect(customRoutes.rewrites.fallback).toEqual([])
})
it('array rewrites should be added to afterFiles', async () => {
const customRoutes = await loadC... | back).toEqual([])
})
it('rewrites should be preserved correctly', async () => {
const customRoutes = await loadCustomRoutes({
async rewrites() {
return {
beforeFiles: [
{
source: '/ | ct(customRoutes.rewrites.beforeFiles).toEqual([])
expect(customRoutes.rewrites.afterFiles).toEqual([
{
destination: '/b',
source: '/a',
},
])
expect(customRoutes.rewrites.fall | {
"filepath": "packages/next/src/lib/load-custom-routes.test.ts",
"language": "typescript",
"file_size": 5465,
"cut_index": 716,
"middle_length": 229
} |
m 'node:crypto'
import { getCacheDirectory } from './helpers/get-cache-directory'
import * as Log from '../build/output/log'
import { execSync } from 'node:child_process'
const { WritableStream } =
require('node:stream/web') as typeof import('node:stream/web')
const MKCERT_VERSION = 'v1.4.4'
export interface SelfSi... | rt-${MKCERT_VERSION}-linux-${arch}`
}
throw new Error(`Unsupported platform: ${platform}`)
}
async function downloadBinary() {
try {
const binaryName = getBinaryName()
const cacheDirectory = getCacheDirectory('mkcert')
const binaryPath | h
if (platform === 'win32') {
return `mkcert-${MKCERT_VERSION}-windows-${arch}.exe`
}
if (platform === 'darwin') {
return `mkcert-${MKCERT_VERSION}-darwin-${arch}`
}
if (platform === 'linux') {
return `mkce | {
"filepath": "packages/next/src/lib/mkcert.ts",
"language": "typescript",
"file_size": 5034,
"cut_index": 614,
"middle_length": 229
} |
dUp from 'next/dist/compiled/find-up'
// @ts-ignore no-json types
import { optionalDependencies as nextOptionalDeps } from 'next/package.json'
import type { UnwrapPromise } from './coalesced-function'
import { isCI } from '../server/ci-info'
import { getRegistry } from './helpers/get-registry'
let registry: string | u... | ionData.cpu,
engines: versionData.engines,
tarball: versionData.dist.tarball,
integrity: versionData.dist.integrity,
}
}
/**
* Attempts to patch npm package-lock.json when it
* fails to include optionalDependencies for other platforms
* t | ed to fetch registry info for ${pkg}, got status ${res.status}`
)
}
const data = await res.json()
const versionData = data.versions[process.env.__NEXT_VERSION as string]
return {
os: versionData.os,
cpu: vers | {
"filepath": "packages/next/src/lib/patch-incorrect-lockfile.ts",
"language": "typescript",
"file_size": 5067,
"cut_index": 614,
"middle_length": 229
} |
sorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, ... | ILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | ission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTAB | {
"filepath": "packages/next/src/lib/pretty-bytes.ts",
"language": "typescript",
"file_size": 2629,
"cut_index": 563,
"middle_length": 229
} |
'../client/components/redirect-status-code'
export const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export function getRedirectStatus(route: {
statusCode?: number
permanent?: boolean
}): number {
return (
route.statusCode ||
(route.permanent
? RedirectStatusCode.PermanentRedirect
... | outeRegex(regex: string, restrictedPaths?: string[]) {
if (restrictedPaths) {
regex = regex.replace(
/\^/,
`^(?!${restrictedPaths
.map((path) => path.replace(/\//g, '\\/'))
.join('|')})`
)
}
regex = regex.replace(/ | en trailingSlash: true/false
export function modifyR | {
"filepath": "packages/next/src/lib/redirect-status.ts",
"language": "typescript",
"file_size": 891,
"cut_index": 547,
"middle_length": 52
} |
mport fs from 'fs'
import path from 'path'
export function findDir(dir: string, name: 'pages' | 'app'): string | null {
// prioritize ./${name} over ./src/${name}
let curDir = path.join(dir, name)
if (fs.existsSync(curDir)) return curDir
curDir = path.join(dir, 'src', name)
if (fs.existsSync(curDir)) return... | gesDir && appDir) {
const pagesParent = path.dirname(pagesDir)
const appParent = path.dirname(appDir)
if (pagesParent !== appParent) {
throw new Error(
'> `pages` and `app` directories should be under the same folder'
)
| onst appDir = findDir(dir, 'app') || undefined
if (appDir == null && pagesDir == null) {
throw new Error(
"> Couldn't find any `pages` or `app` directory. Please create one under the project root"
)
}
if (pa | {
"filepath": "packages/next/src/lib/find-pages-dir.ts",
"language": "typescript",
"file_size": 1048,
"cut_index": 513,
"middle_length": 229
} |
ferredValue',
'useEffect',
'useEffectEvent',
'useImperativeHandle',
'useInsertionEffect',
'useLayoutEffect',
'useReducer',
'useRef',
'useState',
'useSyncExternalStore',
'useTransition',
'experimental_useOptimistic',
'useOptimistic',
]
function setMessage(error: Error, message: string): void {
... | essage(error: Error): string {
const stack = error.stack
if (!stack) return ''
return stack.replace(/^[^\n]*\n/, '')
}
export function formatServerError(error: Error): void {
if (typeof error?.message !== 'string') return
if (
error.message | wrong
at funcName (/path/to/file.js:10:5)
at anotherFunc (/path/to/file.js:15:10)
* Output:
at funcName (/path/to/file.js:10:5)
at anotherFunc (/path/to/file.js:15:10)
*/
export function getStackWithoutErrorM | {
"filepath": "packages/next/src/lib/format-server-error.ts",
"language": "typescript",
"file_size": 2366,
"cut_index": 563,
"middle_length": 229
} |
from 'path'
import { warn } from '../build/output/log'
import { detectTypo } from './detect-typo'
import { realpathSync } from './realpath'
import { printAndExit } from '../server/lib/utils'
export function getProjectDir(dir?: string, exitOnEnoent = true) {
const resolvedDir = path.resolve(dir || '.')
try {
co... | ENT' && exitOnEnoent) {
if (typeof dir === 'string') {
const detectedTypo = detectTypo(dir, [
'build',
'dev',
'info',
'lint',
'start',
'telemetry',
'experimental-test',
| d for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`
)
}
return realDir
} catch (err: any) {
if (err.code === 'ENO | {
"filepath": "packages/next/src/lib/get-project-dir.ts",
"language": "typescript",
"file_size": 1330,
"cut_index": 524,
"middle_length": 229
} |
*/
internal?: boolean
/**
* @internal - used internally for routing
*/
regex?: string
}
export type Header = {
source: string
basePath?: false
locale?: false
headers: Array<{ key: string; value: string }>
has?: RouteHas[]
missing?: RouteHas[]
/**
* @internal - used internally for routing... | umber
permanent?: never
}
)
export type Middleware = {
source: string
locale?: false
has?: RouteHas[]
missing?: RouteHas[]
}
const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host'])
const namedGroupsRegex = /\(\?<([a-zA-Z] | : RouteHas[]
missing?: RouteHas[]
priority?: boolean
/**
* @internal - used internally for routing
*/
internal?: boolean
} & (
| {
statusCode?: never
permanent: boolean
}
| {
statusCode: n | {
"filepath": "packages/next/src/lib/load-custom-routes.ts",
"language": "typescript",
"file_size": 24017,
"cut_index": 1331,
"middle_length": 229
} |
o_station'
| 'profile'
| 'website'
| 'video.tv_show'
| 'video.other'
| 'video.movie'
| 'video.episode'
export type OpenGraph =
| OpenGraphWebsite
| OpenGraphArticle
| OpenGraphBook
| OpenGraphProfile
| OpenGraphMusicSong
| OpenGraphMusicAlbum
| OpenGraphMusicPlaylist
| OpenGraphRadioStation... | string | Array<string> | undefined
faxNumbers?: string | Array<string> | undefined
siteName?: string | undefined
locale?: Locale | undefined
alternateLocale?: Locale | Array<Locale> | undefined
images?: OGImage | Array<OGImage> | undefined
aud | ype OpenGraphMetadata = {
determiner?: 'a' | 'an' | 'the' | 'auto' | '' | undefined
title?: string | TemplateString | undefined
description?: string | undefined
emails?: string | Array<string> | undefined
phoneNumbers?: | {
"filepath": "packages/next/src/lib/metadata/types/opengraph-types.ts",
"language": "typescript",
"file_size": 8932,
"cut_index": 716,
"middle_length": 229
} |
adata, ResolvedMetadataWithURLs } from './metadata-interface'
export type FieldResolver<
Key extends keyof Data & keyof ResolvedData,
Data = Metadata,
ResolvedData = ResolvedMetadataWithURLs,
> = (T: Data[Key]) => ResolvedData[Key]
export type FieldResolverExtraArgs<
Key extends keyof Data & keyof ResolvedDat... | vedData,
ExtraArgs extends unknown[] = any[],
Data = Metadata,
ResolvedData = ResolvedMetadataWithURLs,
> = (T: Data[Key], ...args: ExtraArgs) => Promise<ResolvedData[Key]>
export type MetadataContext = {
trailingSlash: boolean
isStaticMetadataR | verExtraArgs<
Key extends keyof Data & keyof Resol | {
"filepath": "packages/next/src/lib/metadata/types/resolvers.ts",
"language": "typescript",
"file_size": 857,
"cut_index": 529,
"middle_length": 52
} |
const glob = promisify(globOriginal)
interface ResolvedBuildPaths {
appPaths: string[]
pagePaths: string[]
}
/**
* Escapes Next.js dynamic route bracket expressions so glob treats them as
* literal directory names rather than character classes.
*
* e.g., "app/blog/[slug]/** /page.tsx" → "app/blog/\[slug\]/**... | negation patterns prefixed with "!" to exclude paths.
* e.g., "app/**,!app/[lang]/page.js" includes all App Router paths except
* app/[lang]/page.js
*/
export async function resolveBuildPaths(
patterns: string[],
projectDir: string
): Promise<Resol | [^\]]+\]/g, (match) =>
match.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
)
}
/**
* Resolves glob patterns and explicit paths to actual file paths.
* Categorizes them into App Router and Pages Router paths.
*
* Supports | {
"filepath": "packages/next/src/lib/resolve-build-paths.ts",
"language": "typescript",
"file_size": 5257,
"cut_index": 716,
"middle_length": 229
} |
'../client/components/app-router-headers'
import {
extractInterceptionRouteInformation,
isInterceptionRouteAppPath,
} from '../shared/lib/router/utils/interception-routes'
import type { Rewrite } from './load-custom-routes'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
export function... |
const header = getNamedRouteRegex(interceptingRoute, {
prefixRouteKeys: true,
reference: destination.reference,
})
const source = getNamedRouteRegex(basePath + interceptedRoute, {
prefixRouteKeys: true,
| th(appPath)) {
const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(appPath)
const destination = getNamedRouteRegex(basePath + appPath, {
prefixRouteKeys: true,
}) | {
"filepath": "packages/next/src/lib/generate-interception-routes-rewrites.ts",
"language": "typescript",
"file_size": 1848,
"cut_index": 537,
"middle_length": 229
} |
lainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
export class SerializableError extends Error {
constructor(page: string, method: string, path: string, message: string) {
super(
path
? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}`
: `Error serial... | )}\`).`
)
}
function visit(visited: Map<any, string>, value: any, path: string) {
if (visited.has(value)) {
throw new SerializableError(
page,
method,
path,
`Circular references cannot be expressed in | lainObject(input)) {
throw new SerializableError(
page,
method,
'',
`Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${getObjectClassLabel(
input
| {
"filepath": "packages/next/src/lib/is-serializable-props.ts",
"language": "typescript",
"file_size": 3572,
"cut_index": 614,
"middle_length": 229
} |
saryDependencies,
} from './has-necessary-dependencies'
import semver from 'next/dist/compiled/semver'
import { CompileError } from './compile-error'
import * as log from '../build/output/log'
import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import type { TypeCheckResult } from './typescript/runT... | issingDependency = {
file: 'typescript/lib/typescript.js',
pkg: 'typescript',
exportsRestrict: true,
}
const requiredPackages: MissingDependency[] = [
typescriptPackage,
{
file: '@types/react/index.d.ts',
pkg: '@types/react',
exports | Dependencies } from './install-dependencies'
import { isCI } from '../server/ci-info'
import { missingDepsError } from './typescript/missingDependencyError'
import { resolveFrom } from './resolve-from'
const typescriptPackage: M | {
"filepath": "packages/next/src/lib/verify-typescript-setup.ts",
"language": "typescript",
"file_size": 9008,
"cut_index": 716,
"middle_length": 229
} |
t/dist/compiled/jest-worker', () => {
const WorkerMock = jest.fn().mockImplementation((_path, options) => {
latestForkEnv = options?.forkOptions?.env
return {
_workerPool: { _workers: [] },
getStdout: () => new PassThrough(),
getStderr: () => new PassThrough(),
end: jest.fn().mockResol... | criptor(target, property)
restoreDescriptors.push(() => {
if (descriptor) {
Object.defineProperty(target, property, descriptor)
} else {
delete (target as any)[property]
}
})
Object.defineProperty(target, property, {
confi | ring[],
}
const restoreDescriptors: Array<() => void> = []
const overrideBooleanDescriptor = (
target: NodeJS.WriteStream,
property: 'isTTY',
value: boolean | undefined
) => {
const descriptor = Object.getOwnPropertyDes | {
"filepath": "packages/next/src/lib/worker.test.ts",
"language": "typescript",
"file_size": 3372,
"cut_index": 614,
"middle_length": 229
} |
t path from 'path'
import fs from 'fs'
// get platform specific cache directory adapted from playwright's handling
// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
export function getCacheDirectory(fileDirectory: string, envPat... | systemCacheDirectory =
process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
} else {
/// Attempt to use generic tmp location for un-handled platform
if (!systemCacheDirectory) {
for (const dir of [
| nv.XDG_CACHE_HOME || path.join(os.homedir(), '.cache')
} else if (process.platform === 'darwin') {
systemCacheDirectory = path.join(os.homedir(), 'Library', 'Caches')
} else if (process.platform === 'win32') {
| {
"filepath": "packages/next/src/lib/helpers/get-cache-directory.ts",
"language": "typescript",
"file_size": 1893,
"cut_index": 537,
"middle_length": 229
} |
cSync } from 'child_process'
import { getPkgManager } from './get-pkg-manager'
import { getFormattedNodeOptionsWithoutInspect } from '../../server/lib/utils'
/**
* Returns the package registry using the user's package manager.
* The URL will have a trailing slash.
* @default https://registry.npmjs.org/
*/
export f... | 21#issuecomment-1499044345
// x-ref: https://github.com/npm/statusboard/issues/371#issue-920669998
const resolvedFlags = pkgManager === 'npm' ? '--no-workspaces' : ''
let registry = `https://registry.npmjs.org/`
try {
const output = execSync(
|
// add `--no-workspaces` flag to run under the context of the root project only.
// Safe for non-workspace projects as it's equivalent to default `--workspaces=false`.
// x-ref: https://github.com/vercel/next.js/issues/471 | {
"filepath": "packages/next/src/lib/helpers/get-registry.ts",
"language": "typescript",
"file_size": 1484,
"cut_index": 524,
"middle_length": 229
} |
cSync } from 'child_process'
function gitExec(args: string, cwd: string): string {
return execSync(`git ${args}`, {
cwd,
timeout: 2000,
stdio: ['ignore', 'pipe', 'ignore'],
})
.toString()
.trim()
}
/**
* Returns the current git branch name for the given working directory, or
* undefined if i... | non-zero in detached HEAD state
// (caught below and treated as unknown).
return gitExec('symbolic-ref --short HEAD', cwd)
} catch {
return undefined
}
}
/**
* Returns the current git commit SHA for the given working directory, or
* unde | if (process.env.VERCEL_GIT_COMMIT_REF) {
return process.env.VERCEL_GIT_COMMIT_REF
}
try {
// symbolic-ref --short HEAD: returns the branch name for regular branches,
// works on repos with no commits, and exits | {
"filepath": "packages/next/src/lib/helpers/git.ts",
"language": "typescript",
"file_size": 1335,
"cut_index": 524,
"middle_length": 229
} |
from 'next/dist/compiled/cross-spawn'
import type { PackageManager } from './get-pkg-manager'
interface InstallArgs {
/**
* Indicate whether to install packages using npm, pnpm, or yarn.
*/
packageManager: PackageManager
/**
* Indicate whether there is an active internet connection.
*/
isOnline: b... | t args: string[] = []
if (dependencies.length > 0) {
if (packageManager === 'yarn') {
args = ['add', '--exact']
if (devDependencies) args.push('--dev')
} else if (packageManager === 'pnpm') {
args = ['add', '--save-exact']
| *
* @returns A Promise that resolves once the installation is finished.
*/
export function install(
root: string,
dependencies: string[],
{ packageManager, isOnline, devDependencies }: InstallArgs
): Promise<void> {
le | {
"filepath": "packages/next/src/lib/helpers/install.ts",
"language": "typescript",
"file_size": 2247,
"cut_index": 563,
"middle_length": 229
} |
ormalizeMetadataRoute,
} from './get-metadata-route'
describe('fillStaticMetadataSegment', () => {
it('should preserve a statically known root favicon path', () => {
expect(fillStaticMetadataSegment('/', 'favicon.ico')).toBe('/favicon.ico')
})
it('should replace dynamic segments with placeholder segments', ... | e = normalizeMetadataRoute(
'/(post)/@feed/blog/twitter-image'
)
const suffix = normalizedRoute.match(/twitter-image(-[0-9a-z]{6})\/route$/)
expect(suffix).not.toBeNull()
expect(staticPath).toBe(`/blog/twitter-image${suffix?.[1]}.png | '/blog/-/icon.png'
)
})
it('should preserve grouped metadata suffixes', () => {
const staticPath = fillStaticMetadataSegment(
'/(post)/@feed/blog',
'twitter-image.png'
)
const normalizedRout | {
"filepath": "packages/next/src/lib/metadata/get-metadata-route.test.ts",
"language": "typescript",
"file_size": 3349,
"cut_index": 614,
"middle_length": 229
} |
om '../../shared/lib/router/utils/route-regex'
import { PARAMETER_PATTERN } from '../../shared/lib/router/utils/get-dynamic-param'
import { djb2Hash } from '../../shared/lib/hash'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { isDynamicRoute } from '../../shared/lib/router/utils'
im... | ge.tsx -> /opengraph-image-[0-9a-z]{6}
*
* Sitemap is an exception, it should not have a suffix.
* Each sitemap contains all the urls of sub routes, we don't have the case of duplicates `/(group)/sitemap.[ext]` and `/sitemap.[ext]` since they should be | from '../../shared/lib/segment'
/*
* If there's special convention like (...) or @ in the page path,
* Give it a unique hash suffix to avoid conflicts
*
* e.g.
* /opengraph-image -> /opengraph-image
* /(post)/opengraph-ima | {
"filepath": "packages/next/src/lib/metadata/get-metadata-route.ts",
"language": "typescript",
"file_size": 6836,
"cut_index": 716,
"middle_length": 229
} |
n this way we can let the metadata tags always render successfully,
// and the error will be caught by the error boundary and trigger fallbacks.
export function createMetadataComponents({
tree,
pathname,
parsedQuery,
metadataContext,
interpolatedParams,
errorType,
serveStreamingMetadata,
isRuntimePrefet... | data(
parsedQuery,
isRuntimePrefetchable
)
const pathnameForMetadata = createServerPathnameForMetadata(pathname)
async function Viewport() {
// Gate metadata to the correct render stage. If the page is not
// runtime-prefetchable, de | rveStreamingMetadata: boolean
isRuntimePrefetchable: boolean
}): {
Viewport: React.ComponentType
Metadata: React.ComponentType
MetadataOutlet: React.ComponentType
} {
const searchParams = createServerSearchParamsForMeta | {
"filepath": "packages/next/src/lib/metadata/metadata.tsx",
"language": "tsx",
"file_size": 53843,
"cut_index": 2151,
"middle_length": 229
} |
pp-dir-module'
import {
resolveAlternates,
resolveAppleWebApp,
resolveAppLinks,
resolveRobots,
resolveThemeColor,
resolveVerification,
resolveItunes,
resolveFacebook,
resolvePagination,
} from './resolvers/resolve-basics'
import { resolveIcons } from './resolvers/resolve-icons'
import { getTracer } fr... | lient-and-server-references'
import type {
UseCacheLayoutProps,
UseCachePageProps,
} from '../../server/use-cache/use-cache-wrapper'
import { createLazyResult } from '../../server/lib/lazy-result'
type StaticIcons = Pick<ResolvedIcons, 'icon' | 'apple | ./build/output/log'
import { createServerParamsForMetadata } from '../../server/request/params'
import type { MetadataBaseURL } from './resolvers/resolve-url'
import {
getUseCacheFunctionInfo,
isUseCacheFunction,
} from '../c | {
"filepath": "packages/next/src/lib/metadata/resolve-metadata.ts",
"language": "typescript",
"file_size": 39681,
"cut_index": 2151,
"middle_length": 229
} |
member exists.
// ref: https://developers.facebook.com/docs/applinks/metadata-reference
export type AppLinks = {
ios?: AppLinksApple | Array<AppLinksApple> | undefined
iphone?: AppLinksApple | Array<AppLinksApple> | undefined
ipad?: AppLinksApple | Array<AppLinksApple> | undefined
android?: AppLinksAndroid | ... | ipad?: Array<AppLinksApple> | undefined
android?: Array<AppLinksAndroid> | undefined
windows_phone?: Array<AppLinksWindows> | undefined
windows?: Array<AppLinksWindows> | undefined
windows_universal?: Array<AppLinksWindows> | undefined
web?: Arra | AppLinksWindows | Array<AppLinksWindows> | undefined
web?: AppLinksWeb | Array<AppLinksWeb> | undefined
}
export type ResolvedAppLinks = {
ios?: Array<AppLinksApple> | undefined
iphone?: Array<AppLinksApple> | undefined
| {
"filepath": "packages/next/src/lib/metadata/types/extra-types.ts",
"language": "typescript",
"file_size": 4439,
"cut_index": 614,
"middle_length": 229
} |
g'
| 'navigate-existing'
| 'navigate-new'
type File = {
name: string
accept: string | string[]
}
type Icon = {
src: string
type?: string | undefined
sizes?: string | undefined
purpose?: 'any' | 'maskable' | 'monochrome' | undefined
}
export type Manifest = {
background_color?: string | undefined
... | accept: {
[mimeType: string]: string[]
}
}[]
| undefined
icons?: Icon[] | undefined
id?: string | undefined
lang?: string | undefined
launch_handler?:
| {
client_mode: ClientModeEnum | ClientModeEnum[] | display_override?:
| (
| 'fullscreen'
| 'standalone'
| 'minimal-ui'
| 'browser'
| 'window-controls-overlay'
)[]
| undefined
file_handlers?:
| {
action: string
| {
"filepath": "packages/next/src/lib/metadata/types/manifest-types.ts",
"language": "typescript",
"file_size": 2927,
"cut_index": 563,
"middle_length": 229
} |
port type { CacheFs } from '../shared/lib/utils'
/**
* A task to be written.
*/
type Task = [
/**
* The directory to create.
*/
directory: string,
/**
* The promise to create the directory.
*/
mkdir: Promise<unknown>,
/**
* The promises to write the files that are dependent on the director... | /**
* The file system methods to use.
*/
private readonly fs: Pick<CacheFs, 'mkdir' | 'writeFile'>
) {}
/**
* Finds or creates a task for a directory.
*
* @param directory - The directory to find or create a task for.
* @retu | r their containing directory
* is created, and that the directory will only be created once.
*/
export class MultiFileWriter {
/**
* The tasks to be written.
*/
private readonly tasks: Task[] = []
constructor(
| {
"filepath": "packages/next/src/lib/multi-file-writer.ts",
"language": "typescript",
"file_size": 2799,
"cut_index": 563,
"middle_length": 229
} |
eadDirOptions = {
/**
* Filter to ignore files with absolute pathnames, false to ignore.
*/
pathnameFilter?: Filter
/**
* Filter to ignore files and directories with absolute pathnames, false to
* ignore.
*/
ignoreFilter?: Filter
/**
* Filter to ignore files and directories with the pathna... | e behavior of the recursive read
* @returns the list of pathnames
*/
export async function recursiveReadDir(
rootDirectory: string,
options: RecursiveReadDirOptions = {}
): Promise<string[]> {
// Grab our options.
const {
pathnameFilter,
| e pathnames, true by default.
*/
relativePathnames?: boolean
}
/**
* Recursively reads a directory and returns the list of pathnames.
*
* @param rootDirectory the directory to read
* @param options options to control th | {
"filepath": "packages/next/src/lib/recursive-readdir.ts",
"language": "typescript",
"file_size": 5434,
"cut_index": 716,
"middle_length": 229
} |
l'
import globOriginal from 'next/dist/compiled/glob'
import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared'
import { getNextConfigEnv, getStaticEnv } from './static-env'
const glob = promisify(globOriginal)
export async function inlineStaticEnv({
dist... | ap}', {
cwd: clientDir,
})
const manifestChunks = await glob('*.{js,json,js.map}', {
cwd: distDir,
})
const inlineSema = new Sema(8)
const nextConfigEnvKeys = Object.keys(nextConfigEnv).map((item) =>
item.split('process.env.').pop()
| serverDir = path.join(distDir, 'server')
const serverChunks = await glob('**/*.{js,json,js.map}', {
cwd: serverDir,
})
const clientDir = path.join(distDir, 'static')
const clientChunks = await glob('**/*.{js,json,js.m | {
"filepath": "packages/next/src/lib/inline-static-env.ts",
"language": "typescript",
"file_size": 3634,
"cut_index": 614,
"middle_length": 229
} |
t type { LRUCache } from '../server/lib/lru-cache'
export function withPromiseCache<K, V>(
cache: LRUCache<Promise<V>>,
fn: (value: K) => Promise<V>
): (value: K) => Promise<V>
export function withPromiseCache<T extends any[], K, V>(
cache: LRUCache<Promise<V>>,
fn: (...values: T) => Promise<V>,
getKey: (...... | (...values: T) => Promise<V> {
return (...values: T) => {
const key = getKey ? getKey(...values) : values[0]
let p = cache.get(key)
if (!p) {
p = fn(...values)
p.catch(() => cache.remove(key))
cache.set(key, p)
}
ret | s: T) => K
): | {
"filepath": "packages/next/src/lib/with-promise-cache.ts",
"language": "typescript",
"file_size": 799,
"cut_index": 517,
"middle_length": 14
} |
RESTARTED = Symbol('restarted')
const cleanupWorkers = (worker: JestWorker) => {
for (const curWorker of ((worker as any)._workerPool?._workers || []) as {
_child?: ChildProcess
}[]) {
curWorker._child?.kill('SIGINT')
}
}
export function getNextBuildDebuggerPortOffset(_: {
kind: 'export-page'
}): num... | ocessEnv> | undefined
})
| undefined
/**
* `-1` if not inspectable
*/
debuggerPortOffset: number
enableSourceMaps?: boolean
/**
* True if `--max-old-space-size` should not be forwarded to the w | id) | undefined
constructor(
workerPath: string,
options: Omit<FarmOptions, 'forkOptions'> & {
forkOptions?:
| (Omit<NonNullable<FarmOptions['forkOptions']>, 'env'> & {
env?: Partial<NodeJS.Pr | {
"filepath": "packages/next/src/lib/worker.ts",
"language": "typescript",
"file_size": 10341,
"cut_index": 921,
"middle_length": 229
} |
{
ResolvedMetadata,
ResolvedViewport,
} from './types/metadata-interface'
export function createDefaultViewport(): ResolvedViewport {
return {
// name=viewport
width: 'device-width',
initialScale: 1,
// visual metadata
themeColor: null,
colorScheme: null,
}
}
export function createDefa... | lternates: {
canonical: null,
languages: null,
media: null,
types: null,
},
icons: null,
openGraph: null,
twitter: null,
verification: {},
appleWebApp: null,
formatDetection: null,
itunes: null,
f | title: null,
description: null,
applicationName: null,
authors: null,
generator: null,
keywords: null,
referrer: null,
creator: null,
publisher: null,
robots: null,
manifest: null,
a | {
"filepath": "packages/next/src/lib/metadata/default-metadata.tsx",
"language": "tsx",
"file_size": 1276,
"cut_index": 524,
"middle_length": 229
} |
ex(
...args: Parameters<typeof getExtensionRegexString>
) {
return new RegExp(`^${getExtensionRegexString(...args)}$`)
}
describe('with dynamic extensions', () => {
it('should return the correct regex', () => {
const regex = createExtensionMatchRegex(['png', 'jpg'], ['tsx', 'ts'])
expect(... | egex.test('.png')).toBe(true)
expect(regex.test('.jpg')).toBe(true)
expect(regex.test('.webp')).toBe(false)
expect(regex.test('.ts')).toBe(false)
expect(regex.test('.tsx')).toBe(false)
expect(regex.test('.js')).toBe(false)
| ts')).toBe(true)
expect(regex.test('.js')).toBe(false)
})
it('should not handle js extensions with empty dynamic extensions', () => {
const regex = createExtensionMatchRegex(['png', 'jpg'], [])
expect(r | {
"filepath": "packages/next/src/lib/metadata/is-metadata-route.test.ts",
"language": "typescript",
"file_size": 5873,
"cut_index": 716,
"middle_length": 229
} |
| 'bg'
| 'bh'
| 'bi'
| 'bm'
| 'bn'
| 'bo'
| 'br'
| 'bs'
| 'ca'
| 'ce'
| 'ch'
| 'co'
| 'cr'
| 'cs'
| 'cu'
| 'cv'
| 'cy'
| 'da'
| 'de'
| 'dv'
| 'dz'
| 'ee'
| 'el'
| 'en'
| 'eo'
| 'es'
| 'et'
| 'eu'
| 'fa'
| 'ff'
| 'fi'
| 'fj'
| 'fo'
| 'fr'
| 'fy'
| 'g... | 'lo'
| 'lt'
| 'lu'
| 'lv'
| 'mg'
| 'mh'
| 'mi'
| 'mk'
| 'ml'
| 'mn'
| 'mr'
| 'ms'
| 'mt'
| 'my'
| 'na'
| 'nb'
| 'nd'
| 'ne'
| 'ng'
| 'nl'
| 'nn'
| 'no'
| 'nr'
| 'nv'
| 'ny'
| 'oc'
| 'oj'
| 'om'
| 'or' | | 'is'
| 'it'
| 'iu'
| 'ja'
| 'jv'
| 'ka'
| 'kg'
| 'ki'
| 'kj'
| 'kk'
| 'kl'
| 'km'
| 'kn'
| 'ko'
| 'kr'
| 'ks'
| 'ku'
| 'kv'
| 'kw'
| 'ky'
| 'la'
| 'lb'
| 'lg'
| 'li'
| 'ln'
| | {
"filepath": "packages/next/src/lib/metadata/types/alternative-urls-types.ts",
"language": "typescript",
"file_size": 5951,
"cut_index": 716,
"middle_length": 229
} |
reen'?: never | undefined
/**
* Obsolete since iOS 7.
* @see https://web.dev/apple-touch-icon/
* @deprecated Use icons.apple instead
*/
'apple-touch-icon-precomposed'?: never | undefined
}
export type TemplateString =
| DefaultTemplateString
| AbsoluteTemplateString
| AbsoluteString
export type ... | hould
// use '"unsafe-URL" as ReferrerEnum'
export type ReferrerEnum =
| 'no-referrer'
| 'origin'
| 'no-referrer-when-downgrade'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
export type C | : string
}
export type Author = {
// renders as <link rel="author"...
url?: string | URL | undefined
// renders as <meta name="author"...
name?: string | undefined
}
// does not include "unsafe-URL". to use this users s | {
"filepath": "packages/next/src/lib/metadata/types/metadata-types.ts",
"language": "typescript",
"file_size": 5097,
"cut_index": 716,
"middle_length": 229
} |
n to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCL... | lexeyraspopov/picocolors/blob/b6261487e7b81aaab2440e397a356732cad9e342/picocolors.js#L1
const { env, stdout } = globalThis?.process ?? {}
const enabled =
env &&
!env.NO_COLOR &&
(env.FORCE_COLOR || (stdout?.isTTY && !env.CI && env.TERM !== 'dumb')) | ER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// https://github.com/a | {
"filepath": "packages/next/src/lib/picocolors.ts",
"language": "typescript",
"file_size": 3302,
"cut_index": 614,
"middle_length": 229
} |
import fs from 'fs'
import path from 'path'
import { execSync } from 'child_process'
export type PackageManager = 'npm' | 'pnpm' | 'yarn'
export function getPkgManager(baseDir: string): PackageManager {
try {
for (const { lockFile, packageManager } of [
{ lockFile: 'yarn.lock', packageManager: 'yarn' },
... | startsWith('pnpm')) {
return 'pnpm'
}
}
try {
execSync('yarn --version', { stdio: 'ignore' })
return 'yarn'
} catch {
execSync('pnpm --version', { stdio: 'ignore' })
return 'pnpm'
}
} catch {
retu | return packageManager as PackageManager
}
}
const userAgent = process.env.npm_config_user_agent
if (userAgent) {
if (userAgent.startsWith('yarn')) {
return 'yarn'
} else if (userAgent. | {
"filepath": "packages/next/src/lib/helpers/get-pkg-manager.ts",
"language": "typescript",
"file_size": 1012,
"cut_index": 512,
"middle_length": 229
} |
outer/utils/app-paths'
import { isAppRouteRoute } from '../is-app-route-route'
export const STATIC_METADATA_IMAGES = {
icon: {
filename: 'icon',
extensions: ['ico', 'jpg', 'jpeg', 'png', 'svg'],
},
apple: {
filename: 'apple-icon',
extensions: ['jpg', 'jpeg', 'png'],
},
favicon: {
filename... | t const DEFAULT_METADATA_ROUTE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx']
// Match the file extension with the dynamic multi-routes extensions
// e.g. ([xml, js], null) -> can match `/sitemap.xml/route`, `sitemap.js/route`
// e.g. ([png], [ts]) -> can match | xtensions: ['jpg', 'jpeg', 'png', 'gif'],
},
} as const
// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc.
// TODO-METADATA: support more metadata routes with more extensions
expor | {
"filepath": "packages/next/src/lib/metadata/is-metadata-route.ts",
"language": "typescript",
"file_size": 8651,
"cut_index": 716,
"middle_length": 229
} |
inks,
ResolvedFacebook,
ResolvedPinterest,
ViewportLayout,
} from './extra-types'
import type {
DeprecatedMetadataFields,
AbsoluteTemplateString,
Author,
ColorSchemeEnum,
Icon,
Icons,
IconURL,
ReferrerEnum,
ResolvedIcons,
ResolvedVerification,
Robots,
ResolvedRobots,
TemplateString,
Ve... | metadata fields available in Next.js including title, description,
* icons, openGraph, twitter, and more. Fields such as `metadataBase` help in composing absolute URLs
* from relative ones. The `title` field supports both simple strings and a template ob | engraph-types'
import type { ResolvedTwitterMetadata, Twitter } from './twitter-types'
/**
* Metadata interface to describe all the metadata fields that can be set in a document.
*
* @remarks
* This interface covers all the | {
"filepath": "packages/next/src/lib/metadata/types/metadata-interface.ts",
"language": "typescript",
"file_size": 22072,
"cut_index": 1331,
"middle_length": 229
} |
led/commander'
import { bold } from '../lib/picocolors'
// Copy-pasted from Commander's Help class -> formatHelp().
// TL;DR, we're overriding the built-in help to add a few niceties.
// Link: https://github.com/tj/commander.js/blob/master/lib/help.js
const formatCliHelpOutput = (cmd: Command, helper: Help) => {
con... | aratorWidth
)}${description}`
return helper.wrap(
fullText,
helpWidth - itemIndentWidth,
termWidth + itemSeparatorWidth
)
}
return term
}
function formatList(textArray: string[]) {
return textArr | rmatItem(term: string, description: string) {
let value = term
if (description) {
if (term === 'directory') {
value = `[${term}]`
}
const fullText = `${value.padEnd(
termWidth + itemSep | {
"filepath": "packages/next/src/lib/format-cli-help-output.ts",
"language": "typescript",
"file_size": 2447,
"cut_index": 563,
"middle_length": 229
} |
ports: Viewport[]) {
// skip the first two arguments (metadata and static metadata)
return originAccumulateViewport(viewportExports.map((item) => item))
}
function mapUrlsToStrings(obj: any) {
if (typeof obj === 'object') {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] in... | nc metadata', async () => {
const generateMetadata = () => Promise.resolve({ description: 'child' })
const metadataItems: MetadataItems = [
[{ description: 'parent' }, null],
[
Object.assign(generateMetadata, { $$origi | ively process nested objects
obj[key] = mapUrlsToStrings(obj[key])
}
}
}
}
return obj
}
describe('accumulateMetadata', () => {
describe('typing', () => {
it('should support both sync and asy | {
"filepath": "packages/next/src/lib/metadata/resolve-metadata.test.ts",
"language": "typescript",
"file_size": 23789,
"cut_index": 1331,
"middle_length": 229
} |
atwg.org/#port-blocking */
export const KNOWN_RESERVED_PORTS = {
1: 'tcpmux',
7: 'echo',
9: 'discard',
11: 'systat',
13: 'daytime',
15: 'netstat',
17: 'qotd',
19: 'chargen',
20: 'ftp-data',
21: 'ftp',
22: 'ssh',
23: 'telnet',
25: 'smtp',
37: 'time',
42: 'name',
43: 'nicname',
53: 'doma... | 'submissions',
512: 'exec',
513: 'login',
514: 'shell',
515: 'printer',
526: 'tempo',
530: 'courier',
531: 'chat',
532: 'netnews',
540: 'uucp',
548: 'afp',
554: 'rtsp',
556: 'remotefs',
563: 'nntps',
587: 'submission',
601: 's | unrpc',
113: 'auth',
115: 'sftp',
117: 'uucp-path',
119: 'nntp',
123: 'ntp',
135: 'epmap',
137: 'netbios-ns',
139: 'netbios-ssn',
143: 'imap',
161: 'snmp',
179: 'bgp',
389: 'ldap',
427: 'svrloc',
465: | {
"filepath": "packages/next/src/lib/helpers/get-reserved-port.ts",
"language": "typescript",
"file_size": 1827,
"cut_index": 537,
"middle_length": 229
} |
describe('resolveTitle', () => {
it('should resolve nullable template as empty string title', () => {
expect(resolveTitle('', null)).toEqual({ absolute: '', template: null })
expect(resolveTitle(null, null)).toEqual({ absolute: '', template: null })
})
it('should resolve title with template', () => {
... | absolute' }, 'dash %s')
).toEqual({ absolute: 'dash title', template: '%s | absolute' })
expect(
resolveTitle({ default: '', template: '%s | absolute' }, 'fake template')
).toEqual({ absolute: 'fake template', template: '%s | absolute' }) | resolveTitle({ default: 'title', template: '%s | | {
"filepath": "packages/next/src/lib/metadata/resolvers/resolve-title.test.ts",
"language": "typescript",
"file_size": 876,
"cut_index": 559,
"middle_length": 52
} |
Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif... | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | {
"filepath": "packages/next/src/shared/lib/dset.js",
"language": "javascript",
"file_size": 1752,
"cut_index": 537,
"middle_length": 229
} |
eclare type LoaderComponent<P = {}> = Promise<
React.ComponentType<P> | ComponentModule<P>
>
export declare type Loader<P = {}> =
| (() => LoaderComponent<P>)
| LoaderComponent<P>
export type LoaderMap = { [module: string]: () => Loader<any> }
export type LoadableGeneratedOptions = {
webpack?(): any
module... | d to a module.
function convertModule<P>(mod: React.ComponentType<P> | ComponentModule<P>) {
return { default: (mod as ComponentModule<P>)?.default || mod }
}
export type DynamicOptions<P = {}> = LoadableGeneratedOptions & {
loading?: (loadingProps: D | r to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader
// Client component reference proxy need to be converte | {
"filepath": "packages/next/src/shared/lib/dynamic.tsx",
"language": "tsx",
"file_size": 5136,
"cut_index": 716,
"middle_length": 229
} |
FNV_PRIMES and FNV_OFFSETS from
// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param
const FNV_PRIMES = {
32: BigInt(16_777_619),
64: BigInt(1_099_511_628_211),
128: BigInt(309_485_009_821_345_068_724_781_371),
256: BigInt(
374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211
... | 720_260_389_217_684_476_157_468_082_573
),
} as const
const FNV_OFFSETS = {
32: BigInt(2_166_136_261),
64: BigInt(14_695_981_039_346_656_037),
128: BigInt(144_066_263_297_769_815_596_495_629_667_062_367_629),
256: BigInt(
100_029_257_958_052 | _456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_ | {
"filepath": "packages/next/src/shared/lib/fnv1a.ts",
"language": "typescript",
"file_size": 2708,
"cut_index": 563,
"middle_length": 229
} |
ons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMI... | ile is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk and CRA-specific logic
const friendlySyntaxErrorLabel = 'Synta | BILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import stripAnsi from 'next/dist/compiled/strip-ansi'
// This f | {
"filepath": "packages/next/src/shared/lib/format-webpack-messages.ts",
"language": "typescript",
"file_size": 9197,
"cut_index": 921,
"middle_length": 229
} |
om './get-hostname'
describe('getHostname', () => {
describe('from URL', () => {
it.each([
{ url: 'http://example.com', hostname: 'example.com' },
{ url: 'http://example.com/', hostname: 'example.com' },
{ url: 'http://example.com:3000', hostname: 'example.com' },
{ url: 'https://example.... | ://127.0.0.1/', hostname: '127.0.0.1' },
{ url: 'http://127.0.0.1:3000', hostname: '127.0.0.1' },
{ url: 'http://8.8.8.8', hostname: '8.8.8.8' },
{ url: 'http://8.8.8.8/', hostname: '8.8.8.8' },
{ url: 'http://8.8.8.8:3000', hostnam | ost', hostname: 'localhost' },
{ url: 'http://localhost/', hostname: 'localhost' },
{ url: 'http://localhost:3000', hostname: 'localhost' },
{ url: 'http://127.0.0.1', hostname: '127.0.0.1' },
{ url: 'http | {
"filepath": "packages/next/src/shared/lib/get-hostname.test.ts",
"language": "typescript",
"file_size": 1892,
"cut_index": 537,
"middle_length": 229
} |
port type { OutgoingHttpHeaders } from 'http'
/**
* Takes an object with a hostname property (like a parsed URL) and some
* headers that may contain Host and returns the preferred hostname.
* @param parsed An object containing a hostname property.
* @param headers A dictionary with headers containing a `host`.
*/... | // hostname.
let hostname: string
if (headers?.host && !Array.isArray(headers.host)) {
hostname = headers.host.toString().split(':', 1)[0]
} else if (parsed.hostname) {
hostname = parsed.hostname
} else return
return hostname.toLowerCase | the parsed
| {
"filepath": "packages/next/src/shared/lib/get-hostname.ts",
"language": "typescript",
"file_size": 789,
"cut_index": 514,
"middle_length": 14
} |
: string
width?: number | `${number}`
height?: number | `${number}`
fill?: boolean
loader?: ImageLoader
quality?: number | `${number}`
preload?: boolean
/**
* @deprecated Use `preload` prop instead.
* See https://nextjs.org/docs/app/api-reference/components/image#preload
*/
priority?: boolean
... | xtjs.org/docs/api-reference/next/legacy/image
*/
layout?: string
/**
* @deprecated Use `style` prop instead.
*/
objectFit?: string
/**
* @deprecated Use `style` prop instead.
*/
objectPosition?: string
/**
* @deprecated This p | xtjs.org/docs/app/api-reference/components/image#onload
*/
onLoadingComplete?: OnLoadingComplete
/**
* @deprecated Use `fill` prop instead of `layout="fill"` or change import to `next/legacy/image`.
* @see https://ne | {
"filepath": "packages/next/src/shared/lib/get-img-props.ts",
"language": "typescript",
"file_size": 24983,
"cut_index": 1331,
"middle_length": 229
} |
port { warnOnce } from '../../build/output/log'
export function getRspackCore() {
warnRspack()
try {
// eslint-disable-next-line @next/internal/typechecked-require
return require('next-rspack/rspack-core')
} catch (e) {
if (e instanceof Error && 'code' in e && e.code === 'MODULE_NOT_FOUND') {
t... | xt-rspack\` is currently experimental. It's not an official Next.js plugin, and is supported by the Rspack team in partnership with Next.js. Help improve Next.js and Rspack by providing feedback at https://github.com/vercel/next.js/discussions/77800`
)
} | XT_TEST_MODE) {
return
}
warnOnce(
`\`ne | {
"filepath": "packages/next/src/shared/lib/get-rspack.ts",
"language": "typescript",
"file_size": 823,
"cut_index": 514,
"middle_length": 52
} |
.yorku.ca/~oz/hash.html
// More specifically, 32-bit hash via djbxor
// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765)
// This is due to number type differences between rust for turbopack to js number types,
// where rust does not have easy way to repreesn... | jb2Hash(str: string) {
let hash = 5381
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = ((hash << 5) + hash + char) & 0xffffffff
}
return hash >>> 0
}
export function hexHash(str: string) {
return djb2Hash(str | terminstic output from 32bit hash.
export function d | {
"filepath": "packages/next/src/shared/lib/hash.ts",
"language": "typescript",
"file_size": 866,
"cut_index": 529,
"middle_length": 52
} |
utils/warn-once'
export function defaultHead(): JSX.Element[] {
const head = [
<meta charSet="utf-8" key="charset" />,
<meta name="viewport" content="width=device-width" key="viewport" />,
]
return head
}
function onlyReactElement(
list: Array<React.ReactElement<any>>,
child: React.ReactElement | nu... | n ReactPortal[]
React.Children.toArray(child.props.children).reduce(
// @ts-expect-error @types/react does not remove fragments but this could also return ReactPortal[]
(
fragmentList: Array<React.ReactElement<any>>,
| ld === 'number') {
return list
}
// Adds support for React.Fragment
if (child.type === React.Fragment) {
return list.concat(
// @ts-expect-error @types/react does not remove fragments but this could also retur | {
"filepath": "packages/next/src/shared/lib/head.tsx",
"language": "tsx",
"file_size": 5199,
"cut_index": 716,
"middle_length": 229
} |
eateContext } from 'react'
import type { Params } from '../../server/request/params'
import { ReadonlyURLSearchParams } from '../../client/components/readonly-url-search-params'
export const SearchParamsContext = createContext<URLSearchParams | null>(null)
export const PathnameContext = createContext<string | null>(nu... | romise<ReadonlyURLSearchParams>
params: InstrumentedPromise<Params>
// Layout segment hooks (updated at each layout boundary)
selectedLayoutSegmentPromises?: Map<
string,
InstrumentedPromise<string | null>
>
selectedLayoutSegmentsPromises | React DevTools
export type InstrumentedPromise<T> = Promise<T> & {
status: 'fulfilled'
value: T
displayName: string
}
export type NavigationPromises = {
pathname: InstrumentedPromise<string>
searchParams: InstrumentedP | {
"filepath": "packages/next/src/shared/lib/hooks-client-context.shared-runtime.ts",
"language": "typescript",
"file_size": 1941,
"cut_index": 537,
"middle_length": 229
} |
t-page-files'
import type { ServerRuntime } from '../../types'
import type { NEXT_DATA } from './utils'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { DeepReadonly } from './deep-readonly'
import { createContext, useContext, type JSX } from 'react'
export t... | m/vercel/next.js/pull/72959
*/
dynamicCssManifest: Set<string>
assetPrefix?: string
headTags: any[]
unstable_runtimeJS?: false
unstable_JsPreload?: false
assetQueryString: string
mutableAssetQueryString: string
/**
* Asset query strin | lean
}
buildManifest: BuildManifest
isDevelopment: boolean
deploymentId: string | undefined
dynamicImports: string[]
/**
* This manifest is only needed for Pages dir, Production, Webpack
* @see https://github.co | {
"filepath": "packages/next/src/shared/lib/html-context.shared-runtime.ts",
"language": "typescript",
"file_size": 2233,
"cut_index": 563,
"middle_length": 229
} |
s based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP: { [match: string]: string } = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
}
export con... | htmlEscapeJsonString(str: string): string {
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match])
}
export function htmlEscapeAttributeString(str: string): string {
return str.replace(
ATTRIBUTE_ESCAPE_REGEX,
(match) => ATTRIBUTE_E | TTRIBUTE_ESCAPE_REGEX = /[&"'<>]/g
export function | {
"filepath": "packages/next/src/shared/lib/htmlescape.ts",
"language": "typescript",
"file_size": 863,
"cut_index": 529,
"middle_length": 52
} |
red function, used on both client and server, to generate a SVG blur placeholder.
*/
export function getImageBlurSvg({
widthInt,
heightInt,
blurWidth,
blurHeight,
blurDataURL,
objectFit,
}: {
widthInt?: number
heightInt?: number
blurWidth?: number
blurHeight?: number
blurDataURL: string
objectF... | none'
return `%3Csvg xmlns='http://www.w3.org/2000/svg' ${viewBox}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3Cf | && svgHeight ? `viewBox='0 0 ${svgWidth} ${svgHeight}'` : ''
const preserveAspectRatio = viewBox
? 'none'
: objectFit === 'contain'
? 'xMidYMid'
: objectFit === 'cover'
? 'xMidYMid slice'
: ' | {
"filepath": "packages/next/src/shared/lib/image-blur-svg.ts",
"language": "typescript",
"file_size": 1359,
"cut_index": 524,
"middle_length": 229
} |
string
width: number
quality?: number
}
export type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig>
}
export type LocalPattern = {
/**
* Can be literal or wildcard.
* Single `*` matches a single path segment.
* Double `**` matches any number of path segments.
*/
... | Can be literal port such as `8080` or empty string
* meaning no port.
*/
port?: string
/**
* Can be literal or wildcard.
* Single `*` matches a single path segment.
* Double `**` matches any number of path segments.
*/
pathname?: | be `http` or `https`.
*/
protocol?: 'http' | 'https'
/**
* Can be literal or wildcard.
* Single `*` matches a single subdomain.
* Double `**` matches any number of subdomains.
*/
hostname: string
/**
* | {
"filepath": "packages/next/src/shared/lib/image-config.ts",
"language": "typescript",
"file_size": 5657,
"cut_index": 716,
"middle_length": 229
} |
{ ImageConfigComplete, ImageLoaderProps } from './image-config'
import type { ImageProps, ImageLoader, StaticImageData } from './get-img-props'
import { getImgProps } from './get-img-props'
import { Image } from '../../client/image-component'
// This is replaced by webpack alias
import defaultLoader from 'next/dist/s... | const { props } = getImgProps(imgProps, {
defaultLoader,
// This is replaced by webpack define plugin
imgConf: process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete,
})
// Normally we don't care about undefined props because we pass t | hem to another component, style, canvas, etc.
*
* Read more: [Next.js docs: `getImageProps`](https://nextjs.org/docs/app/api-reference/components/image#getimageprops)
*/
export function getImageProps(imgProps: ImageProps) {
| {
"filepath": "packages/next/src/shared/lib/image-external.tsx",
"language": "tsx",
"file_size": 1410,
"cut_index": 524,
"middle_length": 229
} |
/find-closest-quality'
import { getAssetToken, getDeploymentId } from './deployment-id'
function defaultLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sur... | // Extract dpl parameter early so validation uses the clean URL.
// If a immutable asset token should be used, it was already added as a query parameter and will
// be extracted and reused here.
let deploymentId = getDeploymentId()
if (src.startsW | ires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
}
| {
"filepath": "packages/next/src/shared/lib/image-loader.ts",
"language": "typescript",
"file_size": 4965,
"cut_index": 614,
"middle_length": 229
} |
pe InstantNavCookieData =
| { state: 'pending' }
| { state: 'mpa' }
| {
state: 'spa'
fromTree: FlightRouterState
toTree: FlightRouterState | null
}
export function parseInstantNavCookieValue(raw: string): InstantNavCookieData {
try {
const parsed = JSON.parse(raw)
if (Array.isArra... | l) {
const fromTree: FlightRouterState = rawState.from ?? ['', {}]
const toTree: FlightRouterState | null = rawState.to ?? null
return { state: 'spa', fromTree, toTree }
}
return { state: 'spa', fromTree: ['', {}], toTre | if (typeof rawState === 'object' && rawState !== nul | {
"filepath": "packages/next/src/shared/lib/instant-nav-cookie.ts",
"language": "typescript",
"file_size": 951,
"cut_index": 582,
"middle_length": 52
} |
App Router. */
export const reactVendoredRe =
/[\\/]next[\\/]dist[\\/]compiled[\\/](react|react-dom|react-server-dom-(webpack|turbopack)|scheduler)[\\/]/
/** React the user installed. Used by Pages Router, or user imports in App Router. */
export const reactNodeModulesRe =
/node_modules[\\/](react|react-dom|schedu... | turn false
// NOTE: native code has a version of the same logic in crates/next-napi-bindings/src/next_api/utils.rs
// keep them in sync.
return (
nextInternalsRe.test(file) ||
reactVendoredRe.test(file) ||
reactNodeModulesRe.test(file)
| on isInternal(file: string | null) {
if (!file) re | {
"filepath": "packages/next/src/shared/lib/is-internal.ts",
"language": "typescript",
"file_size": 872,
"cut_index": 559,
"middle_length": 52
} |
are and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the... | Y CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/
// https://github.com/jamiebuilds/react-loadable/blob/v5.5.0/s | T WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR AN | {
"filepath": "packages/next/src/shared/lib/loadable.shared-runtime.tsx",
"language": "tsx",
"file_size": 7431,
"cut_index": 716,
"middle_length": 229
} |
ntifier', () => {
// Basic decoding tests (ported from Rust)
test('decodes module evaluation', () => {
expect(decodeMagicIdentifier('__TURBOPACK__module__evaluation__')).toBe(
'module evaluation'
)
})
test('decodes path with slashes', () => {
expect(decodeMagicIdentifier('__TURBOPACK__Hello$2... | c identifiers globally', () => {
const text =
'Hello __TURBOPACK__Hello__World__ and __TURBOPACK__foo$2f$bar__'
const matches = text.match(MAGIC_IDENTIFIER_REGEX)
expect(matches).toHaveLength(2)
})
})
describe('deobfuscateModuleId', () | test('returns unchanged if not a magic identifier', () => {
expect(decodeMagicIdentifier('regular_identifier')).toBe(
'regular_identifier'
)
})
})
describe('MAGIC_IDENTIFIER_REGEX', () => {
test('matches magi | {
"filepath": "packages/next/src/shared/lib/magic-identifier.test.ts",
"language": "typescript",
"file_size": 5737,
"cut_index": 716,
"middle_length": 229
} |
valid hex: \`${hexStr}\``)
}
return String.fromCodePoint(num)
}
const enum Mode {
Text,
Underscore,
Hex,
LongHex,
}
const DECODE_REGEX = /^__TURBOPACK__([a-zA-Z0-9_$]+)__$/
export function decodeMagicIdentifier(identifier: string): string {
const matches = identifier.match(DECODE_REGEX)
if (!matches... | ore) {
if (char === '_') {
output += ' '
mode = Mode.Text
} else if (char === '$') {
output += '_'
mode = Mode.Hex
} else {
output += char
mode = Mode.Text
}
} else if (mode === Mo | ]
if (mode === Mode.Text) {
if (char === '_') {
mode = Mode.Underscore
} else if (char === '$') {
mode = Mode.Hex
} else {
output += char
}
} else if (mode === Mode.Undersc | {
"filepath": "packages/next/src/shared/lib/magic-identifier.ts",
"language": "typescript",
"file_size": 6014,
"cut_index": 716,
"middle_length": 229
} |
rt type { LocalPattern } from './image-config'
import { makeRe } from 'next/dist/compiled/picomatch'
// Modifying this function should also modify writeImagesManifest()
export function matchLocalPattern(pattern: LocalPattern, url: URL): boolean {
if (pattern.search !== undefined) {
if (pattern.search !== url.sea... | ry: string
): boolean {
if (!localPatterns) {
// if the user didn't define "localPatterns", we allow all local images
return true
}
const url = new URL(urlPathAndQuery, 'http://n')
return localPatterns.some((p) => matchLocalPattern(p, url)) | atterns: LocalPattern[] | undefined,
urlPathAndQue | {
"filepath": "packages/next/src/shared/lib/match-local-pattern.ts",
"language": "typescript",
"file_size": 827,
"cut_index": 516,
"middle_length": 52
} |
{ RemotePattern } from './image-config'
import { makeRe } from 'next/dist/compiled/picomatch'
// Modifying this function should also modify writeImagesManifest()
export function matchRemotePattern(
pattern: RemotePattern | URL,
url: URL
): boolean {
if (pattern.protocol !== undefined) {
if (pattern.protocol.... | }
}
if (pattern.search !== undefined) {
if (pattern.search !== url.search) {
return false
}
}
// Should be the same as writeImagesManifest()
if (!makeRe(pattern.pathname ?? '**', { dot: true }).test(url.pathname)) {
return fa | (pattern.hostname === undefined) {
throw new Error(
`Pattern should define hostname but found\n${JSON.stringify(pattern)}`
)
} else {
if (!makeRe(pattern.hostname).test(url.hostname)) {
return false
| {
"filepath": "packages/next/src/shared/lib/match-remote-pattern.ts",
"language": "typescript",
"file_size": 1291,
"cut_index": 524,
"middle_length": 229
} |
/jasonformat.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or... | A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE | l be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR | {
"filepath": "packages/next/src/shared/lib/mitt.ts",
"language": "typescript",
"file_size": 2042,
"cut_index": 563,
"middle_length": 229
} |
refix } from './normalized-asset-prefix'
describe('normalizedAssetPrefix', () => {
it('should return an empty string when assetPrefix is nullish', () => {
expect(normalizedAssetPrefix(undefined)).toBe('')
})
it('should return an empty string when assetPrefix is an empty string', () => {
expect(normalize... | should not remove the leading slash when assetPrefix has only one', () => {
expect(normalizedAssetPrefix('/path/to/asset')).toBe('/path/to/asset')
})
it('should add a leading slash when assetPrefix is missing one', () => {
expect(normalizedAss | string because it could be an unnecessary trailing slash
it('should remove leading slash(es) when assetPrefix has more than one', () => {
expect(normalizedAssetPrefix('///path/to/asset')).toBe('/path/to/asset')
})
it(' | {
"filepath": "packages/next/src/shared/lib/normalized-asset-prefix.test.ts",
"language": "typescript",
"file_size": 1633,
"cut_index": 537,
"middle_length": 229
} |
app-router-types'
export function getSegmentValue(segment: Segment) {
return Array.isArray(segment) ? segment[1] : segment
}
export function isGroupSegment(segment: string) {
// Use array[0] for performant purpose
return segment[0] === '(' && segment.endsWith(')')
}
export function isParallelRouteSegment(segme... | tringifiedQuery
: PAGE_SEGMENT_KEY
}
return segment
}
export function computeSelectedLayoutSegment(
segments: string[] | null,
parallelRouteKey: string
): string | null {
if (!segments || segments.length === 0) {
return null
}
// | | undefined>
) {
const isPageSegment = segment.includes(PAGE_SEGMENT_KEY)
if (isPageSegment) {
const stringifiedQuery = JSON.stringify(searchParams)
return stringifiedQuery !== '{}'
? PAGE_SEGMENT_KEY + '?' + s | {
"filepath": "packages/next/src/shared/lib/segment.ts",
"language": "typescript",
"file_size": 2588,
"cut_index": 563,
"middle_length": 229
} |
ct, { useContext } from 'react'
export type ServerInsertedHTMLHook = (callbacks: () => React.ReactNode) => void
// Use `React.createContext` to avoid errors from the RSC checks because
// it can't be imported directly in Server Components:
//
// import { createContext } from 'react'
//
// More info: https://github.... | e): void {
const addInsertedServerHTMLCallback = useContext(ServerInsertedHTMLContext)
// Should have no effects on client where there's no flush effects provider
if (addInsertedServerHTMLCallback) {
addInsertedServerHTMLCallback(callback)
}
}
| React.ReactNod | {
"filepath": "packages/next/src/shared/lib/server-inserted-html.shared-runtime.tsx",
"language": "tsx",
"file_size": 806,
"cut_index": 536,
"middle_length": 14
} |
erver-reference-info'
describe('extractInfoFromServerReferenceId', () => {
test('should parse id with typeBit 0, no args used, no restArgs', () => {
const id = '00' // 0b00000000
const expected: ServerReferenceInfo = {
type: 'server-action',
usedArgs: [false, false, false, false, false, false],
... | )).toEqual(expected)
})
test('should parse id with typeBit 0, argMask 0b101010, restArgs false', () => {
const id = '54' // 0b01010100
const expected: ServerReferenceInfo = {
type: 'server-action',
usedArgs: [true, false, true, fa | st id = 'ff' // 0b11111111
const expected: ServerReferenceInfo = {
type: 'use-cache',
usedArgs: [true, true, true, true, true, true],
hasRestArgs: true,
}
expect(extractInfoFromServerReferenceId(id | {
"filepath": "packages/next/src/shared/lib/server-reference-info.test.ts",
"language": "typescript",
"file_size": 4575,
"cut_index": 614,
"middle_length": 229
} |
ver-action' | 'use-cache'
usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]
hasRestArgs: boolean
}
/**
* Extracts info about the server reference for the given server reference ID by
* parsing the first byte of the hex-encoded ID.
*
* ```
* Bit positions: [7] [6] [5] [4] [3] [2] [1] [0]
... |
*
* @param id hex-encoded server reference ID
*/
export function extractInfoFromServerReferenceId(
id: string
): ServerReferenceInfo {
const infoByte = parseInt(id.slice(0, 2), 16)
const typeBit = (infoByte >> 7) & 0x1
const argMask = (infoByte | he `argMask` encodes whether the function uses the argument at the
* respective position.
*
* The `restArgs` bit indicates whether the function uses a rest parameter. It's
* also set to 1 if the function has more than 6 args. | {
"filepath": "packages/next/src/shared/lib/server-reference-info.ts",
"language": "typescript",
"file_size": 2247,
"cut_index": 563,
"middle_length": 229
} |
seEffect, useLayoutEffect, type JSX } from 'react'
type State = JSX.Element[] | undefined
export type SideEffectProps = {
reduceComponentsToState: (components: Array<React.ReactElement<any>>) => State
handleStateChange?: (state: State) => void
headManager: any
children: React.ReactNode
}
const isServer = typ... | om(headManager.mountedInstances as Set<React.ReactNode>).filter(
Boolean
)
) as React.ReactElement[]
headManager.updateHead(reduceComponentsToState(headElements))
}
}
if (isServer) {
headManager?.mountedInstances? | ct(props: SideEffectProps) {
const { headManager, reduceComponentsToState } = props
function emitChange() {
if (headManager && headManager.mountedInstances) {
const headElements = Children.toArray(
Array.fr | {
"filepath": "packages/next/src/shared/lib/side-effect.tsx",
"language": "tsx",
"file_size": 2262,
"cut_index": 563,
"middle_length": 229
} |
xport const DEFAULT_MAX_POSTPONED_STATE_SIZE: SizeLimit = '100 MB'
// 100MB in bytes. Not using the parseSizeLimit for performance as parseMaxPostponedStateSize is in the hot path for rendering.
const DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES = 104_857_600
function parseSizeLimit(size: SizeLimit): number | undefined {
... | StateSize config value, using the default if not provided.
*/
export function parseMaxPostponedStateSize(
size: SizeLimit | undefined
): number | undefined {
if (!size) {
return DEFAULT_MAX_POSTPONED_STATE_SIZE_BYTES
}
return parseSizeLimit(si | }
return bytes
}
/**
* Parses the maxPostponed | {
"filepath": "packages/next/src/shared/lib/size-limit.ts",
"language": "typescript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
mport type { Metadata } from '../types/metadata-interface'
import type { AbsoluteTemplateString } from '../types/metadata-types'
function resolveTitleTemplate(
template: string | null | undefined,
title: string
) {
return template ? template.replace(/%s/g, title) : title
}
export function resolveTitle(
title:... | plate, title.default)
}
if ('absolute' in title && title.absolute) {
resolved = title.absolute
}
}
if (title && typeof title !== 'string') {
return {
template,
absolute: resolved || '',
}
} else {
return { a | ? title.template
: null
if (typeof title === 'string') {
resolved = resolveTitleTemplate(stashedTemplate, title)
} else if (title) {
if ('default' in title) {
resolved = resolveTitleTemplate(stashedTem | {
"filepath": "packages/next/src/lib/metadata/resolvers/resolve-title.ts",
"language": "typescript",
"file_size": 1049,
"cut_index": 513,
"middle_length": 229
} |
"(.+)"' is not assignable to type 'RouteImpl<.+> \| UrlObject'\./
) ||
message.match(
/Type '"(.+)"' is not assignable to type 'UrlObject \| RouteImpl<.+>'\./
)
if (match) {
const [, href] = match
return `"${bold(
href
)}" is not an existing route. If it is inten... | s & /
)
) {
return `Invalid \`href\` property of \`Link\`: the route does not exist. If it is intentional, please type it explicitly with \`as Route\`.`
}
}
} else if (typeof message === 'string' && diagnostic.code === 282 | elatedInformation?.[0]?.messageText
if (
typeof relatedMessage === 'string' &&
relatedMessage.match(
/The expected type comes from property 'href' which is declared here on type 'IntrinsicAttribute | {
"filepath": "packages/next/src/lib/typescript/diagnosticFormatter.ts",
"language": "typescript",
"file_size": 13368,
"cut_index": 921,
"middle_length": 229
} |
stsSync, readFileSync } from 'fs'
import path from 'path'
import { recursiveReadDir } from '../recursive-readdir'
export type TypeScriptIntent = { firstTimeSetup: boolean }
export async function getTypeScriptIntent(
baseDir: string,
intentDirs: string[],
tsconfigPath: string
): Promise<TypeScriptIntent | false>... | }
}
// Next.js also offers a friendly setup mode that bootstraps a TypeScript
// project for the user when we detect TypeScript files. So, we need to check
// the `pages/` directory for a TypeScript file.
// Checking all directories is too slow, | existsSync(resolvedTsConfigPath)
if (hasTypeScriptConfiguration) {
const content = readFileSync(resolvedTsConfigPath, {
encoding: 'utf8',
}).trim()
return { firstTimeSetup: content === '' || content === '{}' | {
"filepath": "packages/next/src/lib/typescript/getTypeScriptIntent.ts",
"language": "typescript",
"file_size": 1440,
"cut_index": 524,
"middle_length": 229
} |
/writeConfigurationDefaults'
import { getDevTypesPath } from './type-paths'
import { CompileError } from '../compile-error'
import { warn } from '../../build/output/log'
export interface TypeCheckResult {
hasWarnings: boolean
warnings?: string[]
inputFilesCount: number
totalFilesCount: number
incremental: b... | port async function runTypeCheck(
typescript: typeof import('typescript'),
baseDir: string,
distDir: string,
tsConfigPath: string,
cacheDir?: string,
isAppDirEnabled?: boolean,
dirs?: TypeCheckDirs,
debugBuildPaths?: DebugBuildPaths
): Prom | of the debug build paths.
* Both filePath and debugPaths are resolved file paths from glob.
*/
function fileMatchesDebugPaths(
filePath: string,
debugPaths: string[]
): boolean {
return debugPaths.includes(filePath)
}
ex | {
"filepath": "packages/next/src/lib/typescript/runTypeCheck.ts",
"language": "typescript",
"file_size": 6595,
"cut_index": 716,
"middle_length": 229
} |
{ promises as fs } from 'fs'
export async function writeAppTypeDeclarations({
baseDir,
distDir,
imageImportsEnabled,
hasPagesDir,
hasAppDir,
strictRouteTypes,
typedRoutes,
}: {
baseDir: string
distDir: string
imageImportsEnabled: boolean
hasPagesDir: boolean
hasAppDir: boolean
strictRouteType... | \n', /* skip first so we can lf - 1 */ 1)
if (lf !== -1) {
if (currentContent[lf - 1] === '\r') {
eol = '\r\n'
} else {
eol = '\n'
}
}
} catch {}
/**
* "Triple-slash directives" used to create typings file | ol = os.EOL
let currentContent: string | undefined
try {
currentContent = await fs.readFile(appTypeDeclarations, 'utf8')
// If file already exists then preserve its line ending
const lf = currentContent.indexOf(' | {
"filepath": "packages/next/src/lib/typescript/writeAppTypeDeclarations.ts",
"language": "typescript",
"file_size": 3037,
"cut_index": 563,
"middle_length": 229
} |
tionsShape = {
[K in keyof CompilerOptions]:
| { suggested: any; reason?: string }
| {
parsedValue?: any
parsedValues?: Array<any>
value: any
reason: string
}
}
function getDesiredCompilerOptions(
typescriptVersion: string,
userTsConfig?: Record<string, any>
): Desir... | const moduleResolutionKindNodeNext = 'nodenext'
const moduleResolutionKindNode12 = 'node12'
const moduleResolutionKindNode = 'node'
const configuredModule =
typeof userTsConfig?.compilerOptions?.module === 'string'
? userTsConfig.compilerO |
const moduleKindNode16 = 'node16'
const moduleKindCommonJS = 'commonjs'
const moduleKindAMD = 'amd'
// ModuleResolutionKind
const moduleResolutionKindBundler = 'bundler'
const moduleResolutionKindNode16 = 'node16'
| {
"filepath": "packages/next/src/lib/typescript/writeConfigurationDefaults.ts",
"language": "typescript",
"file_size": 15408,
"cut_index": 921,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.