Unverified Commit 18e07cf4 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Conditionally load uncommon paths (#90514)

## What?

No changes in functionality. Just skips requiring modules that are not
used in the common hot path of builds.

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 5fa40c80
import type { NextConfig } from '../../server/config-shared' import type { NextConfig } from '../../server/config-shared'
import type { RouteHas } from '../../lib/load-custom-routes' import type { RouteHas } from '../../lib/load-custom-routes'
import { promises as fs } from 'fs' import { readFileSync } from 'fs'
import { relative } from 'path' import { relative } from 'path'
import { LRUCache } from '../../server/lib/lru-cache' import { LRUCache } from '../../server/lib/lru-cache'
import { import {
...@@ -427,9 +427,9 @@ function validateMiddlewareProxyExports({ ...@@ -427,9 +427,9 @@ function validateMiddlewareProxyExports({
} }
} }
async function tryToReadFile(filePath: string, shouldThrow: boolean) { function tryToReadFile(filePath: string, shouldThrow: boolean) {
try { try {
return await fs.readFile(filePath, { return readFileSync(filePath, {
encoding: 'utf8', encoding: 'utf8',
}) })
} catch (error: any) { } catch (error: any) {
...@@ -615,7 +615,7 @@ export async function getAppPageStaticInfo({ ...@@ -615,7 +615,7 @@ export async function getAppPageStaticInfo({
isDev, isDev,
page, page,
}: GetPageStaticInfoParams): Promise<AppPageStaticInfo> { }: GetPageStaticInfoParams): Promise<AppPageStaticInfo> {
const content = await tryToReadFile(pageFilePath, !isDev) const content = tryToReadFile(pageFilePath, !isDev)
if (!content || !PARSE_PATTERN.test(content)) { if (!content || !PARSE_PATTERN.test(content)) {
return { return {
type: PAGE_TYPES.APP, type: PAGE_TYPES.APP,
...@@ -718,7 +718,7 @@ export async function getPagesPageStaticInfo({ ...@@ -718,7 +718,7 @@ export async function getPagesPageStaticInfo({
isDev, isDev,
page, page,
}: GetPageStaticInfoParams): Promise<PagesPageStaticInfo> { }: GetPageStaticInfoParams): Promise<PagesPageStaticInfo> {
const content = await tryToReadFile(pageFilePath, !isDev) const content = tryToReadFile(pageFilePath, !isDev)
if (!content || !PARSE_PATTERN.test(content)) { if (!content || !PARSE_PATTERN.test(content)) {
return { return {
type: PAGE_TYPES.PAGES, type: PAGE_TYPES.PAGES,
......
import browserslist from 'next/dist/compiled/browserslist'
import { MODERN_BROWSERSLIST_TARGET } from '../shared/lib/constants'
export function getSupportedBrowsers(
dir: string,
isDevelopment: boolean
): string[] {
let browsers: any
try {
const browsersListConfig = browserslist.loadConfig({
path: dir,
env: isDevelopment ? 'development' : 'production',
})
// Running `browserslist` resolves `extends` and other config features into a list of browsers
if (browsersListConfig && browsersListConfig.length > 0) {
browsers = browserslist(browsersListConfig)
}
} catch {}
// When user has browserslist use that target
if (browsers && browsers.length > 0) {
return browsers
}
// Uses modern browsers as the default.
return MODERN_BROWSERSLIST_TARGET
}
...@@ -196,7 +196,6 @@ import { HTML_LIMITED_BOT_UA_RE_STRING } from '../shared/lib/router/utils/is-bot ...@@ -196,7 +196,6 @@ import { HTML_LIMITED_BOT_UA_RE_STRING } from '../shared/lib/router/utils/is-bot
import type { UseCacheTrackerKey } from './webpack/plugins/telemetry-plugin/use-cache-tracker-utils' import type { UseCacheTrackerKey } from './webpack/plugins/telemetry-plugin/use-cache-tracker-utils'
import { turbopackBuild } from './turbopack-build' import { turbopackBuild } from './turbopack-build'
import { isFileSystemCacheEnabledForBuild } from '../shared/lib/turbopack/utils'
import { inlineStaticEnv } from '../lib/inline-static-env' import { inlineStaticEnv } from '../lib/inline-static-env'
import { populateStaticEnv } from '../lib/static-env' import { populateStaticEnv } from '../lib/static-env'
import { durationToString, hrtimeDurationToString } from './duration-to-string' import { durationToString, hrtimeDurationToString } from './duration-to-string'
...@@ -2694,7 +2693,9 @@ export default async function build( ...@@ -2694,7 +2693,9 @@ export default async function build(
}, },
{ {
featureName: 'turbopackFileSystemCache', featureName: 'turbopackFileSystemCache',
invocationCount: isFileSystemCacheEnabledForBuild(config) ? 1 : 0, invocationCount: config.experimental?.turbopackFileSystemCacheForBuild
? 1
: 0,
}, },
] ]
telemetry.record( telemetry.record(
......
import { formatIssue, isRelevantWarning } from '../shared/lib/turbopack/utils'
import type { TurbopackResult } from './swc/types'
/**
* Processes and reports build issues from Turbopack entrypoints.
*
* @param entrypoints - The result object containing build issues to process.
* @param isDev - A flag indicating if the build is running in development mode.
* @return This function does not return a value but logs or throws errors based on the issues.
* @throws {Error} If a fatal issue is encountered, this function throws an error. In development mode, we only throw on
* 'fatal' and 'bug' issues. In production mode, we also throw on 'error' issues.
*/
export function printBuildErrors(
entrypoints: TurbopackResult,
isDev: boolean
): void {
// Issues that we want to stop the server from executing
const topLevelFatalIssues = []
// Issues that are true errors, but we believe we can keep running and allow the user to address the issue
const topLevelErrors = []
// Issues that are warnings but should not affect the running of the build
const topLevelWarnings = []
// Track seen formatted error messages to avoid duplicates
const seenFatalIssues = new Set<string>()
const seenErrors = new Set<string>()
const seenWarnings = new Set<string>()
for (const issue of entrypoints.issues) {
// We only want to completely shut down the server
if (issue.severity === 'fatal' || issue.severity === 'bug') {
const formatted = formatIssue(issue)
if (!seenFatalIssues.has(formatted)) {
seenFatalIssues.add(formatted)
topLevelFatalIssues.push(formatted)
}
} else if (isRelevantWarning(issue)) {
const formatted = formatIssue(issue)
if (!seenWarnings.has(formatted)) {
seenWarnings.add(formatted)
topLevelWarnings.push(formatted)
}
} else if (issue.severity === 'error') {
const formatted = formatIssue(issue)
if (isDev) {
// We want to treat errors as recoverable in development
// so that we can show the errors in the site and allow users
// to respond to the errors when necessary. In production builds
// though we want to error out and stop the build process.
if (!seenErrors.has(formatted)) {
seenErrors.add(formatted)
topLevelErrors.push(formatted)
}
} else {
if (!seenFatalIssues.has(formatted)) {
seenFatalIssues.add(formatted)
topLevelFatalIssues.push(formatted)
}
}
}
}
// TODO: print in order by source location so issues from the same file are displayed together and then add a summary at the end about the number of warnings/errors
if (topLevelWarnings.length > 0) {
console.warn(
`Turbopack build encountered ${
topLevelWarnings.length
} warnings:\n${topLevelWarnings.join('\n')}`
)
}
if (topLevelErrors.length > 0) {
console.error(
`Turbopack build encountered ${
topLevelErrors.length
} errors:\n${topLevelErrors.join('\n')}`
)
}
if (topLevelFatalIssues.length > 0) {
throw new Error(
`Turbopack build failed with ${
topLevelFatalIssues.length
} errors:\n${topLevelFatalIssues.join('\n')}`
)
}
}
...@@ -3,10 +3,6 @@ import { pathToFileURL } from 'url' ...@@ -3,10 +3,6 @@ import { pathToFileURL } from 'url'
import { arch, platform } from 'os' import { arch, platform } from 'os'
import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples' import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples'
import * as Log from '../output/log' import * as Log from '../output/log'
import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type { import type {
NextConfigComplete, NextConfigComplete,
TurbopackLoaderBuiltinCondition, TurbopackLoaderBuiltinCondition,
...@@ -15,7 +11,6 @@ import type { ...@@ -15,7 +11,6 @@ import type {
TurbopackRuleConfigCollection, TurbopackRuleConfigCollection,
TurbopackRuleConfigItem, TurbopackRuleConfigItem,
} from '../../server/config-shared' } from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import { type DefineEnvOptions, getDefineEnv } from '../define-env' import { type DefineEnvOptions, getDefineEnv } from '../define-env'
import type { import type {
NapiPartialProjectOptions, NapiPartialProjectOptions,
...@@ -42,7 +37,6 @@ import type { ...@@ -42,7 +37,6 @@ import type {
UpdateMessage, UpdateMessage,
WrittenEndpoint, WrittenEndpoint,
} from './types' } from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
import { runLoaderWorkerPool } from './loaderWorkerPool' import { runLoaderWorkerPool } from './loaderWorkerPool'
export enum HmrTarget { export enum HmrTarget {
...@@ -236,9 +230,11 @@ export async function loadBindings( ...@@ -236,9 +230,11 @@ export async function loadBindings(
if (!lockfilePatchPromise.cur) { if (!lockfilePatchPromise.cur) {
// always run lockfile check once so that it gets patched // always run lockfile check once so that it gets patched
// even if it doesn't fail to load locally // even if it doesn't fail to load locally
lockfilePatchPromise.cur = patchIncorrectLockfile(process.cwd()).catch( lockfilePatchPromise.cur = (
console.error require('../../lib/patch-incorrect-lockfile') as typeof import('../../lib/patch-incorrect-lockfile')
) )
.patchIncorrectLockfile(process.cwd())
.catch(console.error)
} }
let attempts: any[] = [] let attempts: any[] = []
...@@ -322,7 +318,9 @@ async function tryLoadNativeWithFallback(attempts: Array<string>) { ...@@ -322,7 +318,9 @@ async function tryLoadNativeWithFallback(attempts: Array<string>) {
) )
if (!downloadNativeBindingsPromise) { if (!downloadNativeBindingsPromise) {
downloadNativeBindingsPromise = downloadNativeNextSwc( downloadNativeBindingsPromise = (
require('../../lib/download-swc') as typeof import('../../lib/download-swc')
).downloadNativeNextSwc(
nextVersion, nextVersion,
nativeBindingsDirectory, nativeBindingsDirectory,
triples.map((triple: any) => triple.platformArchABI) triples.map((triple: any) => triple.platformArchABI)
...@@ -345,8 +343,9 @@ async function tryLoadWasmWithFallback( ...@@ -345,8 +343,9 @@ async function tryLoadWasmWithFallback(
): Promise<Binding | undefined> { ): Promise<Binding | undefined> {
try { try {
let bindings = await loadWasm('') let bindings = await loadWasm('')
// @ts-expect-error TODO: this event has a wrong type. ;(
eventSwcLoadFailure({ require('../../telemetry/events/swc-load-failure') as typeof import('../../telemetry/events/swc-load-failure')
).eventSwcLoadFailure({
wasm: 'enabled', wasm: 'enabled',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
}) })
...@@ -365,12 +364,15 @@ async function tryLoadWasmWithFallback( ...@@ -365,12 +364,15 @@ async function tryLoadWasmWithFallback(
'wasm' 'wasm'
) )
if (!downloadWasmPromise) { if (!downloadWasmPromise) {
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory) downloadWasmPromise = (
require('../../lib/download-swc') as typeof import('../../lib/download-swc')
).downloadWasmSwc(nextVersion, wasmDirectory)
} }
await downloadWasmPromise await downloadWasmPromise
let bindings = await loadWasm(wasmDirectory) let bindings = await loadWasm(wasmDirectory)
// @ts-expect-error TODO: this event has a wrong type. ;(
eventSwcLoadFailure({ require('../../telemetry/events/swc-load-failure') as typeof import('../../telemetry/events/swc-load-failure')
).eventSwcLoadFailure({
wasm: 'fallback', wasm: 'fallback',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
}) })
...@@ -418,8 +420,9 @@ async function logLoadFailure(attempts: any, triedWasm = false) { ...@@ -418,8 +420,9 @@ async function logLoadFailure(attempts: any, triedWasm = false) {
Log.warn(attempt) Log.warn(attempt)
} }
// @ts-expect-error TODO: this event has a wrong type. await (
await eventSwcLoadFailure({ require('../../telemetry/events/swc-load-failure') as typeof import('../../telemetry/events/swc-load-failure')
).eventSwcLoadFailure({
wasm: triedWasm ? 'failed' : undefined, wasm: triedWasm ? 'failed' : undefined,
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
}) })
...@@ -1130,7 +1133,10 @@ function bindingToApi( ...@@ -1130,7 +1133,10 @@ function bindingToApi(
function checkLoaderItem(loaderItem: TurbopackLoaderItem, glob: string) { function checkLoaderItem(loaderItem: TurbopackLoaderItem, glob: string) {
if ( if (
typeof loaderItem !== 'string' && typeof loaderItem !== 'string' &&
!isDeepStrictEqual(loaderItem, JSON.parse(JSON.stringify(loaderItem))) !(require('util') as typeof import('util')).isDeepStrictEqual(
loaderItem,
JSON.parse(JSON.stringify(loaderItem))
)
) { ) {
throw new Error( throw new Error(
`loader ${loaderItem.loader} for match "${glob}" does not have serializable options. ` + `loader ${loaderItem.loader} for match "${glob}" does not have serializable options. ` +
...@@ -1234,7 +1240,9 @@ function bindingToApi( ...@@ -1234,7 +1240,9 @@ function bindingToApi(
await rustifyProjectOptions(options), await rustifyProjectOptions(options),
turboEngineOptions || {}, turboEngineOptions || {},
{ {
throwTurbopackInternalError, throwTurbopackInternalError: (
require('../../shared/lib/turbopack/internal-error') as typeof import('../../shared/lib/turbopack/internal-error')
).throwTurbopackInternalError,
onBeforeDeferredEntries: callbacks?.onBeforeDeferredEntries, onBeforeDeferredEntries: callbacks?.onBeforeDeferredEntries,
} }
) )
...@@ -1727,7 +1735,9 @@ export function isReactCompilerRequired(filename: string): Promise<boolean> { ...@@ -1727,7 +1735,9 @@ export function isReactCompilerRequired(filename: string): Promise<boolean> {
export async function parse(src: string, options: any): Promise<any> { export async function parse(src: string, options: any): Promise<any> {
const bindings = getBindingsSync() const bindings = getBindingsSync()
const parserOptions = getParserOptions(options) const parserOptions = (
require('./options') as typeof import('./options')
).getParserOptions(options)
const parsed = await bindings.parse(src, parserOptions) const parsed = await bindings.parse(src, parserOptions)
return JSON.parse(parsed) return JSON.parse(parsed)
} }
......
...@@ -3,11 +3,10 @@ import type { __ApiPreviewProps } from '../../server/api-utils' ...@@ -3,11 +3,10 @@ import type { __ApiPreviewProps } from '../../server/api-utils'
import path from 'path' import path from 'path'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils'
import { createDefineEnv, loadBindings } from '../swc' import { createDefineEnv, loadBindings } from '../swc'
import { isCI } from '../../server/ci-info' import { isCI } from '../../server/ci-info'
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events' import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers } from '../utils' import { getSupportedBrowsers } from '../get-supported-browsers'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants' import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
...@@ -48,7 +47,8 @@ export async function turbopackAnalyze( ...@@ -48,7 +47,8 @@ export async function turbopackAnalyze(
const supportedBrowsers = getSupportedBrowsers(dir, dev) const supportedBrowsers = getSupportedBrowsers(dir, dev)
const persistentCaching = isFileSystemCacheEnabledForBuild(config) const persistentCaching =
config.experimental?.turbopackFileSystemCacheForBuild || false
const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir
const project = await bindings.turbo.createProject( const project = await bindings.turbo.createProject(
{ {
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
import { saveCpuProfile } from '../../server/lib/cpu-profile' import { saveCpuProfile } from '../../server/lib/cpu-profile'
import path from 'path' import path from 'path'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils'
import { NextBuildContext } from '../build-context' import { NextBuildContext } from '../build-context'
import { createDefineEnv, getBindingsSync } from '../swc' import { createDefineEnv, getBindingsSync } from '../swc'
import { installBindings } from '../swc/install-bindings' import { installBindings } from '../swc/install-bindings'
...@@ -19,7 +18,8 @@ import { Telemetry } from '../../telemetry/storage' ...@@ -19,7 +18,8 @@ import { Telemetry } from '../../telemetry/storage'
import { setGlobal } from '../../trace' import { setGlobal } from '../../trace'
import { isCI } from '../../server/ci-info' import { isCI } from '../../server/ci-info'
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events' import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers, printBuildErrors } from '../utils' import { getSupportedBrowsers } from '../get-supported-browsers'
import { printBuildErrors } from '../print-build-errors'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import type { import type {
ProjectOptions, ProjectOptions,
...@@ -69,7 +69,8 @@ export async function turbopackBuild(): Promise<{ ...@@ -69,7 +69,8 @@ export async function turbopackBuild(): Promise<{
const hasDeferredEntries = const hasDeferredEntries =
(config.experimental.deferredEntries?.length ?? 0) > 0 (config.experimental.deferredEntries?.length ?? 0) > 0
const persistentCaching = isFileSystemCacheEnabledForBuild(config) const persistentCaching =
config.experimental?.turbopackFileSystemCacheForBuild || false
const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir
// Shared options for createProject calls // Shared options for createProject calls
......
...@@ -44,9 +44,7 @@ import path from 'path' ...@@ -44,9 +44,7 @@ import path from 'path'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { isValidElementType } from 'next/dist/compiled/react-is' import { isValidElementType } from 'next/dist/compiled/react-is'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import browserslist from 'next/dist/compiled/browserslist'
import { import {
MODERN_BROWSERSLIST_TARGET,
UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE,
...@@ -80,8 +78,6 @@ import type { ...@@ -80,8 +78,6 @@ import type {
AppRouteModule, AppRouteModule,
AppRouteRouteModule, AppRouteRouteModule,
} from '../server/route-modules/app-route/module' } from '../server/route-modules/app-route/module'
import { formatIssue, isRelevantWarning } from '../shared/lib/turbopack/utils'
import type { TurbopackResult } from './swc/types'
import type { FunctionsConfigManifest, ManifestRoute } from './index' import type { FunctionsConfigManifest, ManifestRoute } from './index'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { parseAppRoute } from '../shared/lib/router/routes/app' import { parseAppRoute } from '../shared/lib/router/routes/app'
...@@ -233,91 +229,6 @@ export function collectRoutesUsingEdgeRuntime( ...@@ -233,91 +229,6 @@ export function collectRoutesUsingEdgeRuntime(
return routesUsingEdgeRuntime return routesUsingEdgeRuntime
} }
/**
* Processes and categorizes build issues, then logs them as warnings, errors, or fatal errors.
* Stops execution if fatal issues are encountered.
*
* @param entrypoints - The result object containing build issues to process.
* @param isDev - A flag indicating if the build is running in development mode.
* @return This function does not return a value but logs or throws errors based on the issues.
* @throws {Error} If a fatal issue is encountered, this function throws an error. In development mode, we only throw on
* 'fatal' and 'bug' issues. In production mode, we also throw on 'error' issues.
*/
export function printBuildErrors(
entrypoints: TurbopackResult,
isDev: boolean
): void {
// Issues that we want to stop the server from executing
const topLevelFatalIssues = []
// Issues that are true errors, but we believe we can keep running and allow the user to address the issue
const topLevelErrors = []
// Issues that are warnings but should not affect the running of the build
const topLevelWarnings = []
// Track seen formatted error messages to avoid duplicates
const seenFatalIssues = new Set<string>()
const seenErrors = new Set<string>()
const seenWarnings = new Set<string>()
for (const issue of entrypoints.issues) {
// We only want to completely shut down the server
if (issue.severity === 'fatal' || issue.severity === 'bug') {
const formatted = formatIssue(issue)
if (!seenFatalIssues.has(formatted)) {
seenFatalIssues.add(formatted)
topLevelFatalIssues.push(formatted)
}
} else if (isRelevantWarning(issue)) {
const formatted = formatIssue(issue)
if (!seenWarnings.has(formatted)) {
seenWarnings.add(formatted)
topLevelWarnings.push(formatted)
}
} else if (issue.severity === 'error') {
const formatted = formatIssue(issue)
if (isDev) {
// We want to treat errors as recoverable in development
// so that we can show the errors in the site and allow users
// to respond to the errors when necessary. In production builds
// though we want to error out and stop the build process.
if (!seenErrors.has(formatted)) {
seenErrors.add(formatted)
topLevelErrors.push(formatted)
}
} else {
if (!seenFatalIssues.has(formatted)) {
seenFatalIssues.add(formatted)
topLevelFatalIssues.push(formatted)
}
}
}
}
// TODO: print in order by source location so issues from the same file are displayed together and then add a summary at the end about the number of warnings/errors
if (topLevelWarnings.length > 0) {
console.warn(
`Turbopack build encountered ${
topLevelWarnings.length
} warnings:\n${topLevelWarnings.join('\n')}`
)
}
if (topLevelErrors.length > 0) {
console.error(
`Turbopack build encountered ${
topLevelErrors.length
} errors:\n${topLevelErrors.join('\n')}`
)
}
if (topLevelFatalIssues.length > 0) {
throw new Error(
`Turbopack build failed with ${
topLevelFatalIssues.length
} errors:\n${topLevelFatalIssues.join('\n')}`
)
}
}
export async function printTreeView( export async function printTreeView(
lists: { lists: {
pages: ReadonlyArray<string> pages: ReadonlyArray<string>
...@@ -1578,30 +1489,7 @@ export class NestedMiddlewareError extends Error { ...@@ -1578,30 +1489,7 @@ export class NestedMiddlewareError extends Error {
} }
} }
export function getSupportedBrowsers( export { getSupportedBrowsers } from './get-supported-browsers'
dir: string,
isDevelopment: boolean
): string[] {
let browsers: any
try {
const browsersListConfig = browserslist.loadConfig({
path: dir,
env: isDevelopment ? 'development' : 'production',
})
// Running `browserslist` resolves `extends` and other config features into a list of browsers
if (browsersListConfig && browsersListConfig.length > 0) {
browsers = browserslist(browsersListConfig)
}
} catch {}
// When user has browserslist use that target
if (browsers && browsers.length > 0) {
return browsers
}
// Uses modern browsers as the default.
return MODERN_BROWSERSLIST_TARGET
}
export function shouldUseReactServerCondition( export function shouldUseReactServerCondition(
layer: WebpackLayerName | null | undefined layer: WebpackLayerName | null | undefined
......
...@@ -65,7 +65,7 @@ import loadJsConfig, { ...@@ -65,7 +65,7 @@ import loadJsConfig, {
} from './load-jsconfig' } from './load-jsconfig'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin' import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin' import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils' import { getSupportedBrowsers } from './get-supported-browsers'
import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin' import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin'
import { getBabelConfigFile } from './get-babel-config-file' import { getBabelConfigFile } from './get-babel-config-file'
import { needsExperimentalReact } from '../lib/needs-experimental-react' import { needsExperimentalReact } from '../lib/needs-experimental-react'
......
...@@ -34,7 +34,7 @@ import { ...@@ -34,7 +34,7 @@ import {
WEBPACK_LAYERS, WEBPACK_LAYERS,
} from '../../../lib/constants' } from '../../../lib/constants'
import type { CustomRoutes } from '../../../lib/load-custom-routes' import type { CustomRoutes } from '../../../lib/load-custom-routes'
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../../../lib/is-interception-route-rewrite'
import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error' import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error'
import { getModuleReferencesInOrder } from '../utils' import { getModuleReferencesInOrder } from '../utils'
......
...@@ -64,7 +64,7 @@ import { formatManifest } from '../build/manifests/formatter/format-manifest' ...@@ -64,7 +64,7 @@ import { formatManifest } from '../build/manifests/formatter/format-manifest'
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace' import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'
import { createProgress } from '../build/progress' import { createProgress } from '../build/progress'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'
import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin' import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info' import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info'
import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding' import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding'
......
...@@ -4,7 +4,6 @@ import { ...@@ -4,7 +4,6 @@ import {
isInterceptionRouteAppPath, isInterceptionRouteAppPath,
} from '../shared/lib/router/utils/interception-routes' } from '../shared/lib/router/utils/interception-routes'
import type { Rewrite } from './load-custom-routes' import type { Rewrite } from './load-custom-routes'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
export function generateInterceptionRoutesRewrites( export function generateInterceptionRoutesRewrites(
...@@ -59,8 +58,3 @@ export function generateInterceptionRoutesRewrites( ...@@ -59,8 +58,3 @@ export function generateInterceptionRoutesRewrites(
return rewrites return rewrites
} }
export function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) {
// When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.
return route.has?.[0]?.key === NEXT_URL
}
import { NEXT_URL } from '../client/components/app-router-headers'
import type { Rewrite } from './load-custom-routes'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) {
// When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.
return route.has?.[0]?.key === NEXT_URL
}
...@@ -100,7 +100,8 @@ import { devIndicatorServerState } from './dev-indicator-server-state' ...@@ -100,7 +100,8 @@ import { devIndicatorServerState } from './dev-indicator-server-state'
import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware' import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'
import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware' import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events' import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers, printBuildErrors } from '../../build/utils' import { getSupportedBrowsers } from '../../build/get-supported-browsers'
import { printBuildErrors } from '../../build/print-build-errors'
import { import {
receiveBrowserLogsTurbopack, receiveBrowserLogsTurbopack,
handleClientFileLogs, handleClientFileLogs,
......
...@@ -109,7 +109,7 @@ import { lazyRenderPagesPage } from './route-modules/pages/module.render' ...@@ -109,7 +109,7 @@ import { lazyRenderPagesPage } from './route-modules/pages/module.render'
import { interopDefault } from '../lib/interop-default' import { interopDefault } from '../lib/interop-default'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path' import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'
import type { ServerOnInstrumentationRequestError } from './app-render/types' import type { ServerOnInstrumentationRequestError } from './app-render/types'
import { RouteKind } from './route-kind' import { RouteKind } from './route-kind'
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
......
import '../node-environment-baseline'
import { AsyncLocalStorage } from 'node:async_hooks' import { AsyncLocalStorage } from 'node:async_hooks'
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
import { import {
......
...@@ -65,7 +65,7 @@ import { ...@@ -65,7 +65,7 @@ import {
} from '../lib/router-utils/router-server-context' } from '../lib/router-utils/router-server-context'
import { decodePathParams } from '../lib/router-utils/decode-path-params' import { decodePathParams } from '../lib/router-utils/decode-path-params'
import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'
import { isInterceptionRouteRewrite } from '../../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../../lib/is-interception-route-rewrite'
/** /**
* RouteModuleOptions is the options that are passed to the route module, other * RouteModuleOptions is the options that are passed to the route module, other
......
import { import type { RequestStore } from '../../../app-render/work-unit-async-storage.external'
workUnitAsyncStorage,
type RequestStore,
} from '../../../app-render/work-unit-async-storage.external'
import { RequestCookies, ResponseCookies } from '../cookies' import { RequestCookies, ResponseCookies } from '../cookies'
import { import {
ReadonlyRequestCookiesError, ReadonlyRequestCookiesError,
RequestCookiesAdapter, RequestCookiesAdapter,
MutableRequestCookiesAdapter, MutableRequestCookiesAdapter,
createCookiesWithMutableAccessCheck,
} from './request-cookies' } from './request-cookies'
describe('RequestCookiesAdapter', () => { describe('RequestCookiesAdapter', () => {
...@@ -107,6 +103,22 @@ describe('MutableRequestCookiesAdapter', () => { ...@@ -107,6 +103,22 @@ describe('MutableRequestCookiesAdapter', () => {
}) })
describe('wrapWithMutableAccessCheck', () => { describe('wrapWithMutableAccessCheck', () => {
let workUnitAsyncStorage: typeof import('../../../app-render/work-unit-async-storage.external').workUnitAsyncStorage
let createCookiesWithMutableAccessCheck: typeof import('./request-cookies').createCookiesWithMutableAccessCheck
beforeAll(() => {
;(globalThis as any).AsyncLocalStorage ??= (
require('node:async_hooks') as typeof import('node:async_hooks')
).AsyncLocalStorage
jest.resetModules()
workUnitAsyncStorage = (
require('../../../app-render/work-unit-async-storage.external') as typeof import('../../../app-render/work-unit-async-storage.external')
).workUnitAsyncStorage
createCookiesWithMutableAccessCheck = (
require('./request-cookies') as typeof import('./request-cookies')
).createCookiesWithMutableAccessCheck
})
const createMockRequestStore = (phase: RequestStore['phase']) => { const createMockRequestStore = (phase: RequestStore['phase']) => {
const headers = new Headers({}) const headers = new Headers({})
const underlyingCookies = new ResponseCookies(headers) const underlyingCookies = new ResponseCookies(headers)
......
...@@ -34,7 +34,6 @@ import { readFileSync } from 'fs' ...@@ -34,7 +34,6 @@ import { readFileSync } from 'fs'
import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler' import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'
import { deleteCache } from '../../../server/dev/require-cache' import { deleteCache } from '../../../server/dev/require-cache'
import { writeFileAtomic } from '../../../lib/fs/write-atomic' import { writeFileAtomic } from '../../../lib/fs/write-atomic'
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites'
import getAssetPathFromRoute from '../router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'
import { getEntryKey, type EntryKey } from './entry-key' import { getEntryKey, type EntryKey } from './entry-key'
import type { CustomRoutes } from '../../../lib/load-custom-routes' import type { CustomRoutes } from '../../../lib/load-custom-routes'
...@@ -547,7 +546,11 @@ export class TurbopackManifestLoader { ...@@ -547,7 +546,11 @@ export class TurbopackManifestLoader {
} }
const interceptionRewrites = JSON.stringify( const interceptionRewrites = JSON.stringify(
rewrites.beforeFiles.filter(isInterceptionRouteRewrite) rewrites.beforeFiles.filter(
(
require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')
).isInterceptionRouteRewrite
)
) )
if (this.cachedInterceptionRewrites === interceptionRewrites) { if (this.cachedInterceptionRewrites === interceptionRewrites) {
......
...@@ -315,9 +315,3 @@ export function isFileSystemCacheEnabledForDev( ...@@ -315,9 +315,3 @@ export function isFileSystemCacheEnabledForDev(
): boolean { ): boolean {
return config.experimental?.turbopackFileSystemCacheForDev || false return config.experimental?.turbopackFileSystemCacheForDev || false
} }
export function isFileSystemCacheEnabledForBuild(
config: NextConfigComplete
): boolean {
return config.experimental?.turbopackFileSystemCacheForBuild || false
}
...@@ -19,7 +19,10 @@ export type EventSwcLoadFailure = { ...@@ -19,7 +19,10 @@ export type EventSwcLoadFailure = {
} }
export async function eventSwcLoadFailure( export async function eventSwcLoadFailure(
event?: EventSwcLoadFailure['payload'] event?: Pick<
EventSwcLoadFailure['payload'],
'wasm' | 'nativeBindingsErrorCode'
>
): Promise<void> { ): Promise<void> {
const telemetry: Telemetry | undefined = traceGlobals.get('telemetry') const telemetry: Telemetry | undefined = traceGlobals.get('telemetry')
// can't continue if telemetry isn't set // can't continue if telemetry isn't set
......
...@@ -137,6 +137,7 @@ async function readNormalizedNFT(next, name) { ...@@ -137,6 +137,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/build/adapter/setup-node-env.external.js", "/node_modules/next/dist/build/adapter/setup-node-env.external.js",
"/node_modules/next/dist/build/define-env.js", "/node_modules/next/dist/build/define-env.js",
"/node_modules/next/dist/build/duration-to-string.js", "/node_modules/next/dist/build/duration-to-string.js",
"/node_modules/next/dist/build/get-supported-browsers.js",
"/node_modules/next/dist/build/next-config-ts/require-hook.js", "/node_modules/next/dist/build/next-config-ts/require-hook.js",
"/node_modules/next/dist/build/next-config-ts/transpile-config.js", "/node_modules/next/dist/build/next-config-ts/transpile-config.js",
"/node_modules/next/dist/build/output/format.js", "/node_modules/next/dist/build/output/format.js",
...@@ -278,6 +279,7 @@ async function readNormalizedNFT(next, name) { ...@@ -278,6 +279,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/is-app-route-route.js", "/node_modules/next/dist/lib/is-app-route-route.js",
"/node_modules/next/dist/lib/is-edge-runtime.js", "/node_modules/next/dist/lib/is-edge-runtime.js",
"/node_modules/next/dist/lib/is-error.js", "/node_modules/next/dist/lib/is-error.js",
"/node_modules/next/dist/lib/is-interception-route-rewrite.js",
"/node_modules/next/dist/lib/is-internal-component.js", "/node_modules/next/dist/lib/is-internal-component.js",
"/node_modules/next/dist/lib/is-serializable-props.js", "/node_modules/next/dist/lib/is-serializable-props.js",
"/node_modules/next/dist/lib/known-edge-safe-packages.json", "/node_modules/next/dist/lib/known-edge-safe-packages.json",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment