prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
inition } from '../../route-definitions/pages-route-definition'
import { RouteKind } from '../../route-kind'
import { DevPagesRouteMatcherProvider } from './dev-pages-route-matcher-provider'
import type { FileReader } from './helpers/file-reader/file-reader'
const normalizeSlashes = (p: string) => p.replace(/\//g, pat... | ect(reader.read).toHaveBeenCalledWith(dir)
})
describe('filename matching', () => {
it.each<{
files: ReadonlyArray<string>
route: PagesRouteDefinition
}>([
{
files: [normalizeSlashes(`${dir}/index.ts`)],
route | {
const reader: FileReader = { read: jest.fn(() => []) }
const matcher = new DevPagesRouteMatcherProvider(dir, extensions, reader)
const matchers = await matcher.matchers()
expect(matchers).toHaveLength(0)
exp | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/dev-pages-route-matcher-provider.test.ts",
"language": "typescript",
"file_size": 3012,
"cut_index": 563,
"middle_length": 229
} |
matchers/route-matcher'
import { CachedRouteMatcherProvider } from '../helpers/cached-route-matcher-provider'
import type { FileReader } from './helpers/file-reader/file-reader'
/**
* This will memoize the matchers when the file contents are the same.
*/
export abstract class FileCacheRouteMatcherProvider<
M exten... | (left.length !== right.length) return false
// Assuming the file traversal order is deterministic...
for (let i = 0; i < left.length; i++) {
if (left[i] !== right[i]) return false
}
return true
},
})
| d(dir),
compare: (left, right) => {
if | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/file-cache-route-matcher-provider.ts",
"language": "typescript",
"file_size": 872,
"cut_index": 559,
"middle_length": 52
} |
r } from './batched-file-reader'
import type { FileReader } from './file-reader'
describe('CachedFileReader', () => {
it('will only scan the filesystem a minimal amount of times', async () => {
const pages = ['1', '2', '3']
const app = ['4', '5', '6']
const reader: FileReader = {
read: jest.fn(asy... | hed.read('<root>/app'),
cached.read('<root>/app'),
])
expect(reader.read).toHaveBeenCalledTimes(2)
expect(results).toHaveLength(4)
expect(results[0]).toBe(pages)
expect(results[1]).toBe(pages)
expect(results[2]).toBe(app)
| throw new Error('unexpected')
}
}),
}
const cached = new BatchedFileReader(reader)
const results = await Promise.all([
cached.read('<root>/pages'),
cached.read('<root>/pages'),
cac | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/helpers/file-reader/batched-file-reader.test.ts",
"language": "typescript",
"file_size": 1926,
"cut_index": 537,
"middle_length": 229
} |
../shared/lib/invariant-error'
import { isThenable } from '../../shared/lib/is-thenable'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { withExecuteRevalidates } from '../revalidation-utils'
import { bindSnapshot } from '../app-render/async-local-storage'
import {
workUnitAsyncSt... | tUntil: RequestLifecycleOpts['waitUntil'] | undefined
private onClose: RequestLifecycleOpts['onClose']
private onTaskError: RequestLifecycleOpts['onAfterTaskError'] | undefined
private runCallbacksOnClosePromise: Promise<void> | undefined
private | ontextOpts = {
waitUntil: RequestLifecycleOpts['waitUntil'] | undefined
onClose: RequestLifecycleOpts['onClose']
onTaskError: RequestLifecycleOpts['onAfterTaskError'] | undefined
}
export class AfterContext {
private wai | {
"filepath": "packages/next/src/server/after/after-context.ts",
"language": "typescript",
"file_size": 5561,
"cut_index": 716,
"middle_length": 229
} |
t { isThenable } from '../../../shared/lib/is-thenable'
/**
* Tracks all in-flight async imports and chunk loads.
* Initialized lazily, because we don't want this to error in case it gets pulled into an edge runtime module.
*/
let _moduleLoadingSignal: CacheSignal | null
function getModuleLoadingSignal() {
if (!_... | returns a promise.
// if it's sync, there's nothing to track.
if (isThenable(exportsOrPromise)) {
// A client reference proxy might look like a promise, but we can only call `.then()` on it, not e.g. `.finally()`.
// Turn it into a real promis | gSignal = getModuleLoadingSignal()
moduleLoadingSignal.trackRead(promise)
}
export function trackPendingImport(exportsOrPromise: unknown) {
const moduleLoadingSignal = getModuleLoadingSignal()
// requiring an async module | {
"filepath": "packages/next/src/server/app-render/module-loading/track-module-loading.instance.ts",
"language": "typescript",
"file_size": 2188,
"cut_index": 563,
"middle_length": 229
} |
*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/
import * as React from 'react'
type Reference = object
type TaintableUniqueValue = string | bigint | ArrayBufferView
function notImplemented() {
throw new Error('Taint can only be used with the taint flag.')
... | notImplemented
export const taintUniqueValue: (
message: string | undefined,
lifetime: Reference,
value: TaintableUniqueValue
) => void = process.env.__NEXT_EXPERIMENTAL_REACT
? // @ts-ignore
React.experimental_taintUniqueValue
: notImplemen | tReference
: | {
"filepath": "packages/next/src/server/app-render/rsc/taint.ts",
"language": "typescript",
"file_size": 787,
"cut_index": 513,
"middle_length": 14
} |
tream'
import { SYMBOL_CLEARED_COOKIES } from '../api-utils'
import type { NextApiRequestCookies } from '../api-utils'
import { NEXT_REQUEST_META } from '../request-meta'
import type { RequestMeta } from '../request-meta'
import { BaseNextRequest, BaseNextResponse, type FetchMetric } from './index'
import type { Out... | }
constructor(private _req: Req) {
super(_req.method!.toUpperCase(), _req.url!, _req)
}
get originalRequest() {
// Need to mimic these changes to the original req object for places where we use it:
// render.tsx, api/ssg requests
th | tRequest extends BaseNextRequest<Readable> {
public headers = this._req.headers
public fetchMetrics: FetchMetric[] | undefined = this._req?.fetchMetrics;
[NEXT_REQUEST_META]: RequestMeta = this._req[NEXT_REQUEST_META] || { | {
"filepath": "packages/next/src/server/base-http/node.ts",
"language": "typescript",
"file_size": 4111,
"cut_index": 614,
"middle_length": 229
} |
NextResponse } from './web'
describe('WebNextResponse onClose', () => {
it('stream body', async () => {
const cb = jest.fn()
const ts = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk)
},
})
const webNextResponse = new WebNextResponse(ts)
webNext... | st text = await t
expect(cb).toHaveBeenCalledTimes(1)
expect(text).toBe('abcdef')
})
it('string body', async () => {
const cb = jest.fn()
const webNextResponse = new WebNextResponse(undefined).body('abcdef')
webNextResponse.onClose | t t = response.text()
const encoder = new TextEncoder()
const writer = ts.writable.getWriter()
await writer.write(encoder.encode('abc'))
await writer.write(encoder.encode('def'))
await writer.close()
con | {
"filepath": "packages/next/src/server/base-http/web.test.ts",
"language": "typescript",
"file_size": 1296,
"cut_index": 524,
"middle_length": 229
} |
ge-route'
import { APP_PATHS_MANIFEST } from '../../shared/lib/constants'
import { AppNormalizers } from '../normalizers/built/app'
import { RouteKind } from '../route-kind'
import { AppPageRouteMatcher } from '../route-matchers/app-page-route-matcher'
import type {
Manifest,
ManifestLoader,
} from './helpers/mani... | r)
}
protected async transform(
manifest: Manifest
): Promise<ReadonlyArray<AppPageRouteMatcher>> {
// This matcher only matches app pages.
const pages = Object.keys(manifest).filter((page) => isAppPageRoute(page))
// Collect all th | pPageRouteMatcher> {
private readonly normalizers: AppNormalizers
constructor(distDir: string, manifestLoader: ManifestLoader) {
super(APP_PATHS_MANIFEST, manifestLoader)
this.normalizers = new AppNormalizers(distDi | {
"filepath": "packages/next/src/server/route-matcher-providers/app-page-route-matcher-provider.ts",
"language": "typescript",
"file_size": 2040,
"cut_index": 563,
"middle_length": 229
} |
} from '../../lib/is-app-route-route'
import { APP_PATHS_MANIFEST } from '../../shared/lib/constants'
import { RouteKind } from '../route-kind'
import { AppRouteRouteMatcher } from '../route-matchers/app-route-route-matcher'
import type {
Manifest,
ManifestLoader,
} from './helpers/manifest-loaders/manifest-loader'... | ers = new AppNormalizers(distDir)
}
protected async transform(
manifest: Manifest
): Promise<ReadonlyArray<AppRouteRouteMatcher>> {
// This matcher only matches app routes.
const pages = Object.keys(manifest).filter((page) => isAppRouteR | anifestRouteMatcherProvider<AppRouteRouteMatcher> {
private readonly normalizers: AppNormalizers
constructor(distDir: string, manifestLoader: ManifestLoader) {
super(APP_PATHS_MANIFEST, manifestLoader)
this.normaliz | {
"filepath": "packages/next/src/server/route-matcher-providers/app-route-route-matcher-provider.ts",
"language": "typescript",
"file_size": 1579,
"cut_index": 537,
"middle_length": 229
} |
./../shared/lib/constants'
import type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'
import { RouteKind } from '../route-kind'
import type { ManifestLoader } from './helpers/manifest-loaders/manifest-loader'
import { PagesAPIRouteMatcherProvider } from './pages-api-route-matcher-pro... | each<{
manifest: Record<string, string>
route: PagesAPIRouteDefinition
}>([
{
manifest: { '/api/users/[id]': 'pages/api/users/[id].js' },
route: {
kind: RouteKind.PAGES_API,
pathname: '/api/users/[i | st provider = new PagesAPIRouteMatcherProvider('<root>', loader)
expect(await provider.matchers()).toEqual([])
expect(loader.load).toHaveBeenCalledWith(PAGES_MANIFEST)
})
describe('manifest matching', () => {
it. | {
"filepath": "packages/next/src/server/route-matcher-providers/pages-api-route-matcher-provider.test.ts",
"language": "typescript",
"file_size": 2447,
"cut_index": 563,
"middle_length": 229
} |
e-definition'
import { RouteKind } from '../route-kind'
import type { ManifestLoader } from './helpers/manifest-loaders/manifest-loader'
import { PagesRouteMatcherProvider } from './pages-route-matcher-provider'
describe('PagesRouteMatcherProvider', () => {
it('returns no routes with an empty manifest', async () => ... | : Array<string>; defaultLocale: string }
}>([
{
manifest: {
'/_app': 'pages/_app.js',
'/_error': 'pages/_error.js',
'/_document': 'pages/_document.js',
'/blog/[slug]': 'pages/blog/[slug].js',
| pect(loader.load).toHaveBeenCalledWith(PAGES_MANIFEST)
})
describe('locale matching', () => {
describe.each<{
manifest: Record<string, string>
routes: ReadonlyArray<PagesRouteDefinition>
i18n: { locales | {
"filepath": "packages/next/src/server/route-matcher-providers/pages-route-matcher-provider.test.ts",
"language": "typescript",
"file_size": 6055,
"cut_index": 716,
"middle_length": 229
} |
m '../../route-matchers/app-page-route-matcher'
import { RouteKind } from '../../route-kind'
import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provider'
import { DevAppNormalizers } from '../../normalizers/built/app'
import { normalizeCatchAllRoutes } from '../../../build/normalize-catchall-rou... | Turbopack: boolean
) {
super(appDir, reader)
this.normalizers = new DevAppNormalizers(appDir, extensions, isTurbopack)
// Match any page file that ends with `/page.${extension}` or `/default.${extension}` under the app
// directory.
| ivate readonly expression: RegExp
private readonly normalizers: DevAppNormalizers
private readonly isTurbopack: boolean
constructor(
appDir: string,
extensions: ReadonlyArray<string>,
reader: FileReader,
is | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/dev-app-page-route-matcher-provider.ts",
"language": "typescript",
"file_size": 3714,
"cut_index": 614,
"middle_length": 229
} |
der/file-reader'
import {
PagesAPILocaleRouteMatcher,
PagesAPIRouteMatcher,
} from '../../route-matchers/pages-api-route-matcher'
import { RouteKind } from '../../route-kind'
import path from 'path'
import type { LocaleRouteNormalizer } from '../../normalizers/locale-route-normalizer'
import { FileCacheRouteMatcher... | <string>,
reader: FileReader,
private readonly localeNormalizer?: LocaleRouteNormalizer
) {
super(pagesDir, reader)
// Match any route file that ends with `/${filename}.${extension}` under the
// pages directory.
this.expression | tcherProvider<PagesAPIRouteMatcher> {
private readonly expression: RegExp
private readonly normalizers: DevPagesNormalizers
constructor(
private readonly pagesDir: string,
private readonly extensions: ReadonlyArray | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/dev-pages-api-route-matcher-provider.ts",
"language": "typescript",
"file_size": 3022,
"cut_index": 563,
"middle_length": 229
} |
der/file-reader'
import {
PagesRouteMatcher,
PagesLocaleRouteMatcher,
} from '../../route-matchers/pages-route-matcher'
import { RouteKind } from '../../route-kind'
import path from 'path'
import type { LocaleRouteNormalizer } from '../../normalizers/locale-route-normalizer'
import { FileCacheRouteMatcherProvider }... | ader: FileReader,
private readonly localeNormalizer?: LocaleRouteNormalizer
) {
super(pagesDir, reader)
// Match any route file that ends with `/${filename}.${extension}` under the
// pages directory.
this.expression = new RegExp(`\\ | <PagesRouteMatcher> {
private readonly expression: RegExp
private readonly normalizers: DevPagesNormalizers
constructor(
private readonly pagesDir: string,
private readonly extensions: ReadonlyArray<string>,
re | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/dev-pages-route-matcher-provider.ts",
"language": "typescript",
"file_size": 2986,
"cut_index": 563,
"middle_length": 229
} |
` on `globalThis` at import time,
// so we have to do some contortions here to set it up before running anything else
type WASMod = typeof import('../app-render/work-async-storage.external')
type WSMod = typeof import('../app-render/work-unit-async-storage.external')
type AfterMod = typeof import('./after')
t... | ternal')
workAsyncStorage = WASMod.workAsyncStorage
const WSMod = await import('../app-render/work-unit-async-storage.external')
workUnitAsyncStorage = WSMod.workUnitAsyncStorage
const AfterContextMod = await import('./after-context')
| ntextMod['AfterContext']
let after: AfterMod['after']
beforeAll(async () => {
// @ts-expect-error
globalThis.AsyncLocalStorage = AsyncLocalStorage
const WASMod = await import('../app-render/work-async-storage.ex | {
"filepath": "packages/next/src/server/after/after-context.test.ts",
"language": "typescript",
"file_size": 17113,
"cut_index": 921,
"middle_length": 229
} |
rom './'
import type { NodeNextRequest, NodeNextResponse } from './node'
import type { WebNextRequest, WebNextResponse } from './web'
/**
* This file provides some helpers that should be used in conjunction with
* explicit environment checks. When combined with the environment checks, it
* will ensure that the corr... | t =>
process.env.NEXT_RUNTIME === 'edge'
/**
* Type guard to determine if a response is a WebNextResponse. This does not
* actually check the type of the response, but rather the runtime environment.
* It's expected that when the runtime environment | ather the runtime environment.
* It's expected that when the runtime environment is the edge runtime, that any
* base request is a WebNextRequest.
*/
export const isWebNextRequest = (req: BaseNextRequest): req is WebNextReques | {
"filepath": "packages/next/src/server/base-http/helpers.ts",
"language": "typescript",
"file_size": 2065,
"cut_index": 563,
"middle_length": 229
} |
'./index'
import { toNodeOutgoingHttpHeaders } from '../web/utils'
import { BaseNextRequest, BaseNextResponse } from './index'
import { DetachedPromise } from '../../lib/detached-promise'
import type { NextRequestHint } from '../web/adapter'
import { CloseController, trackBodyConsumed } from '../web/web-on-close'
imp... | .clone().body
)
this.request = request
this.fetchMetrics = request.fetchMetrics
this.headers = {}
for (const [name, value] of request.headers.entries()) {
this.headers[name] = value
}
}
async parseBody(_limit: string | n | gHttpHeaders
public fetchMetrics: FetchMetrics | undefined
constructor(request: NextRequestHint) {
const url = new URL(request.url)
super(
request.method,
url.href.slice(url.origin.length),
request | {
"filepath": "packages/next/src/server/base-http/web.ts",
"language": "typescript",
"file_size": 3816,
"cut_index": 614,
"middle_length": 229
} |
constants'
import type { AppRouteRouteDefinition } from '../route-definitions/app-route-route-definition'
import { RouteKind } from '../route-kind'
import { AppRouteRouteMatcherProvider } from './app-route-route-matcher-provider'
import type { ManifestLoader } from './helpers/manifest-loaders/manifest-loader'
describe... | ition
}>([
{
manifest: {
'/route': 'app/route.js',
},
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/',
filename: `<root>/${SERVER_DIRECTORY}/app/route.js`,
page: '/route' | w AppRouteRouteMatcherProvider('<root>', loader)
expect(await provider.matchers()).toEqual([])
})
describe('manifest matching', () => {
it.each<{
manifest: Record<string, string>
route: AppRouteRouteDefin | {
"filepath": "packages/next/src/server/route-matcher-providers/app-route-route-matcher-provider.test.ts",
"language": "typescript",
"file_size": 2381,
"cut_index": 563,
"middle_length": 229
} |
import { PAGES_MANIFEST } from '../../shared/lib/constants'
import { RouteKind } from '../route-kind'
import {
PagesAPILocaleRouteMatcher,
PagesAPIRouteMatcher,
} from '../route-matchers/pages-api-route-matcher'
import type {
Manifest,
ManifestLoader,
} from './helpers/manifest-loaders/manifest-loader'
import ... | private readonly i18nProvider?: I18NProvider
) {
super(PAGES_MANIFEST, manifestLoader)
this.normalizers = new PagesNormalizers(distDir)
}
protected async transform(
manifest: Manifest
): Promise<ReadonlyArray<PagesAPIRouteMatcher>> |
export class PagesAPIRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesAPIRouteMatcher> {
private readonly normalizers: PagesNormalizers
constructor(
distDir: string,
manifestLoader: ManifestLoader,
| {
"filepath": "packages/next/src/server/route-matcher-providers/pages-api-route-matcher-provider.ts",
"language": "typescript",
"file_size": 2297,
"cut_index": 563,
"middle_length": 229
} |
./../normalizers/normalizer'
import { AppRouteRouteMatcher } from '../../route-matchers/app-route-route-matcher'
import { RouteKind } from '../../route-kind'
import { FileCacheRouteMatcherProvider } from './file-cache-route-matcher-provider'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { Dev... | eMatcher> {
private readonly normalizers: {
page: Normalizer
pathname: Normalizer
bundlePath: Normalizer
}
private readonly appDir: string
private readonly isTurbopack: boolean
constructor(
appDir: string,
extensions: Readonl | ormalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route'
import path from '../../../shared/lib/isomorphic/path'
export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppRouteRout | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/dev-app-route-route-matcher-provider.ts",
"language": "typescript",
"file_size": 4940,
"cut_index": 614,
"middle_length": 229
} |
} from './file-reader'
import type { RecursiveReadDirOptions } from '../../../../../lib/recursive-readdir'
import { recursiveReadDir } from '../../../../../lib/recursive-readdir'
export type DefaultFileReaderOptions = Pick<
RecursiveReadDirOptions,
'pathnameFilter' | 'ignorePartFilter'
>
/**
* Reads all the file... | false to ignore
* @param ignoreFilter filter to ignore files and directories with absolute pathnames, false to ignore
* @param ignorePartFilter filter to ignore files and directories with the pathname part, false to ignore
*/
constructor(option | If undefined, no files are
* ignored.
*/
private readonly options: Readonly<DefaultFileReaderOptions>
/**
* Creates a new file reader.
*
* @param pathnameFilter filter to ignore files with absolute pathnames, | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/helpers/file-reader/default-file-reader.ts",
"language": "typescript",
"file_size": 1818,
"cut_index": 537,
"middle_length": 229
} |
ers } from 'http'
import type { I18NConfig } from '../config-shared'
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import type { NextApiRequestCookies } from '../api-utils'
import { getCookieParser } from '../api-utils/get-cookie-parser'
export interface BaseNextRequestConfig {
b... | ies: NextApiRequestCookies | undefined
public abstract headers: IncomingHttpHeaders
public abstract fetchMetrics: FetchMetric[] | undefined
constructor(
public method: string,
public url: string,
public body: Body
) {}
// Utils impl | status: number
cacheReason: string
cacheStatus: 'hit' | 'miss' | 'skip' | 'hmr'
cacheWarning?: string
}
export type FetchMetrics = Array<FetchMetric>
export abstract class BaseNextRequest<Body = any> {
protected _cook | {
"filepath": "packages/next/src/server/base-http/index.ts",
"language": "typescript",
"file_size": 2758,
"cut_index": 563,
"middle_length": 229
} |
import { BLOCKED_PAGES, PAGES_MANIFEST } from '../../shared/lib/constants'
import { RouteKind } from '../route-kind'
import {
PagesLocaleRouteMatcher,
PagesRouteMatcher,
} from '../route-matchers/pages-route-matcher'
import type {
Manifest,
ManifestLoader,
} from './helpers/manifest-loaders/manifest-loader'
im... | private readonly i18nProvider?: I18NProvider
) {
super(PAGES_MANIFEST, manifestLoader)
this.normalizers = new PagesNormalizers(distDir)
}
protected async transform(
manifest: Manifest
): Promise<ReadonlyArray<PagesRouteMatcher>> {
| ages'
export class PagesRouteMatcherProvider extends ManifestRouteMatcherProvider<PagesRouteMatcher> {
private readonly normalizers: PagesNormalizers
constructor(
distDir: string,
manifestLoader: ManifestLoader,
| {
"filepath": "packages/next/src/server/route-matcher-providers/pages-route-matcher-provider.ts",
"language": "typescript",
"file_size": 2690,
"cut_index": 563,
"middle_length": 229
} |
rectories: Array<string>
callbacks: Array<{
resolve: (value: ReadonlyArray<string>) => void
reject: (err: any) => void
}>
}
/**
* CachedFileReader will deduplicate requests made to the same folder structure
* to scan for files.
*/
export class BatchedFileReader implements FileReader {
private batch?: ... |
}
private getOrCreateBatch(): FileReaderBatch {
// If there is an existing batch and it's not completed, then reuse it.
if (this.batch && !this.batch.completed) {
return this.batch
}
const batch: FileReaderBatch = {
compl | ePromise?: Promise<void>
private schedule(callback: Function) {
if (!this.schedulePromise) {
this.schedulePromise = Promise.resolve()
}
this.schedulePromise.then(() => {
process.nextTick(callback)
}) | {
"filepath": "packages/next/src/server/route-matcher-providers/dev/helpers/file-reader/batched-file-reader.ts",
"language": "typescript",
"file_size": 3518,
"cut_index": 614,
"middle_length": 229
} |
rom '../route-definitions/app-page-route-definition'
import { RouteKind } from '../route-kind'
import { AppPageRouteMatcherProvider } from './app-page-route-matcher-provider'
import type { ManifestLoader } from './helpers/manifest-loaders/manifest-loader'
describe('AppPageRouteMatcherProvider', () => {
it('returns n... | '/page': 'app/page.js',
},
route: {
kind: RouteKind.APP_PAGE,
pathname: '/',
filename: `<root>/${SERVER_DIRECTORY}/app/page.js`,
page: '/page',
bundlePath: 'app/page',
appPaths: | expect(matcher.matchers()).resolves.toEqual([])
})
describe('manifest matching', () => {
it.each<{
manifest: Record<string, string>
route: AppPageRouteDefinition
}>([
{
manifest: {
| {
"filepath": "packages/next/src/server/route-matcher-providers/app-page-route-matcher-provider.test.ts",
"language": "typescript",
"file_size": 3686,
"cut_index": 614,
"middle_length": 229
} |
les in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/
import ReactDOM from 'react-dom'
export function preloadStyle(
href: string,
crossOrigin: string | undefined,
nonce: string | undefined
) {
const opts: any = { as: 'style' }
if (typeof crossOrigin === 'stri... | ') {
opts.nonce = nonce
}
ReactDOM.preload(href, opts)
}
export function preconnect(
href: string,
crossOrigin: string | undefined,
nonce: string | undefined
) {
const opts: any = {}
if (typeof crossOrigin === 'string') {
opts.crossO | e: string,
crossOrigin: string | undefined,
nonce: string | undefined
) {
const opts: any = { as: 'font', type }
if (typeof crossOrigin === 'string') {
opts.crossOrigin = crossOrigin
}
if (typeof nonce === 'string | {
"filepath": "packages/next/src/server/app-render/rsc/preloads.ts",
"language": "typescript",
"file_size": 1135,
"cut_index": 518,
"middle_length": 229
} |
import { spawn } from 'child_process'
import { getProjectDir } from '../lib/get-project-dir'
import { getNpxCommand } from '../lib/helpers/get-npx-command'
interface NextUpgradeOptions {
revision: string
verbose: boolean
}
export function spawnNextUpgrade(
directory: string | undefined,
options: NextUpgradeOp... | .push('--verbose')
}
const upgradeProcess = spawn(
upgradeProcessCommand,
upgradeProcessCommandArgs,
{
stdio: 'inherit',
cwd: baseDir,
}
)
upgradeProcess.on('close', (code) => {
process.exitCode = code ?? 0
})
}
| [
...upgradeProcessDefaultArgs,
// Needs to be bleeding edge (canary) to pick up latest codemods.
'@next/codemod@canary',
'upgrade',
options.revision,
]
if (options.verbose) {
upgradeProcessCommandArgs | {
"filepath": "packages/next/src/cli/next-upgrade.ts",
"language": "typescript",
"file_size": 997,
"cut_index": 512,
"middle_length": 229
} |
ib/head-manager-context.shared-runtime'
import { onRecoverableError } from './react-client-callbacks/on-recoverable-error'
import {
onCaughtError,
onUncaughtError,
} from './react-client-callbacks/error-boundary-callbacks'
import { callServer } from './app-call-server'
import { findSourceMapURL } from './app-find-s... | time'
import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-app'
import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-helpers'
import { getDeploymentId } from '../shared/lib/deployment-id'
import { setNavigat | RSCPayload } from '../shared/lib/app-router-types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-run | {
"filepath": "packages/next/src/client/app-index.tsx",
"language": "tsx",
"file_size": 14753,
"cut_index": 921,
"middle_length": 229
} |
if (process.env.NODE_ENV !== 'production') {
const callback = (mutationList: MutationRecord[]) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
for (const node of mutation.addedNodes) {
if (
'tagName' in node &&
(node... | const allLinks = [
...document.querySelectorAll(
'link[href^="' + resource + '"]'
),
// It's possible that the resource is a full URL or only pathn | t href = link.getAttribute('href')
if (href) {
const [resource, version] = href.split('?v=', 2)
if (version) {
const currentOrigin = window.location.origin
| {
"filepath": "packages/next/src/client/app-link-gc.ts",
"language": "typescript",
"file_size": 3125,
"cut_index": 614,
"middle_length": 229
} |
P: hydration warning
import './app-webpack'
import { renderAppDevOverlay } from 'next/dist/compiled/next-devtools'
import { appBootstrap } from './app-bootstrap'
import { getOwnerStack } from '../next-devtools/userspace/app/errors/stitched-error'
import { isRecoverableError } from './react-client-callbacks/on-recover... | Indicator = process.env.__NEXT_CACHE_COMPONENTS
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks, assetPrefix)
} finally {
renderAppDevOverlay(getOwnerStack, isRecoverableError, en | st enableCache | {
"filepath": "packages/next/src/client/app-next-dev.ts",
"language": "typescript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
ort './register-deployment-id-global'
import { appBootstrap } from './app-bootstrap'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
window.next.turbopack = true
;(self as any).__webpack_hash__ = ''
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentation... | ce/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error')
const { renderAppDevOverlay } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
ren | umentationHooks, assetPrefix)
} finally {
if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { getOwnerStack } =
require('../next-devtools/userspa | {
"filepath": "packages/next/src/client/app-next-turbopack.ts",
"language": "typescript",
"file_size": 1119,
"cut_index": 515,
"middle_length": 229
} |
st go first because it needs to patch webpack chunk loading
// before React patches chunk loading.
import './app-webpack'
import { appBootstrap } from './app-bootstrap'
const instrumentationHooks =
// eslint-disable-next-line @next/internal/typechecked-require -- not a module
require('../lib/require-instrumentatio... | e -- Why not relative imports?
require('next/dist/client/components/app-router')
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/layout-router')
hydrate(instrumentatio | -disable-next-line @next/internal/typechecked-requir | {
"filepath": "packages/next/src/client/app-next.ts",
"language": "typescript",
"file_size": 861,
"cut_index": 529,
"middle_length": 52
} |
ping in the webpack runtime
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
import './register-deployment-id-global'
import { getAssetToken, getAssetTokenQuery } from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-pat... | rver matches against and encoded
// filename path.
encodeURIPath(getChunkScriptFilename(...args)) + suffix
const getChunkCssFilename = __webpack_require__.k
__webpack_require__.k = (...args: any[]) =>
getChunkCssFilename(...args) + suffix
| optimized
if (getAssetToken()) {
const suffix = getAssetTokenQuery()
const getChunkScriptFilename = __webpack_require__.u
__webpack_require__.u = (...args: any[]) =>
// We encode the chunk filename because our static se | {
"filepath": "packages/next/src/client/app-webpack.ts",
"language": "typescript",
"file_size": 1753,
"cut_index": 537,
"middle_length": 229
} |
ectly assign location to URL
*
* The method will add basePath, and will also correctly add location (including if it is a relative path)
* @param location Location that should be added to the url
* @param url Base URL to which the location should be assigned
*/
export function assignLocation(location: string, url:... | URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'
// new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'
(urlBase.endsWith('/') ? urlBase : urlBase + '/') + loc | the current url must end with a slash
// new | {
"filepath": "packages/next/src/client/assign-location.ts",
"language": "typescript",
"file_size": 959,
"cut_index": 582,
"middle_length": 52
} |
?{"sensitive":"data"}',
{},
['/some/url', ''],
'refetch',
PrefetchHint.IsRootLayout | 1,
]
const result = prepareFlightRouterStateForRequest(flightRouterState, true)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded).toEqual(flightRouterState... | ('__PAGE__')
})
it('should preserve non-page segments', () => {
const flightRouterState: FlightRouterState = ['regular-segment', {}]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse | '__PAGE__?{"param":"value","foo":"bar"}',
{},
]
const result = prepareFlightRouterStateForRequest(flightRouterState)
const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[0]).toBe | {
"filepath": "packages/next/src/client/flight-data-helpers.test.ts",
"language": "typescript",
"file_size": 9574,
"cut_index": 921,
"middle_length": 229
} |
cSegmentAppearInURL,
getRenderedPathname,
getRenderedSearch,
} from './route-params'
import { createHrefFromUrl } from './components/router-reducer/create-href-from-url'
export type NormalizedFlightData = {
/**
* The full `FlightSegmentPath` inclusive of the final `Segment`
*/
segmentPath: FlightSegmentP... | 't conform to the `FlightDataPath` type (it's missing the root segment)
// we're currently exporting it so we can use it directly. This should be fixed as part of the unification of
// the different ways we express `FlightSegmentPath`.
export function getF | ll
head: HeadData
isHeadPartial: boolean
isRootRender: boolean
}
// TODO: We should only have to export `normalizeFlightData`, however because the initial flight data
// that gets passed to `createInitialRouterState` doesn | {
"filepath": "packages/next/src/client/flight-data-helpers.ts",
"language": "typescript",
"file_size": 10711,
"cut_index": 921,
"middle_length": 229
} |
SALLOWED_FORM_PROPS)[number]
type InternalFormProps = {
/**
* `action` can be either a `string` or a function.
* - If `action` is a string, it will be interpreted as a path or URL to navigate to when the form is submitted.
* The path will be prefetched when the form becomes visible.
* - If `action` is ... | alse}`. Prefetching is only enabled in production.
*
* Options:
* - "auto", null, undefined (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest | 'action']>
/**
* Controls how the route specified by `action` is prefetched.
* Any `<Form />` that is in the viewport (initially or through scroll) will be prefetched.
* Prefetch can be disabled by passing `prefetch={f | {
"filepath": "packages/next/src/client/form-shared.tsx",
"language": "tsx",
"file_size": 7593,
"cut_index": 716,
"middle_length": 229
} |
ort type { NextRouter } from './router'
import {
checkFormActionUrl,
createFormSubmitDestinationUrl,
DISALLOWED_FORM_PROPS,
hasReactClientActionAttributes,
hasUnsupportedSubmitterAttributes,
type FormProps,
} from './form-shared'
export type { FormProps }
const Form = forwardRef<HTMLFormElement, FormProps... | cess.env.NODE_ENV === 'development') {
if (prefetchProp !== undefined) {
console.error(
'Passing `prefetch` to a <Form> has no effect in the pages directory.'
)
}
}
// Validate `scroll` and `replace`
if (process.env.NODE_ | orm = typeof actionProp === 'string'
// Validate `action`
if (process.env.NODE_ENV === 'development') {
if (isNavigatingForm) {
checkFormActionUrl(actionProp, 'action')
}
}
// Validate `prefetch`
if (pro | {
"filepath": "packages/next/src/client/form.tsx",
"language": "tsx",
"file_size": 5109,
"cut_index": 716,
"middle_length": 229
} |
{ DomainLocale } from '../server/config'
import type { normalizeLocalePath as NormalizeFn } from './normalize-locale-path'
import type { detectDomainLocale as DetectFn } from './detect-domain-locale'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'
const basePath = (process.env.__NEXT_ROUTER_BAS... | etectFn = (
require('./detect-domain-locale') as typeof import('./detect-domain-locale')
).detectDomainLocale
const target = locale || normalizeLocalePath(path, locales).detectedLocale
const domain = detectDomainLocale(domainLocales, und | nv.__NEXT_I18N_SUPPORT) {
const normalizeLocalePath: typeof NormalizeFn = (
require('./normalize-locale-path') as typeof import('./normalize-locale-path')
).normalizeLocalePath
const detectDomainLocale: typeof D | {
"filepath": "packages/next/src/client/get-domain-locale.ts",
"language": "typescript",
"file_size": 1354,
"cut_index": 524,
"middle_length": 229
} |
function reactElementToDOM({ type, props }: JSX.Element): HTMLElement {
const el: HTMLElement = document.createElement(type)
setAttributesFromProps(el, props)
const { children, dangerouslySetInnerHTML } = props
if (dangerouslySetInnerHTML) {
el.innerHTML = dangerouslySetInnerHTML.__html || ''
} else if... | that have nonces, `Element,isEqualNode()` will return false if one
* of those elements gets added to the document. Although the `element.nonce` property will be the
* same for both elements, the one that was added to the document will return an empty st | * When a `nonce` is present on an element, browsers such as Chrome and Firefox strip it out of the
* actual HTML attributes for security reasons *when the element is added to the document*. Thus,
* given two equivalent elements | {
"filepath": "packages/next/src/client/head-manager.ts",
"language": "typescript",
"file_size": 4725,
"cut_index": 614,
"middle_length": 229
} |
type {
ImageConfigComplete,
ImageLoaderProps,
} from '../shared/lib/image-config'
import { imageConfigDefault } from '../shared/lib/image-config'
import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'
import { warnOnce } from '../shared/lib/utils/warn-once'
import { RouterContext } f... | type { ImageLoaderProps }
export type ImageLoader = (p: ImageLoaderProps) => string
type ImgElementWithDataProp = HTMLImageElement & {
'data-loaded-src'?: string | undefined
}
type ImageElementProps = ImgProps & {
unoptimized: boolean
placeholder: | -ref'
// This is replaced by webpack define plugin
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
if (typeof window === 'undefined') {
;(globalThis as any).__NEXT_IMAGE_IMPORTED = true
}
export | {
"filepath": "packages/next/src/client/image-component.tsx",
"language": "tsx",
"file_size": 14699,
"cut_index": 921,
"middle_length": 229
} |
archParams,
assign,
} from '../shared/lib/router/utils/querystring'
import { getURL, loadGetInitialProps, ST } from '../shared/lib/utils'
import type { NextWebVitalsMetric, NEXT_DATA } from '../shared/lib/utils'
import { Portal } from './portal'
import initHeadManager from './head-manager'
import PageLoader from './p... | /remove-base-path'
import { hasBasePath } from './has-base-path'
import { AppRouterContext } from '../shared/lib/app-router-context.shared-runtime'
import {
adaptForAppRouterInstance,
adaptForPathParams,
adaptForSearchParams,
PathnameContextProvide | etProperError } from '../lib/is-error'
import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import { removeBasePath } from '. | {
"filepath": "packages/next/src/client/index.tsx",
"language": "tsx",
"file_size": 31561,
"cut_index": 1331,
"middle_length": 229
} |
seMergedRef } from './use-merged-ref'
import { errorOnce } from '../shared/lib/utils/error-once'
type Url = string | UrlObject
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K
}[keyof T]
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never
}[keyof T]
type OnNavi... | ious docs](https://github.com/vercel/next.js/blob/v9.5.2/docs/api-reference/next/link.md#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous | extjs.org/docs/api-reference/next/link#with-url-object
*/
href: Url
/**
* Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [prev | {
"filepath": "packages/next/src/client/link.tsx",
"language": "tsx",
"file_size": 23775,
"cut_index": 1331,
"middle_length": 229
} |
s gets assigned as a side-effect during app initialization. Because it
// represents the build used to create the JS bundle, it should never change
// after being set, so we store it in a global variable.
//
// When performing RSC requests, if the incoming data has a different build ID,
// we perform an MPA navigation/... | uld fail and trigger an MPA navigation.
//
// Note that this can also be initialized with the deployment id instead (if available). So it's not
// the same as "the build id", but we are running out of alternative names for "build id or
// deployment id".
l | / before hydration starts, this will always get reassigned to the actual ID before it's ever needed
// by a navigation. If for some reasons it didn't, due to a bug or race condition, then on
// navigation the build comparision wo | {
"filepath": "packages/next/src/client/navigation-build-id.ts",
"language": "typescript",
"file_size": 1193,
"cut_index": 518,
"middle_length": 229
} |
polyfill from `@next/polyfill-module` after build.
import '../build/polyfills/polyfill-module'
// Only set up devtools for the dev server.
if (process.env.__NEXT_DEV_SERVER) {
require('../next-devtools/userspace/app/app-dev-overlay-setup') as typeof import('../next-devtools/userspace/app/app-dev-overlay-setup')
}
... | ING_API && typeof window !== 'undefined') {
const { startListeningForInstantNavigationCookie } =
require('./components/segment-cache/navigation-testing-lock') as typeof import('./components/segment-cache/navigation-testing-lock')
startListeningForI | XT_EXPOSE_TEST | {
"filepath": "packages/next/src/client/app-globals.ts",
"language": "typescript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
out time-based windows
*
* This ensures we suppress noisy prerender-related rejections while preserving
* normal error logging for genuine unhandled rejections.
*/
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
const MODE:
| 'enabled'
| 'debug'
| 'silent'
| 'true'
... | eak
case '':
case undefined:
case 'enabled':
case 'true':
case '1':
break
default:
if (typeof MODE === 'string') {
console.error(
`NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use "en | arn'
switch (MODE) {
case 'silent':
UHR_FILTER_LOG_LEVEL = 'silent'
break
case 'debug':
UHR_FILTER_LOG_LEVEL = 'debug'
break
case 'false':
case 'disabled':
case '0':
ENABLE_UHR_FILTER = false
br | {
"filepath": "packages/next/src/server/node-environment-extensions/unhandled-rejection.external.tsx",
"language": "tsx",
"file_size": 25257,
"cut_index": 1331,
"middle_length": 229
} |
to APIs during builds and revalidates to ensure that prerenders don't observe random bytes
* When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is
* enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.
*
... | pto'))
.webcrypto
} else {
webCrypto = crypto
}
}
const getRandomValuesExpression = '`crypto.getRandomValues()`'
try {
const _getRandomValues = webCrypto.getRandomValues
webCrypto.getRandomValues = function getRandomValues() {
io(get | rocess.env.NEXT_RUNTIME === 'edge') {
webCrypto = crypto
} else {
if (typeof crypto === 'undefined') {
// @ts-expect-error -- TODO: Is this actually safe?
webCrypto = (require('node:crypto') as typeof import('node:cry | {
"filepath": "packages/next/src/server/node-environment-extensions/web-crypto.tsx",
"language": "tsx",
"file_size": 1788,
"cut_index": 537,
"middle_length": 229
} |
teSelfSignedCertificate } from '../lib/mkcert'
import type { SelfSignedCertificate } from '../lib/mkcert'
import uploadTrace from '../trace/upload-trace'
import { initialEnv } from '@next/env'
import { fork } from 'child_process'
import type { ChildProcess } from 'child_process'
import {
getReservedPortExplanation,
... | { Bundler, parseBundlerArgs } from '../lib/bundler'
export type NextDevOptions = {
disableSourceMaps: boolean
// Commander is not putting `--inspect` through the arg parser
inspect?: DebugAddress | true
turbo?: boolean
turbopack?: boolean
web | from 'os'
import fs from 'node:fs'
import { once } from 'node:events'
import { clearTimeout } from 'timers'
import { trace, initializeTraceState, exportTraceState } from '../trace'
import { traceId } from '../trace/shared'
import | {
"filepath": "packages/next/src/cli/next-dev.ts",
"language": "typescript",
"file_size": 18623,
"cut_index": 1331,
"middle_length": 229
} |
nv node
import { existsSync } from 'fs'
import path from 'path'
import loadConfig from '../server/config'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { getProjectDir } from '../lib/get-project-dir'
import { printAndExit } from '../server/lib/utils'
import { loadBindings } from '../build/swc... | orBuild || false
if (!persistentCaching) {
console.log('Persistent caching for build is not enabled. Nothing to do.')
return
}
const distDir = path.join(dir, config.distDir)
const cachePath = path.join(distDir, 'cache', 'turbopack')
if | dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
const config = await loadConfig(PHASE_PRODUCTION_BUILD, dir)
const persistentCaching =
config.experimental?.turbopackFileSystemCacheF | {
"filepath": "packages/next/src/cli/next-post-build.ts",
"language": "typescript",
"file_size": 1382,
"cut_index": 524,
"middle_length": 229
} |
nv node
import { bold, cyan, green, red, yellow } from '../lib/picocolors'
import { Telemetry } from '../telemetry/storage'
export type NextTelemetryOptions = {
enable?: boolean
disable?: boolean
}
const telemetry = new Telemetry({ distDir: process.cwd() })
let isEnabled = telemetry.isEnabled
const nextTelemetr... | console.log(yellow(`Next.js' telemetry collection is already disabled.`))
}
isEnabled = false
} else {
console.log(bold('Next.js Telemetry'))
}
console.log(
`\nStatus: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled' | e if (options.disable || arg === 'disable') {
const path = telemetry.setEnabled(false)
if (isEnabled) {
console.log(
cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`)
)
} else {
| {
"filepath": "packages/next/src/cli/next-telemetry.ts",
"language": "typescript",
"file_size": 1397,
"cut_index": 524,
"middle_length": 229
} |
} from 'fs/promises'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyAndRunTypeScript ... | { installBindings } from '../build/swc/install-bindings'
export type NextTypegenOptions = {
dir?: string
}
const nextTypegen = async (
_options: NextTypegenOptions,
directory?: string
) => {
const baseDir = getProjectDir(directory)
// Check i | '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { writeRootParamsTypes } from '../server/lib/router-utils/root-params-type-utils'
import | {
"filepath": "packages/next/src/cli/next-typegen.ts",
"language": "typescript",
"file_size": 3544,
"cut_index": 614,
"middle_length": 229
} |
ort { encodeURIPath } from '../shared/lib/encode-uri-path'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { getTracer } from '../server/lib/trace/tracer'
import { getTracedMetadata } from '../server/lib/trace/utils'
export type { DocumentContext, DocumentInitialProps, DocumentProps }
export ty... | es that have triggered a large data warning on production mode. */
const largePageDataWarnings = new Set<string>()
function getDocumentFiles(
buildManifest: BuildManifest,
pathname: string
): DocumentFiles {
const sharedFiles: readonly string[] = ge | ageFiles: readonly string[]
allFiles: readonly string[]
}
type HeadHTMLProps = React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadElement>,
HTMLHeadElement
>
type HeadProps = OriginProps & HeadHTMLProps
/** Set of pag | {
"filepath": "packages/next/src/pages/_document.tsx",
"language": "tsx",
"file_size": 29456,
"cut_index": 1331,
"middle_length": 229
} |
../shared/lib/utils'
const statusCodes: { [code: number]: string } = {
400: 'Bad Request',
404: 'This page could not be found',
405: 'Method Not Allowed',
500: 'Internal Server Error',
}
export type ErrorProps = {
statusCode: number
hostname?: string
title?: string
withDarkMode?: boolean
}
function _... | const initUrl = getRequestMeta(req, 'initURL')
if (initUrl) {
const url = new URL(initUrl)
hostname = url.hostname
}
}
return { statusCode, hostname }
}
const styles: Record<string, React.CSSProperties> = {
error: {
// ht | let hostname
if (typeof window !== 'undefined') {
hostname = window.location.hostname
} else if (req) {
const { getRequestMeta } =
require('../server/request-meta') as typeof import('../server/request-meta')
| {
"filepath": "packages/next/src/pages/_error.tsx",
"language": "tsx",
"file_size": 4276,
"cut_index": 614,
"middle_length": 229
} |
er-headers'
import type {
NormalizedPathname,
NormalizedSearch,
} from './components/segment-cache/cache-key'
import type { RSCResponse } from './components/router-reducer/fetch-server-response'
import type { ParsedUrlQuery } from 'querystring'
export type RouteParamValue = string | Array<string> | null
export fu... | !== null) {
return (
rewrittenQuery === '' ? '' : '?' + rewrittenQuery
) as NormalizedSearch
}
// If the header is not present, there was no rewrite, so we use the search
// query of the response URL.
return urlToUrlWithoutFlightMark | rent from the params in the request URL. In this case,
// the response will include a header that gives the rewritten search query.
const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)
if (rewrittenQuery | {
"filepath": "packages/next/src/client/route-params.ts",
"language": "typescript",
"file_size": 9804,
"cut_index": 921,
"middle_length": 229
} |
uter-context.shared-runtime'
import isError from '../lib/is-error'
type SingletonRouterBase = {
router: Router | null
readyCallbacks: Array<() => any>
ready(cb: () => any): void
}
export { Router }
export type { NextRouter }
export type SingletonRouter = SingletonRouterBase & NextRouter
const singletonRouter... | 'components',
'isFallback',
'basePath',
'locale',
'locales',
'defaultLocale',
'isReady',
'isPreview',
'isLocaleDomain',
'domainLocales',
] as const
const routerEvents = [
'routeChangeStart',
'beforeHistoryChange',
'routeChangeCompl | !== 'undefined') {
this.readyCallbacks.push(callback)
}
},
}
// Create public properties and methods of the router in the singletonRouter
const urlPropertyFields = [
'pathname',
'route',
'query',
'asPath',
| {
"filepath": "packages/next/src/client/router.ts",
"language": "typescript",
"file_size": 5291,
"cut_index": 716,
"middle_length": 229
} |
String } from '../shared/lib/htmlescape'
const ScriptCache = new Map()
const LoadCache = new Set()
export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive' | 'worker'
id?: string
onLoad?: (e: any) => void
onReady?: () => ... | esheets might have already been loaded if initialized with Script component
// Re-inject styles here to handle scripts loaded via handleClientScriptLoad
// ReactDOM.preinit handles dedup and ensures the styles are loaded only once
if (ReactDOM.preini | tStylesheets = (stylesheets: string[]) => {
// Case 1: Styles for afterInteractive/lazyOnload with appDir injected via handleClientScriptLoad
//
// Using ReactDOM.preinit to feature detect appDir and inject styles
// Styl | {
"filepath": "packages/next/src/client/script.tsx",
"language": "tsx",
"file_size": 11928,
"cut_index": 921,
"middle_length": 229
} |
Record<string, string> = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv',
noModule: 'noModule',
}
const ignoreProps = [
'onLoad',
'onReady',
'dangerouslySetInnerHTML',
'children',
'onError',
'strategy',
'stylesheets',
]
function isBooleanScriptAtt... | continue
}
const attr = DOMAttributeNames[p] || p.toLowerCase()
if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {
// Correctly assign boolean script attributes
// https://github.com/vercel/next.js/pull/20748
| ct) {
for (const [p, value] of Object.entries(props)) {
if (!props.hasOwnProperty(p)) continue
if (ignoreProps.includes(p)) continue
// we don't render undefined props to the DOM
if (value === undefined) {
| {
"filepath": "packages/next/src/client/set-attributes-from-props.ts",
"language": "typescript",
"file_size": 1739,
"cut_index": 537,
"middle_length": 229
} |
s the Trusted Types Policy. Starts as undefined and can be set to null
* if Trusted Types is not supported in the browser.
*/
let policy: TrustedTypePolicy | null | undefined
/**
* Getter for the Trusted Types Policy. If it is undefined, it is instantiated
* here or set to null if Trusted Types is not supported in... | * when Trusted Types are not available.
* This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that the
* provided string will never cause an XSS vulnerability if used in a | HTML: (input) => input,
createScript: (input) => input,
createScriptURL: (input) => input,
}) || null
}
return policy
}
/**
* Unsafely promote a string to a TrustedScriptURL, falling back to strings
| {
"filepath": "packages/next/src/client/trusted-types.ts",
"language": "typescript",
"file_size": 1265,
"cut_index": 524,
"middle_length": 229
} |
celIdleCallback,
} from './request-idle-callback'
type UseIntersectionObserverInit = Pick<
IntersectionObserverInit,
'rootMargin' | 'root'
>
type UseIntersection = { disabled?: boolean } & UseIntersectionObserverInit & {
rootRef?: React.RefObject<HTMLElement | null> | null
}
type ObserveCallback = (isVisibl... | Init): Observer {
const id = {
root: options.root || null,
margin: options.rootMargin || '',
}
const existing = idList.find(
(obj) => obj.root === id.root && obj.margin === id.margin
)
let instance: Observer | undefined
if (existin | eCallback>
}
const hasIntersectionObserver = typeof IntersectionObserver === 'function'
const observers = new Map<Identifier, Observer>()
const idList: Identifier[] = []
function createObserver(options: UseIntersectionObserver | {
"filepath": "packages/next/src/client/use-intersection.tsx",
"language": "tsx",
"file_size": 3605,
"cut_index": 614,
"middle_length": 229
} |
t'
// This is a compatibility hook to support React 18 and 19 refs.
// In 19, a cleanup function from refs may be returned.
// In 18, returning a cleanup function creates a warning.
// Since we take userspace refs, we don't know ahead of time if a cleanup function will be returned.
// This implements cleanup functions... | d skip the wrapping if only one of the refs is non-null.
// (this happens often if the user doesn't pass a ref to Link/Form/Image)
// But this can cause us to leak a cleanup-ref into user code (previously via `<Link legacyBehavior>`),
// and the user | tion useMergedRef<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): Ref<TElement> {
const cleanupA = useRef<(() => void) | null>(null)
const cleanupB = useRef<(() => void) | null>(null)
// NOTE: In theory, we coul | {
"filepath": "packages/next/src/client/use-merged-ref.ts",
"language": "typescript",
"file_size": 2325,
"cut_index": 563,
"middle_length": 229
} |
PHASE_DEVELOPMENT_SERVER } from '../../shared/lib/constants'
import type { TraceEvent } from '../types'
import type { Reporter } from './types'
// Batch events as zipkin allows for multiple events to be sent in one go
export function batcher(reportEvents: (evts: TraceEvent[]) => Promise<void>) {
const events: Trace... | vents.length = 0
const report = reportEvents(evts)
queue.add(report)
report.then(() => queue.delete(report))
}
},
}
}
const writeStreamOptions = {
flags: 'a',
encoding: 'utf8' as const,
}
class RotatingWriteStream { | ngth > 0) {
await reportEvents(events)
events.length = 0
}
},
report: (event: TraceEvent) => {
events.push(event)
if (events.length > 100) {
const evts = events.slice()
e | {
"filepath": "packages/next/src/trace/report/to-json.ts",
"language": "typescript",
"file_size": 4668,
"cut_index": 614,
"middle_length": 229
} |
t
| OutputReport
| ErrorLogReport
| SerializableDataReport
type ErrorReport = { type: 'error'; message: string }
type OutputReport = { type: 'output'; message: string }
type CountReport = {
type: 'count'
count: number
}
type UHRReport = {
type: 'uhr'
reason: string
}
type ErrorLogReport = {
type: 'error... | eport>
errorLog: Array<string>
data: Record<string, unknown>
messages: Array<ReportableResult>
}
export function runWorkerCode(fn: Function): Promise<WorkerResult> {
return new Promise((resolve, reject) => {
const script = `
const { pare | t type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
import { Worker } from 'node:worker_threads'
type WorkerResult = {
exitCode: number
stderr: string
uhr: Array<UHRReport>
count: Array<CountR | {
"filepath": "packages/next/src/server/node-environment-extensions/unhandled-rejection.external.test.ts",
"language": "typescript",
"file_size": 40593,
"cut_index": 2151,
"middle_length": 229
} |
nv node
import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs'
import { italic } from '../lib/picocolors'
import analyze from '../build/analyze'
import { warn } from '../build/output/log'
import { printAndExit } from '../server/lib/utils'
import { ... | eCpuProfile()
process.exit(130)
})
const { profile, mangling, experimentalAppOnly, output, port } = options
if (!mangling) {
warn(
`Mangling is disabled. ${italic('Note: This may affect performance and should only be used for debuggin | erimentalAppOnly?: boolean
}
const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
process.on('SIGTERM', () => {
saveCpuProfile()
process.exit(143)
})
process.on('SIGINT', () => {
sav | {
"filepath": "packages/next/src/cli/next-analyze.ts",
"language": "typescript",
"file_size": 1482,
"cut_index": 524,
"middle_length": 229
} |
IME is set for accurate "Ready in" timing.
// This should already be set by bin/next.ts, but we set it here as a fallback
// in case the module is loaded through a different code path.
if (!process.env.NEXT_PRIVATE_START_TIME) {
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()
}
import '../server/lib/cpu-... | om '../build/output/log'
export type NextStartOptions = {
port: number
hostname?: string
// Commander is not putting `--inspect` through the arg parser
inspect?: DebugAddress | true
keepAliveTimeout?: number
experimentalNextConfigStripTypes?: | xit,
type DebugAddress,
} from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir'
import {
getReservedPortExplanation,
isPortIsReserved,
} from '../lib/helpers/get-reserved-port'
import * as Log fr | {
"filepath": "packages/next/src/cli/next-start.ts",
"language": "typescript",
"file_size": 2859,
"cut_index": 563,
"middle_length": 229
} |
RPC `tools/call` request and prints the response to stdout.
* Use --json for machine-readable JSON output (default: markdown).
*
* Usage: next internal query-trace [options]
*/
const DEFAULT_MCP_PORT = 5748 // Keep in sync with turbo-trace-server.ts
interface QueryTraceOptions {
port: number | undefined
paren... | ptions.parent !== undefined) args.parent = options.parent
if (options.aggregated !== undefined) args.aggregated = options.aggregated
if (options.sort !== undefined) args.sort = options.sort
if (options.search !== undefined) args.search = options.sear | queryTraceCli(options: QueryTraceOptions): Promise<void> {
const port = options.port ?? DEFAULT_MCP_PORT
// Build arguments — only include values explicitly set by the user.
const args: Record<string, unknown> = {}
if (o | {
"filepath": "packages/next/src/cli/internal/query-trace.ts",
"language": "typescript",
"file_size": 3114,
"cut_index": 614,
"middle_length": 229
} |
t/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp') as typeof import('next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp')
const DEFAULT_WS_PORT = 5747
/** 100 internal ticks = 1 µs */
const TICKS_PER_US = 100
const TICKS_PER_MS = TICKS_PER_US * 1000
const TICKS_PER_S = TICKS_PER_MS * 10... | the parent reference point
const prefix = ticks < 0 ? '-' : ''
return prefix + formatDuration(Math.abs(ticks))
}
function formatBytes(bytes: number): string {
const KB = 1024
const MB = KB * 1024
const GB = MB * 1024
if (bytes >= GB) return ` | t ms = ticks / TICKS_PER_MS
return `${ms.toFixed(2)}ms`
}
const s = ticks / TICKS_PER_S
return `${s.toFixed(3)}s`
}
function formatRelative(ticks: number): string {
// ticks may be negative if the child starts before | {
"filepath": "packages/next/src/cli/internal/turbo-trace-server.ts",
"language": "typescript",
"file_size": 10086,
"cut_index": 921,
"middle_length": 229
} |
React from 'react'
import type {
AppContextType,
AppInitialProps,
AppPropsType,
NextWebVitalsMetric,
AppType,
} from '../shared/lib/utils'
import type { Router } from '../client/router'
import { loadGetInitialProps } from '../shared/lib/utils'
export type { AppInitialProps, AppType }
export type { NextWe... | Context): Promise<AppInitialProps> {
const pageProps = await loadGetInitialProps(Component, ctx)
return { pageProps }
}
export default class App<P = any, CP = {}, S = {}> extends React.Component<
P & AppProps<CP>,
S
> {
static origGetInitialProp | overwriting and full control of the `page` initialization.
* This allows for keeping state between navigation, custom error handling, injecting additional data.
*/
async function appGetInitialProps({
Component,
ctx,
}: App | {
"filepath": "packages/next/src/pages/_app.tsx",
"language": "tsx",
"file_size": 1197,
"cut_index": 518,
"middle_length": 229
} |
lient-side entry point for Turbopack builds. Includes logic to load chunks,
// but does not include development-time features like hot module reloading.
import './register-deployment-id-global'
import '../lib/require-instrumentation-client'
// TODO: Remove use of `any` type.
import { initialize, version, router, emit... | ck_load_page_chunks__ = (
page: string,
chunksData: any
) => {
const chunkPromises = chunksData.map((c: unknown) =>
__turbopack_load__(c)
)
Promise.all(chunkPromises).catch((err) =>
console.error('failed t | as any).__next_set_public_path__ = () => {}
;(self as any).__webpack_hash__ = ''
// for the page loader
declare let __turbopack_load__: any
initialize({})
.then(() => {
// for the page loader
;(self as any).__turbopa | {
"filepath": "packages/next/src/client/next-turbopack.ts",
"language": "typescript",
"file_size": 1154,
"cut_index": 518,
"middle_length": 229
} |
connectHMR,
addMessageListener,
} from './dev/hot-reloader/pages/websocket'
import {
assign,
urlQueryToSearchParams,
} from '../shared/lib/router/utils/querystring'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types'
import { RuntimeErrorHandler } from './dev/runtime-error-handler'
impo... | t reloading = false
addMessageListener((message) => {
if (reloading) return
switch (message.type) {
case HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ERROR: {
const errorObject = JSON.parse(message.errorJSON)
const error | st/compiled/next-devtools'
export function pageBootstrap(assetPrefix: string) {
connectHMR({ assetPrefix, path: '/_next/hmr' })
return hydrate({ beforeRender: displayContent }).then(() => {
initOnDemandEntries()
le | {
"filepath": "packages/next/src/client/page-bootstrap.ts",
"language": "typescript",
"file_size": 5185,
"cut_index": 716,
"middle_length": 229
} |
ase-path'
import { interpolateAs } from '../shared/lib/router/utils/interpolate-as'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
import { addLocale } from './add-locale'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { parseRelativeUrl } from '.... | ce Window {
__DEV_MIDDLEWARE_MATCHERS?: ProxyMatcher[]
__DEV_PAGES_MANIFEST?: { pages: string[] }
__SSG_MANIFEST_CB?: () => void
__SSG_MANIFEST?: Set<string>
}
}
export type StyleSheetTuple = { href: string; text: string }
export type Go | arkAssetError,
} from './route-loader'
import {
DEV_CLIENT_PAGES_MANIFEST,
DEV_CLIENT_MIDDLEWARE_MANIFEST,
} from '../shared/lib/constants'
import { resolvePromiseWithTimeout } from './lib/promise'
declare global {
interfa | {
"filepath": "packages/next/src/client/page-loader.ts",
"language": "typescript",
"file_size": 6871,
"cut_index": 716,
"middle_length": 229
} |
etTokenQuery } from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-path'
import { resolvePromiseWithTimeout } from './lib/promise'
declare global {
interface Window {
__BUILD_MANIFEST?: Record<string, string[]>
__BUILD_MANIFEST_CB?: Function
__SERVER_FILES_MANIFEST?... | : ComponentType
exports: any
}
interface LoadedEntrypointFailure {
error: unknown
}
type RouteEntrypoint = LoadedEntrypointSuccess | LoadedEntrypointFailure
interface RouteStyleSheet {
href: string
content: string
}
interface LoadedRouteSuccess e | MANIFEST?: any
__RSC_SERVER_MANIFEST?: any
__NEXT_FONT_MANIFEST?: any
__SUBRESOURCE_INTEGRITY_MANIFEST?: string
__INTERCEPTION_ROUTE_REWRITE_MANIFEST?: string
}
}
interface LoadedEntrypointSuccess {
component | {
"filepath": "packages/next/src/client/route-loader.ts",
"language": "typescript",
"file_size": 12629,
"cut_index": 921,
"middle_length": 229
} |
ort { tmpdir } from 'os'
import { join } from 'path'
import { setGlobal } from '../trace/shared'
import {
recordFrameworkVersion,
updateBuildDiagnostics,
} from './build-diagnostics'
async function readBuildDiagnostics(dir: string) {
return JSON.parse(
await readFile(join(dir, 'diagnostics', 'build-diagnosti... | 'diagnostics', 'framework.json'), 'utf8')
)
expect(diagnostics.version).toEqual('14.2.3')
})
it('records build diagnostics to a file correctly', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'build-diagnostics'))
setGlobal( | ld-diagnostics'))
setGlobal('distDir', tmpDir)
// Record the initial diagnostics and make sure it's correct.
await recordFrameworkVersion('14.2.3')
let diagnostics = JSON.parse(
await readFile(join(tmpDir, | {
"filepath": "packages/next/src/diagnostics/build-diagnostics.test.ts",
"language": "typescript",
"file_size": 2217,
"cut_index": 563,
"middle_length": 229
} |
rom 'fs'
import path from 'path'
import { getGitBranch, getGitCommit } from '../lib/helpers/git'
const COMMON_ALLOWED_EVENTS = ['memory-usage']
// Predefined set of the event names to be included in the trace.
// If the trace span's name matches to one of the event names in the set,
// it'll up uploaded to the trace ... | rbopack',
'webpack-compilation',
'run-webpack-compiler',
'create-entrypoints',
'worker-main-edge-server',
'worker-main-client',
'worker-main-server',
'server',
'make',
'seal',
'chunk-graph',
'optimize-modules',
'optimize-chunks',
| 'navigation-to-hydration',
'start-dev-server',
'compile-path',
'memory-usage',
'server-restart-close-to-memory-threshold',
])
const BUILD_ALLOWED_EVENTS = new Set([
...COMMON_ALLOWED_EVENTS,
'next-build',
'run-tu | {
"filepath": "packages/next/src/trace/trace-uploader.ts",
"language": "typescript",
"file_size": 6456,
"cut_index": 716,
"middle_length": 229
} |
et count = 0
const getId = () => {
count++
return count
}
let defaultParentSpanId: SpanId | undefined
let shouldSaveTraceEvents: boolean | undefined
let savedTraceEvents: TraceEvent[] = []
const RECORD_SPAN_THRESHOLD_MS = parseInt(
process.env.NEXT_TRACE_SPAN_THRESHOLD_MS ?? '-1'
)
// eslint typescript has a bu... | parentId,
attrs,
startTime,
}: {
name: string
parentId?: SpanId
startTime?: bigint
attrs?: Attributes
}) {
this.name = name
this.parentId = parentId ?? defaultParentSpanId
this.attrs = attrs ? { ...attrs } : {}
| e id: SpanId
private parentId?: SpanId
private attrs: { [key: string]: unknown }
private status: SpanStatus
private now: number
// Number of nanoseconds since epoch.
private _start: bigint
constructor({
name,
| {
"filepath": "packages/next/src/trace/trace.ts",
"language": "typescript",
"file_size": 6056,
"cut_index": 716,
"middle_length": 229
} |
e } from 'fs/promises'
import { reporter } from '.'
import { setGlobal } from '../shared'
import { join } from 'path'
import { tmpdir } from 'os'
const TRACE_EVENT = {
name: 'test-span',
duration: 321,
timestamp: Date.now(),
id: 127,
startTime: Date.now(),
}
const WEBPACK_INVALIDATED_EVENT = {
name: 'webpa... | t reporter.flushAll()
const traceFilename = join(tmpDir, 'trace')
const traces = JSON.parse(await readFile(traceFilename, 'utf-8'))
expect(traces.length).toEqual(1)
expect(traces[0].name).toEqual('test-span')
expect(traces[0]. | e trace events to JSON file', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'json-reporter'))
setGlobal('distDir', tmpDir)
setGlobal('phase', 'anything')
reporter.report(TRACE_EVENT)
awai | {
"filepath": "packages/next/src/trace/report/index.test.ts",
"language": "typescript",
"file_size": 1784,
"cut_index": 537,
"middle_length": 229
} |
iring any module, we need to make
* sure the following scripts are executed in the correct order:
* - Polyfills
* - next/script with `beforeInteractive` strategy
*/
import { getAssetPrefix } from './asset-prefix'
import { setAttributesFromProps } from './set-attributes-from-props'
const version = process.env.__NE... | teElement('script')
if (props) {
setAttributesFromProps(el, props)
}
if (src) {
el.src = src
el.onload = () => resolve()
el.onerror = reject
} else if (props) {
| | !scripts.length) {
return hydrate()
}
return scripts
.reduce((promise, [src, props]) => {
return promise.then(() => {
return new Promise<void>((resolve, reject) => {
const el = document.crea | {
"filepath": "packages/next/src/client/app-bootstrap.ts",
"language": "typescript",
"file_size": 2255,
"cut_index": 563,
"middle_length": 229
} |
from 'fs'
import { italic } from '../lib/picocolors'
import build from '../build'
import { warn } from '../build/output/log'
import { printAndExit } from '../server/lib/utils'
import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir'
import { enableMemoryDebuggingMode } from '../lib/m... | n
webpack?: boolean
experimentalDebugMemoryUsage: boolean
experimentalAppOnly?: boolean
experimentalTurbo?: boolean
experimentalBuildMode: 'default' | 'compile' | 'generate' | 'generate-env'
experimentalUploadTrace?: string
experimentalNextCo | ut,
} from '../lib/resolve-build-paths'
export type NextBuildOptions = {
experimentalAnalyze?: boolean
debug?: boolean
debugPrerender?: boolean
profile?: boolean
mangling: boolean
turbo?: boolean
turbopack?: boolea | {
"filepath": "packages/next/src/cli/next-build.ts",
"language": "typescript",
"file_size": 4891,
"cut_index": 614,
"middle_length": 229
} |
TION_BUILD } from '../shared/lib/constants'
import {
hasNecessaryDependencies,
type MissingDependency,
} from '../lib/has-necessary-dependencies'
import { installDependencies } from '../lib/install-dependencies'
import type { NextConfigComplete } from '../server/config-shared'
import findUp from 'next/dist/compiled... | nst requiredPackagesByTestRunner: {
[k in SupportedTestRunners]: MissingDependency[]
} = {
playwright: [
{ file: 'playwright', pkg: '@playwright/test', exportsRestrict: false },
],
}
export async function nextTest(
directory?: string,
testRu | iled/cross-spawn'
export interface NextTestOptions {
testRunner?: string
}
export const SUPPORTED_TEST_RUNNERS_LIST = ['playwright'] as const
export type SupportedTestRunners = (typeof SUPPORTED_TEST_RUNNERS_LIST)[number]
co | {
"filepath": "packages/next/src/cli/next-test.ts",
"language": "typescript",
"file_size": 7205,
"cut_index": 716,
"middle_length": 229
} |
Buffer.from('{"nodes":')
// Turbopack trace files start with this magic header (written by trace_writer.rs)
const TURBOPACK_TRACE_HEADER = Buffer.from('TRACEv0')
const PROGRESS_CHUNK_SIZE = 64 * 1024 // 64 KB
export interface UploadTraceOptions {
directory?: string
}
function getUploadUrl(): string {
return pro... | = Math.round(width * ratio)
const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(width - filled)
const percent = (ratio * 100).toFixed(0).padStart(3)
return ` [${bar}] ${percent}% ${formatBytes(current)}/${formatBytes(total)}`
}
function createPr | es / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
function renderProgressBar(current: number, total: number): string {
const width = 30
const ratio = Math.min(current / total, 1)
const filled | {
"filepath": "packages/next/src/cli/internal/upload-trace.ts",
"language": "typescript",
"file_size": 5958,
"cut_index": 716,
"middle_length": 229
} |
lib/router/utils/remove-trailing-slash'
import { parsePath } from '../shared/lib/router/utils/parse-path'
/**
* Normalizes the trailing slash of a path according to the `trailingSlash` option
* in `next.config.js`.
*/
export const normalizePathTrailingSlash = (path: string) => {
// 47 is the char code for '/'
i... | `${removeTrailingSlash(pathname)}${query}${hash}`
} else if (pathname.endsWith('/')) {
return `${pathname}${query}${hash}`
} else {
return `${pathname}/${query}${hash}`
}
}
return `${removeTrailingSlash(pathname)}${query}${has | if (/\.[^/]+\/?$/.test(pathname)) {
return | {
"filepath": "packages/next/src/client/normalize-trailing-slash.ts",
"language": "typescript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
import { useRouter } from './router'
const nextjsRouteAnnouncerStyles: React.CSSProperties = {
border: 0,
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
top: 0,
width: '1px',
// https://medium.com/@jessebeach/beware-smushed-off-screen-a... | es, announce the new page’s title following this
// priority: first the document title (from head), otherwise the first h1, or
// if none of these exist, then the pathname from the URL. This methodology is
// inspired by Marcy Sutton’s accessible cli | ment] = React.useState('')
// Only announce the path change, but not for the first load because screen
// reader will do that automatically.
const previouslyLoadedPath = React.useRef(asPath)
// Every time the path chang | {
"filepath": "packages/next/src/client/route-announcer.tsx",
"language": "tsx",
"file_size": 1998,
"cut_index": 537,
"middle_length": 229
} |
bals } from '../trace/shared'
import type { ExportAppResult } from '../export/types'
import type { FetchMetrics } from '../server/base-http'
const DIAGNOSTICS_DIR = 'diagnostics'
const DIAGNOSTICS_FILE = 'build-diagnostics.json'
const FETCH_METRICS_FILE = 'fetch-metrics.json'
const INCREMENTAL_BUILDS_FILE = 'increment... | etDiagnosticsDir(): Promise<string> {
const distDir = traceGlobals.get('distDir')
const diagnosticsDir = join(distDir, DIAGNOSTICS_DIR)
await mkdir(diagnosticsDir, { recursive: true })
return diagnosticsDir
}
/**
* Saves the exact version of Next | rogresses so it's what stage the build was in when an error
// happened.
buildStage?: string
// Additional debug information about the configuration for the build.
buildOptions?: Record<string, string>
}
async function g | {
"filepath": "packages/next/src/diagnostics/build-diagnostics.ts",
"language": "typescript",
"file_size": 4011,
"cut_index": 614,
"middle_length": 229
} |
ceId } from './shared'
import { Telemetry } from '../telemetry/storage'
export default function uploadTrace({
traceUploadUrl,
mode,
projectDir,
distDir,
isTurboSession,
sync,
}: {
traceUploadUrl: string
mode: 'dev' | 'build'
projectDir: string
distDir: string
isTurboSession: boolean
sync?: bool... | NEXT_TRACE_UPLOAD_DEBUG || sync
? child_process.spawnSync
: child_process.spawn
spawn(
process.execPath,
[
require.resolve('./trace-uploader'),
traceUploadUrl,
mode,
projectDir,
distDir,
String(i | ear when we don't want it to
const child_process =
require('child_process') as typeof import('child_process')
// we use spawnSync when debugging to ensure logs are piped
// correctly to stdout/stderr
const spawn =
| {
"filepath": "packages/next/src/trace/upload-trace.ts",
"language": "typescript",
"file_size": 1311,
"cut_index": 524,
"middle_length": 229
} |
basePath = process.env.__NEXT_ROUTER_BASEPATH || ''
const pathname = `${basePath}/__nextjs_source-map`
export const findSourceMapURL =
// Source maps are only served by the dev server.
process.env.__NEXT_DEV_SERVER
? function findSourceMapURL(filename: string): string | null {
if (filename === '') {
... | o the filename, with an added `.map` extension. The
// browser can just request this file, and it gets served through the
// normal dev server, without the need to route this through
// the `/__nextjs_source-map` dev middlewar | or a client chunk. This can only happen when
// using Turbopack. In this case, since we control how those source
// maps are generated, we can safely assume that the sourceMappingURL
// is relative t | {
"filepath": "packages/next/src/client/app-find-source-map-url.ts",
"language": "typescript",
"file_size": 1216,
"cut_index": 518,
"middle_length": 229
} |
---------------------------------------------------
/**
* The 6 file categories we partition each route's files into. Each file is
* placed into exactly one category to avoid double-counting.
*
* To add a new category, extend this tuple, add a label below, and update
* the relevant collector(s).
*/
const CATEGOR... | Unbundled: 'Server Unbundled',
serverMaps: 'Server Source Maps',
}
/**
* Per-route file sets, one entry per category.
*
* Paths are stored either relative to `distDir` (for files that live inside
* the build output) or as absolute paths (for files t | itles, in the same order as CATEGORIES. */
const CATEGORY_LABELS: Record<Category, string> = {
clientJs: 'Client JS',
clientCss: 'Client CSS',
clientMaps: 'Client Source Maps',
serverBundled: 'Server Bundled JS',
server | {
"filepath": "packages/next/src/cli/internal/static-routes-info.ts",
"language": "typescript",
"file_size": 42594,
"cut_index": 2151,
"middle_length": 229
} |
from '../shared/lib/router/utils/querystring'
import { formatWithValidation } from '../shared/lib/router/utils/format-url'
import { omit } from '../shared/lib/router/utils/omit'
import { normalizeRepeatedSlashes } from '../shared/lib/utils'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'
import ... | cluded).
* Preserves absolute urls.
*/
export function resolveHref(
router: NextRouter,
href: Url,
resolveAs: true
): [string, string] | [string]
export function resolveHref(
router: NextRouter,
href: Url,
resolveAs?: false
): string
export f | as'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
/**
* Resolves a given hyperlink with a certain router state (basePath not in | {
"filepath": "packages/next/src/client/resolve-href.ts",
"language": "typescript",
"file_size": 4952,
"cut_index": 614,
"middle_length": 229
} |
port { traceGlobals } from '../shared'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
import { createJsonReporter } from './to-json'
const allowlistedEvents = new Set([
'next-build',
'run-turbopack',
'run-webpack',
'run-typescript',
'run-eslint',
'static-check',
'collect-build-traces... | pack-compaction',
])
export default createJsonReporter({
filename: 'trace-build',
sizeLimit: Infinity,
filter: (event) => {
const phase = traceGlobals.get('phase')
return phase === PHASE_PRODUCTION_BUILD && allowlistedEvents.has(event.name)
| nce',
'turbo | {
"filepath": "packages/next/src/trace/report/to-json-build.ts",
"language": "typescript",
"file_size": 792,
"cut_index": 514,
"middle_length": 14
} |
ny` type.
import './register-deployment-id-global'
import { initialize, version, router, emitter } from './'
import initHMR from './dev/hot-middleware-client'
import { pageBootstrap } from './page-bootstrap'
//@ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension
import { connec... | // for the page loader
declare let __turbopack_load__: any
const devClient = initHMR()
initialize({
devClient,
})
.then(({ assetPrefix }) => {
// for the page loader
;(self as any).__turbopack_load_page_chunks__ = (
page: string,
c | rsion,
turbopack: true,
// router is initialized later so it has to be live-binded
get router() {
return router
},
emitter,
}
;(self as any).__next_set_public_path__ = () => {}
;(self as any).__webpack_hash__ = ''
| {
"filepath": "packages/next/src/client/next-dev-turbopack.ts",
"language": "typescript",
"file_size": 1656,
"cut_index": 537,
"middle_length": 229
} |
b.com/facebook/react/blob/b565373afd0cc1988497e1107106e851e8cfb261/packages/react-dom-bindings/src/shared/sanitizeURL.js
// A javascript: URL can contain leading C0 control or \u0020 SPACE,
// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab ... | -space
const isJavaScriptProtocol =
// eslint-disable-next-line no-control-regex
/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i
export function isJavaScriptURLString(url: str | ive:
// https://infra.spec.whatwg.org/#c0-control-or | {
"filepath": "packages/next/src/client/lib/javascript-url.ts",
"language": "typescript",
"file_size": 976,
"cut_index": 582,
"middle_length": 52
} |
{ PromiseQueue } from './promise-queue'
describe('PromiseQueue', () => {
it('should limit the number of concurrent promises', async () => {
const queue = new PromiseQueue(2)
const results: number[] = []
const promises = Array.from({ length: 5 }, (_, i) =>
queue.enqueue(async () => {
resul... | s = Array.from({ length: 5 }, (_, i) =>
queue.enqueue(async () => {
results.push(i)
await new Promise((resolve) => setTimeout(resolve, 100))
return i
})
)
queue.bump(promises[3])
const resolved = await Prom | 1, 2, 3, 4])
expect(results).toEqual([0, 1, 2, 3, 4])
})
it('should allow bumping a promise to be next in the queue', async () => {
const queue = new PromiseQueue(2)
const results: number[] = []
const promise | {
"filepath": "packages/next/src/client/components/promise-queue.test.ts",
"language": "typescript",
"file_size": 1213,
"cut_index": 518,
"middle_length": 229
} |
romise queue that allows you to limit the number of concurrent promises
that are running at any given time. It's used to limit the number of concurrent
prefetch requests that are being made to the server but could be used for other
things as well.
*/
export class PromiseQueue {
#maxConcurrency: number
#... | solve, reject) => {
taskResolve = resolve
taskReject = reject
}) as Promise<T>
const task = async () => {
try {
this.#runningCount++
const result = await promiseFn()
taskResolve(result)
} catch (erro | nt = 0
this.#queue = []
}
enqueue<T>(promiseFn: () => Promise<T>): Promise<T> {
let taskResolve: (value: T | PromiseLike<T>) => void
let taskReject: (reason?: any) => void
const taskPromise = new Promise((re | {
"filepath": "packages/next/src/client/components/promise-queue.ts",
"language": "typescript",
"file_size": 1805,
"cut_index": 537,
"middle_length": 229
} |
arams implementation shared between client and server.
* This file is intentionally not marked as 'use client' or 'use server'
* so it can be imported by both environments.
*/
/** @internal */
class ReadonlyURLSearchParamsError extends Error {
constructor() {
super(
'Method unavailable on `ReadonlyURLSe... | e on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */
append() {
throw new ReadonlyURLSearchParamsError()
}
/** @deprecated Method unavailable on `ReadonlyURLSear | rs when mutation methods are called.
* This ensures that the URLSearchParams returned by useSearchParams() cannot be mutated.
*/
export class ReadonlyURLSearchParams extends URLSearchParams {
/** @deprecated Method unavailabl | {
"filepath": "packages/next/src/client/components/readonly-url-search-params.ts",
"language": "typescript",
"file_size": 1668,
"cut_index": 537,
"middle_length": 229
} |
t'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { useRouter } from './navigation'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { type RedirectType, isRedirectError } from './redirect-error'
interface RedirectBoundaryProps {
... | reset()
})
}, [redirect, redirectType, reset, router])
return null
}
export class RedirectErrorBoundary extends React.Component<
RedirectBoundaryProps,
{ redirect: string | null; redirectType: RedirectType | null }
> {
constructor(props: Re | id
}) {
const router = useRouter()
useEffect(() => {
React.startTransition(() => {
if (redirectType === 'push') {
router.push(redirect, {})
} else {
router.replace(redirect, {})
}
| {
"filepath": "packages/next/src/client/components/redirect-boundary.tsx",
"language": "tsx",
"file_size": 2457,
"cut_index": 563,
"middle_length": 229
} |
{ RedirectStatusCode } from './redirect-status-code'
export const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'
export type RedirectType = 'push' | 'replace'
export type RedirectError = Error & {
digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`
}
/**
* Checks an error to determin... | gest = error.digest.split(';')
const [errorCode, type] = digest
const destination = digest.slice(2, -2).join(';')
const status = digest.at(-2)
const statusCode = Number(status)
return (
errorCode === REDIRECT_ERROR_CODE &&
(type === 're | ction isRedirectError(error: unknown): error is RedirectError {
if (
typeof error !== 'object' ||
error === null ||
!('digest' in error) ||
typeof error.digest !== 'string'
) {
return false
}
const di | {
"filepath": "packages/next/src/client/components/redirect-error.ts",
"language": "typescript",
"file_size": 1141,
"cut_index": 518,
"middle_length": 229
} |
ectError,
isRedirectError,
REDIRECT_ERROR_CODE,
} from './redirect-error'
const actionAsyncStorage =
typeof window === 'undefined'
? (
require('../../server/app-render/action-async-storage.external') as typeof import('../../server/app-render/action-async-storage.external')
).actionAsyncStorage
... | * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),
* [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app | = new Error(REDIRECT_ERROR_CODE) as RedirectError
error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`
return error
}
/**
* This function allows you to redirect the user to another URL. It can be used in
| {
"filepath": "packages/next/src/client/components/redirect.ts",
"language": "typescript",
"file_size": 3731,
"cut_index": 614,
"middle_length": 229
} |
TTP_ERROR_FALLBACK_ERROR_CODE,
type HTTPAccessFallbackError,
} from './http-access-fallback/http-access-fallback'
// TODO: Add `unauthorized` docs
/**
* @experimental
* This function allows you to render the [unauthorized.js file](https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized)
* within a... | more: [Next.js Docs: `unauthorized`](https://nextjs.org/docs/app/api-reference/functions/unauthorized)
*/
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`
export function unauthorized(): never {
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUP | te Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and
* [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
*
*
* Read | {
"filepath": "packages/next/src/client/components/unauthorized.ts",
"language": "typescript",
"file_size": 1298,
"cut_index": 524,
"middle_length": 229
} |
args: ConstructorParameters<typeof Error>) {
super(...args)
this.name = 'UnrecognizedActionError'
}
}
/**
* Check whether a server action call failed because the server action was not recognized by the server.
* This can happen if the client and the server are not from the same deployment.
*
* Example us... |
* window.alert("Please refresh the page and try again");
* return;
* }
* }
* ```
* */
export function unstable_isUnrecognizedActionError(
error: unknown
): error is UnrecognizedActionError {
return !!(
error &&
typeof error === | * // Reloading the page will fix this mismatch. | {
"filepath": "packages/next/src/client/components/unrecognized-action-error.ts",
"language": "typescript",
"file_size": 954,
"cut_index": 582,
"middle_length": 52
} |
rror } from '../../server/dynamic-rendering-utils'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error'
import {
isDynamicPostpone,
isPrerenderInterruptedEr... | ) ||
isDynamicServerError(error) ||
isDynamicPostpone(error) ||
isPostpone(error) ||
isHangingPromiseRejectionError(error) ||
isPrerenderInterruptedError(error)
) {
throw error
}
if (error instanceof Error && 'cause' in error | tRouterError(error) ||
isBailoutToCSRError(error | {
"filepath": "packages/next/src/client/components/unstable-rethrow.server.ts",
"language": "typescript",
"file_size": 899,
"cut_index": 547,
"middle_length": 52
} |
* This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.
* When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.
* This function will rethrow the error if it is a Next.js error so it can be... | window === 'undefined'
? (
require('./unstable-rethrow.server') as typeof import('./unstable-rethrow.server')
).unstable_rethrow
: (
require('./unstable-rethrow.browser') as typeof import('./unstable-rethrow.browser')
) | row =
typeof | {
"filepath": "packages/next/src/client/components/unstable-rethrow.ts",
"language": "typescript",
"file_size": 805,
"cut_index": 517,
"middle_length": 14
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.