diff --git a/.config/eslintignore.mjs b/.config/eslintignore.mjs index 62407c08a66e..b62bb2750e77 100644 --- a/.config/eslintignore.mjs +++ b/.config/eslintignore.mjs @@ -20,6 +20,9 @@ export default globalIgnores([ 'packages/next/src/bundles/webpack/packages/*.runtime.js', 'packages/next/src/bundles/webpack/packages/lazy-compilation-*.js', 'packages/next/src/compiled/**/*', + 'packages/next/src/webpack/bundles/webpack/packages/*.runtime.js', + 'packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-*.js', + 'packages/next/src/webpack/compiled/**/*', 'packages/next/wasm/@next', 'packages/react-refresh-utils/**/*.js', 'packages/react-dev-overlay/lib/**/*', diff --git a/.prettierignore b/.prettierignore index 1395aad47f8e..cbe0ebcf07c8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,6 +16,9 @@ pnpm-lock.yaml packages/next/src/bundles/webpack/packages/*.runtime.js packages/next/src/bundles/webpack/packages/lazy-compilation-*.js +packages/next/src/webpack/bundles/webpack/packages/*.runtime.js +packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-*.js +packages/next/src/webpack/compiled/**/* packages/next/wasm/@next packages/next/errors.json diff --git a/crates/next-api/src/next_server_nft.rs b/crates/next-api/src/next_server_nft.rs index dad21b243f25..f1b169b7c6d7 100644 --- a/crates/next-api/src/next_server_nft.rs +++ b/crates/next-api/src/next_server_nft.rs @@ -317,6 +317,7 @@ impl ServerNftJsonAsset { "**/*.map", "**/next/dist/pages/**/*", "**/next/dist/compiled/next-server/**/*.dev.js", + "**/next/dist/webpack/load-webpack-hook.js", "**/next/dist/compiled/webpack/*", "**/node_modules/webpack5/**/*", "**/next/dist/server/lib/route-resolver*", diff --git a/crates/next-core/src/next_app/metadata/route.rs b/crates/next-core/src/next_app/metadata/route.rs index 3bc96ba12e5d..0aeb9a835547 100644 --- a/crates/next-core/src/next_app/metadata/route.rs +++ b/crates/next-core/src/next_app/metadata/route.rs @@ -219,14 +219,14 @@ async fn dynamic_text_route_source(path: FileSystemPath) -> Result { // Keep using `styleTag` to ensure when new styles injected the style can also be updated. injectType: 'styleTag', insert: require.resolve( - './src/build/webpack/loaders/devtool/devtool-style-inject.js' + 'next/dist/webpack/build/webpack/loaders/devtool/devtool-style-inject.js' ), }, }, diff --git a/packages/next/next-runtime.webpack-config.js b/packages/next/next-runtime.webpack-config.js index b84ef5ef9a1c..1721bfb62d44 100644 --- a/packages/next/next-runtime.webpack-config.js +++ b/packages/next/next-runtime.webpack-config.js @@ -42,7 +42,7 @@ function makeAppAliases({ experimental, bundler }) { 'react/compiler-runtime$': `next/dist/compiled/react${reactChannel}/compiler-runtime`, 'react-dom/client$': `next/dist/compiled/react-dom${reactChannel}/client`, // optimizations to ignore the legacy APIs in react-dom/server - 'react-dom/server$': `next/dist/build/webpack/alias/react-dom-server${reactChannel}.js`, + 'react-dom/server$': `next/dist/webpack/build/webpack/alias/react-dom-server${reactChannel}.js`, 'react-dom/static$': `next/dist/compiled/react-dom${reactChannel}/static.node`, // react-server-dom-webpack alias 'react-server-dom-turbopack/client$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/client.node`, diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts index cbd3ce28b81d..461969d8db4a 100644 --- a/packages/next/src/build/adapter/build-complete.ts +++ b/packages/next/src/build/adapter/build-complete.ts @@ -20,10 +20,7 @@ import { convertHeaders, } from 'next/dist/compiled/@vercel/routing-utils' -import type { - MiddlewareManifest, - EdgeFunctionDefinition, -} from '../webpack/plugins/middleware-plugin' +import type { MiddlewareManifest, EdgeFunctionDefinition } from '../manifests' import type { RoutesManifest, @@ -2203,7 +2200,8 @@ async function getSharedNodeAssets({ const sharedTraceIgnores = [ '**/next/dist/compiled/next-server/**/*.dev.js', - '**/next/dist/compiled/webpack/*', + '**/next/dist/webpack/load-webpack-hook.js', + '**/next/dist/webpack/compiled/webpack/*', '**/node_modules/webpack5/**/*', '**/next/dist/server/lib/route-resolver*', 'next/dist/compiled/semver/semver/**/*.js', diff --git a/packages/next/src/build/analysis/get-page-static-info.ts b/packages/next/src/build/analysis/get-page-static-info.ts index 315e2cedf672..ef1704dc7a69 100644 --- a/packages/next/src/build/analysis/get-page-static-info.ts +++ b/packages/next/src/build/analysis/get-page-static-info.ts @@ -24,7 +24,7 @@ import { } from '../warn-about-edge-runtime' import { RSC_MODULE_TYPES } from '../../shared/lib/constants' import { escapeStringRegexp } from '../../shared/lib/escape-regexp' -import type { RSCMeta } from '../webpack/loaders/get-module-build-info' +import type { RSCMeta } from '../manifests' import { PAGE_TYPES } from '../../lib/page-types' import { AppSegmentConfigSchemaKeys, diff --git a/packages/next/src/build/babel/loader/get-config.ts b/packages/next/src/build/babel/loader/get-config.ts index f62a2b749c9c..d9d3841eb29d 100644 --- a/packages/next/src/build/babel/loader/get-config.ts +++ b/packages/next/src/build/babel/loader/get-config.ts @@ -15,9 +15,9 @@ import { type SourceMap, type BabelLoaderTransformOptions, } from './util' -import * as Log from '../../output/log' -import { isReactCompilerRequired } from '../../swc' -import { installBindings } from '../../swc/install-bindings' +import * as Log from 'next/dist/build/output/log' +import { isReactCompilerRequired } from 'next/dist/build/swc' +import { installBindings } from 'next/dist/build/swc/install-bindings' /** * An internal (non-exported) type used by babel. @@ -165,7 +165,7 @@ function getPlugins( const applyCommonJsItem = hasModuleExports ? createConfigItem( - require('../plugins/commonjs') as typeof import('../plugins/commonjs'), + require('next/dist/build/babel/plugins/commonjs') as typeof import('next/dist/build/babel/plugins/commonjs'), { type: 'plugin' } ) : null @@ -182,7 +182,7 @@ function getPlugins( !isServer && isPageFile ? createConfigItem( [ - require('../plugins/next-page-config') as typeof import('../plugins/next-page-config'), + require('next/dist/build/babel/plugins/next-page-config') as typeof import('next/dist/build/babel/plugins/next-page-config'), ], { type: 'plugin', @@ -193,7 +193,7 @@ function getPlugins( !isServer && isPageFile ? createConfigItem( [ - require('../plugins/next-page-disallow-re-export-all-exports') as typeof import('../plugins/next-page-disallow-re-export-all-exports'), + require('next/dist/build/babel/plugins/next-page-disallow-re-export-all-exports') as typeof import('next/dist/build/babel/plugins/next-page-disallow-re-export-all-exports'), ], { type: 'plugin' } ) @@ -212,9 +212,12 @@ function getPlugins( ) const nextSsgItem = !isServer && isPageFile - ? createConfigItem([require.resolve('../plugins/next-ssg-transform')], { - type: 'plugin', - }) + ? createConfigItem( + [require.resolve('next/dist/build/babel/plugins/next-ssg-transform')], + { + type: 'plugin', + } + ) : null const commonJsItem = isNextDist ? createConfigItem( @@ -224,7 +227,7 @@ function getPlugins( : null const nextFontUnsupported = createConfigItem( [ - require('../plugins/next-font-unsupported') as typeof import('../plugins/next-font-unsupported'), + require('next/dist/build/babel/plugins/next-font-unsupported') as typeof import('next/dist/build/babel/plugins/next-font-unsupported'), ], { type: 'plugin' } ) diff --git a/packages/next/src/build/babel/loader/index.ts b/packages/next/src/build/babel/loader/index.ts index 68f8733cb7d8..3574b02f56e0 100644 --- a/packages/next/src/build/babel/loader/index.ts +++ b/packages/next/src/build/babel/loader/index.ts @@ -1,8 +1,8 @@ -import type { Span } from '../../../trace' +import type { Span } from 'next/dist/trace' import transform from './transform' import type { NextJsLoaderContext } from './types' import type { SourceMap } from './util' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' async function nextBabelLoader( ctx: NextJsLoaderContext, diff --git a/packages/next/src/build/babel/loader/transform.ts b/packages/next/src/build/babel/loader/transform.ts index 91f1adb1b294..6503d97b017a 100644 --- a/packages/next/src/build/babel/loader/transform.ts +++ b/packages/next/src/build/babel/loader/transform.ts @@ -13,7 +13,7 @@ import PluginPass from 'next/dist/compiled/babel/core-lib-plugin-pass' import getConfig from './get-config' import { consumeIterator } from './util' -import type { Span } from '../../../trace' +import type { Span } from 'next/dist/trace' import type { NextJsLoaderContext } from './types' import type { SourceMap } from './util' diff --git a/packages/next/src/build/babel/loader/types.d.ts b/packages/next/src/build/babel/loader/types.d.ts index 900f14826ec2..0597f455c975 100644 --- a/packages/next/src/build/babel/loader/types.d.ts +++ b/packages/next/src/build/babel/loader/types.d.ts @@ -1,6 +1,6 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type { JSONValue } from '../../../server/config-shared' -import type { Span } from '../../../trace' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { JSONValue } from 'next/dist/server/config-shared' +import type { Span } from 'next/dist/trace' export interface NextJsLoaderContext extends webpack.LoaderContext<{}> { currentTraceSpan: Span diff --git a/packages/next/src/build/build-context.ts b/packages/next/src/build/build-context.ts index 0eff06e1194c..63d1686b43b5 100644 --- a/packages/next/src/build/build-context.ts +++ b/packages/next/src/build/build-context.ts @@ -3,8 +3,7 @@ import type { Rewrite, Redirect } from '../lib/load-custom-routes' import type { __ApiPreviewProps } from '../server/api-utils' import type { NextConfigComplete } from '../server/config-shared' import type { Span } from '../trace' -import type getBaseWebpackConfig from './webpack-config' -import type { TelemetryPluginState } from './webpack/plugins/telemetry-plugin/telemetry-plugin' +import type { TelemetryPluginState } from './manifests' import type { Telemetry } from '../telemetry/storage' // A layer for storing data that is used by plugins to communicate with each @@ -87,9 +86,7 @@ export const NextBuildContext: Partial<{ reactProductionProfiling: boolean noMangling: boolean appDirOnly: boolean - clientRouterFilters: Parameters< - typeof getBaseWebpackConfig - >[1]['clientRouterFilters'] + clientRouterFilters: any previewModeId: string fetchCacheKeyPrefix?: string allowedRevalidateHeaderKeys?: string[] diff --git a/packages/next/src/build/collect-build-traces.ts b/packages/next/src/build/collect-build-traces.ts index ab3fa3f7c8db..9feb73ece6d0 100644 --- a/packages/next/src/build/collect-build-traces.ts +++ b/packages/next/src/build/collect-build-traces.ts @@ -3,11 +3,8 @@ import '../server/lib/cpu-profile' import { Span } from '../trace' import type { NextConfigComplete } from '../server/config-shared' -import { - TRACE_IGNORES, - type BuildTraceContext, - getFilesMapFromReasons, -} from './webpack/plugins/next-trace-entrypoints-plugin' +import type { BuildTraceContext } from './manifests' +import { TRACE_IGNORES, getFilesMapFromReasons } from './trace-utils' import path from 'path' import { resolveCacheHandlerPathToFilesystem } from '../lib/format-dynamic-import-path' @@ -223,7 +220,8 @@ export async function collectBuildTraces({ const sharedIgnores = [ '**/next/dist/compiled/next-server/**/*.dev.js', ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']), - '**/next/dist/compiled/webpack/*', + '**/next/dist/webpack/load-webpack-hook.js', + '**/next/dist/webpack/compiled/webpack/*', '**/node_modules/webpack5/**/*', '**/next/dist/server/lib/route-resolver*', 'next/dist/compiled/semver/semver/**/*.js', diff --git a/packages/next/src/build/entries.ts b/packages/next/src/build/entries.ts index 4c8635c35ba1..1c2605fefc5b 100644 --- a/packages/next/src/build/entries.ts +++ b/packages/next/src/build/entries.ts @@ -1,125 +1,13 @@ -import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' -import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' -import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader' -import type { EdgeAppRouteLoaderQuery } from './webpack/loaders/next-edge-app-route-loader' -import type { NextConfigComplete } from '../server/config-shared' -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type { - ProxyConfig, - ProxyMatcher, - PageStaticInfo, -} from './analysis/get-page-static-info' -import type { LoadedEnvFiles } from '@next/env' -import type { AppLoaderOptions } from './webpack/loaders/next-app-loader' - -import { posix, join, normalize } from 'path' -import { stringify } from 'querystring' -import { - PAGES_DIR_ALIAS, - ROOT_DIR_ALIAS, - APP_DIR_ALIAS, - WEBPACK_LAYERS, - INSTRUMENTATION_HOOK_FILENAME, -} from '../lib/constants' import { isAPIRoute } from '../lib/is-api-route' import { isEdgeRuntime } from '../lib/is-edge-runtime' -import { APP_CLIENT_INTERNALS, RSC_MODULE_TYPES } from '../shared/lib/constants' -import { - CLIENT_STATIC_FILES_RUNTIME_MAIN, - CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, - CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, - CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, - COMPILER_NAMES, - EDGE_RUNTIME_WEBPACK, -} from '../shared/lib/constants' -import type { CompilerNameValues } from '../shared/lib/constants' -import type { __ApiPreviewProps } from '../server/api-utils' +import { PAGE_TYPES } from '../lib/page-types' +import type { ServerRuntime } from '../types' import { + isInstrumentationHookFile, isMiddlewareFile, - isMiddlewareFilename, isProxyFile, - isInstrumentationHookFile, - isInstrumentationHookFilename, } from './utils' -import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' -import type { ServerRuntime } from '../types' -import { - normalizeAppPath, - compareAppPaths, -} from '../shared/lib/router/utils/app-paths' -import { encodeMatchers } from './webpack/loaders/next-middleware-loader' -import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' -import { isAppRouteRoute } from '../lib/is-app-route-route' -import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' -import { - isInternalComponent, - isNonRoutePagesPage, -} from '../lib/is-internal-component' -import { RouteKind } from '../server/route-kind' -import { encodeToBase64 } from './webpack/loaders/utils' -import { normalizeCatchAllRoutes } from './normalize-catchall-routes' -import type { PageExtensions } from './page-extensions-type' -import type { MappedPages } from './build-context' -import { PAGE_TYPES } from '../lib/page-types' - -type ObjectValue = T extends { [key: string]: infer V } ? V : never -import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts' -import { getPageFromPath } from './route-discovery' - -export function getPageFilePath({ - absolutePagePath, - pagesDir, - appDir, - rootDir, -}: { - absolutePagePath: string - pagesDir: string | undefined - appDir: string | undefined - rootDir: string -}) { - if (absolutePagePath.startsWith(PAGES_DIR_ALIAS) && pagesDir) { - return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir) - } - if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) { - return absolutePagePath.replace(APP_DIR_ALIAS, appDir) - } - - if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) { - return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir) - } - - return require.resolve(absolutePagePath) -} - -export interface CreateEntrypointsParams { - buildId: string - config: NextConfigComplete - envFiles: LoadedEnvFiles - isDev: boolean - pages: MappedPages - pagesDir?: string - previewMode: __ApiPreviewProps - rootDir: string - rootPaths?: MappedPages - appDir?: string - appPaths?: MappedPages - pageExtensions: PageExtensions - hasInstrumentationHook?: boolean - /** - * When set to 'exclude', deferred entries are excluded from the result. - * When set to 'only', only deferred entries are included in the result. - * When undefined, all entries are included. - */ - deferredEntriesFilter?: 'exclude' | 'only' -} - -/** - * Checks if a page path matches any of the deferred entry patterns. - * @param page - The page path (e.g., '/about', '/api/hello') - * @param deferredEntries - Array of path patterns to match against - * @returns true if the page matches a deferred entry pattern - */ export function isDeferredEntry( page: string, deferredEntries: string[] | undefined @@ -128,19 +16,15 @@ export function isDeferredEntry( return false } - // Normalize the page path const normalizedPage = page.startsWith('/') ? page : `/${page}` for (const pattern of deferredEntries) { - // Normalize the pattern const normalizedPattern = pattern.startsWith('/') ? pattern : `/${pattern}` - // Check for exact match or prefix match for directories if (normalizedPage === normalizedPattern) { return true } - // Check if the page is under the deferred directory if (normalizedPage.startsWith(normalizedPattern + '/')) { return true } @@ -149,170 +33,6 @@ export function isDeferredEntry( return false } -export function getEdgeServerEntry(opts: { - rootDir: string - absolutePagePath: string - buildId: string - bundlePath: string - config: NextConfigComplete - isDev: boolean - isServerComponent: boolean - page: string - pages: MappedPages - middleware?: Partial - pagesType: PAGE_TYPES - appDirLoader?: string - hasInstrumentationHook?: boolean - preferredRegion: string | string[] | undefined - middlewareConfig?: ProxyConfig -}) { - const cacheHandler = opts.config.cacheHandler || undefined - - if ( - opts.pagesType === 'app' && - isAppRouteRoute(opts.page) && - opts.appDirLoader - ) { - const loaderParams: EdgeAppRouteLoaderQuery = { - absolutePagePath: opts.absolutePagePath, - page: opts.page, - appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), - preferredRegion: opts.preferredRegion, - middlewareConfig: Buffer.from( - JSON.stringify(opts.middlewareConfig || {}) - ).toString('base64'), - cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}), - ...(cacheHandler ? { cacheHandler } : {}), - } - - return { - import: `next-edge-app-route-loader?${stringify(loaderParams)}!`, - layer: WEBPACK_LAYERS.reactServerComponents, - } - } - - if (isMiddlewareFile(opts.page)) { - const loaderParams: MiddlewareLoaderOptions = { - absolutePagePath: opts.absolutePagePath, - page: opts.page, - rootDir: opts.rootDir, - matchers: opts.middleware?.matchers - ? encodeMatchers(opts.middleware.matchers) - : '', - preferredRegion: opts.preferredRegion, - middlewareConfig: Buffer.from( - JSON.stringify(opts.middlewareConfig || {}) - ).toString('base64'), - ...(cacheHandler ? { cacheHandler } : {}), - } - - return { - import: `next-middleware-loader?${stringify(loaderParams)}!`, - layer: WEBPACK_LAYERS.middleware, - filename: opts.isDev ? 'middleware.js' : undefined, - } - } - - if (isAPIRoute(opts.page)) { - const loaderParams: EdgeFunctionLoaderOptions = { - absolutePagePath: opts.absolutePagePath, - page: opts.page, - rootDir: opts.rootDir, - preferredRegion: opts.preferredRegion, - middlewareConfig: Buffer.from( - JSON.stringify(opts.middlewareConfig || {}) - ).toString('base64'), - ...(cacheHandler ? { cacheHandler } : {}), - } - - return { - import: `next-edge-function-loader?${stringify(loaderParams)}!`, - layer: WEBPACK_LAYERS.apiEdge, - } - } - - const loaderParams: EdgeSSRLoaderQuery = { - absolute500Path: opts.pages['/500'] || '', - absoluteAppPath: opts.pages['/_app'], - absoluteDocumentPath: opts.pages['/_document'], - absoluteErrorPath: opts.pages['/_error'], - absolutePagePath: opts.absolutePagePath, - dev: opts.isDev, - isServerComponent: opts.isServerComponent, - page: opts.page, - pagesType: opts.pagesType, - appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), - sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm, - preferredRegion: opts.preferredRegion, - middlewareConfig: Buffer.from( - JSON.stringify(opts.middlewareConfig || {}) - ).toString('base64'), - serverActions: opts.config.experimental.serverActions, - cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}), - ...(cacheHandler ? { cacheHandler } : {}), - } - - return { - import: `next-edge-ssr-loader?${JSON.stringify(loaderParams)}!`, - // The Edge bundle includes the server in its entrypoint, so it has to - // be in the SSR layer — we later convert the page request to the RSC layer - // via a webpack rule. - layer: opts.appDirLoader ? WEBPACK_LAYERS.serverSideRendering : undefined, - } -} - -export function getInstrumentationEntry(opts: { - absolutePagePath: string - isEdgeServer: boolean - isDev: boolean -}) { - // the '../' is needed to make sure the file is not chunked - const filename = `${ - opts.isEdgeServer ? 'edge-' : opts.isDev ? '' : '../' - }${INSTRUMENTATION_HOOK_FILENAME}.js` - - return { - import: opts.absolutePagePath, - filename, - layer: WEBPACK_LAYERS.instrument, - } -} - -export function getAppLoader() { - return process.env.BUILTIN_APP_LOADER - ? `builtin:next-app-loader` - : 'next-app-loader' -} - -export function getAppEntry(opts: Readonly) { - if (process.env.NEXT_RSPACK && process.env.BUILTIN_APP_LOADER) { - ;(opts as any).projectRoot = normalize(join(__dirname, '../../..')) - } - return { - import: `${getAppLoader()}?${stringify(opts)}!`, - layer: WEBPACK_LAYERS.reactServerComponents, - } -} - -export function getClientEntry(opts: { - absolutePagePath: string - page: string -}) { - const loaderOptions: ClientPagesLoaderOptions = { - absolutePagePath: opts.absolutePagePath, - page: opts.page, - } - - const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!` - - // Make sure next/router is a dependency of _app or else chunk splitting - // might cause the router to not be able to load causing hydration - // to fail - return opts.page === '/_app' - ? [pageLoader, require.resolve('../client/router')] - : pageLoader -} - export function runDependingOnPageType(params: { onClient: () => T onEdgeServer: () => T @@ -339,10 +59,10 @@ export function runDependingOnPageType(params: { if (params.pageRuntime === 'nodejs') { params.onServer() return - } else { - params.onEdgeServer() - return } + + params.onEdgeServer() + return } if (isAPIRoute(params.page)) { @@ -354,10 +74,12 @@ export function runDependingOnPageType(params: { params.onServer() return } + if (params.page === '/_document') { params.onServer() return } + if ( params.page === '/_app' || params.page === '/_error' || @@ -368,6 +90,7 @@ export function runDependingOnPageType(params: { params.onServer() return } + if (isEdgeRuntime(params.pageRuntime)) { params.onClient() params.onEdgeServer() @@ -376,398 +99,4 @@ export function runDependingOnPageType(params: { params.onClient() params.onServer() - return -} - -export async function createEntrypoints( - params: CreateEntrypointsParams -): Promise<{ - client: webpack.EntryObject - server: webpack.EntryObject - edgeServer: webpack.EntryObject - middlewareMatchers: undefined -}> { - const { - config, - pages, - pagesDir, - isDev, - rootDir, - rootPaths, - appDir, - appPaths, - pageExtensions, - deferredEntriesFilter, - } = params - - const deferredEntries = config.experimental.deferredEntries - const edgeServer: webpack.EntryObject = {} - const server: webpack.EntryObject = {} - const client: webpack.EntryObject = {} - let middlewareMatchers: ProxyMatcher[] | undefined = undefined - - let appPathsPerRoute: Record = {} - if (appDir && appPaths) { - for (const pathname in appPaths) { - const normalizedPath = normalizeAppPath(pathname) - const actualPath = appPaths[pathname] - if (!appPathsPerRoute[normalizedPath]) { - appPathsPerRoute[normalizedPath] = [] - } - appPathsPerRoute[normalizedPath].push( - // TODO-APP: refactor to pass the page path from createPagesMapping instead. - getPageFromPath(actualPath, pageExtensions).replace(APP_DIR_ALIAS, '') - ) - } - - // TODO: find a better place to do this - normalizeCatchAllRoutes(appPathsPerRoute) - - // Make sure to sort parallel routes to make the result deterministic. - appPathsPerRoute = Object.fromEntries( - Object.entries(appPathsPerRoute).map(([k, v]) => [ - k, - v.sort(compareAppPaths), - ]) - ) - } - - const getEntryHandler = - (mappings: MappedPages, pagesType: PAGE_TYPES): ((page: string) => void) => - async (page) => { - // Apply deferred entries filter if specified - if (deferredEntriesFilter) { - const isDeferred = isDeferredEntry(page, deferredEntries) - if (deferredEntriesFilter === 'exclude' && isDeferred) { - // Skip deferred entries when excluding them - return - } - if (deferredEntriesFilter === 'only' && !isDeferred) { - // Skip non-deferred entries when only including deferred ones - return - } - } - - const bundleFile = normalizePagePath(page) - const clientBundlePath = posix.join(pagesType, bundleFile) - const serverBundlePath = - pagesType === PAGE_TYPES.PAGES - ? posix.join('pages', bundleFile) - : pagesType === PAGE_TYPES.APP - ? posix.join('app', bundleFile) - : bundleFile.slice(1) - - const absolutePagePath = mappings[page] - - // Handle paths that have aliases - const pageFilePath = getPageFilePath({ - absolutePagePath, - pagesDir, - appDir, - rootDir, - }) - - const isInsideAppDir = - !!appDir && - (absolutePagePath.startsWith(APP_DIR_ALIAS) || - absolutePagePath.startsWith(appDir)) - - const staticInfo: PageStaticInfo = await getStaticInfoIncludingLayouts({ - isInsideAppDir, - pageExtensions, - pageFilePath, - appDir, - config, - isDev, - page, - }) - - // TODO(timneutkens): remove this - const isServerComponent = - isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client - - if (isMiddlewareFile(page)) { - middlewareMatchers = staticInfo.middleware?.matchers ?? [ - { regexp: '.*', originalSource: '/:path*' }, - ] - } - - const isInstrumentation = - isInstrumentationHookFile(page) && pagesType === PAGE_TYPES.ROOT - - runDependingOnPageType({ - page, - pageRuntime: staticInfo.runtime, - pageType: pagesType, - onClient: () => { - if (isServerComponent || isInsideAppDir) { - // We skip the initial entries for server component pages and let the - // server compiler inject them instead. - } else { - client[clientBundlePath] = getClientEntry({ - absolutePagePath, - page, - }) - } - }, - onServer: () => { - if (pagesType === 'app' && appDir) { - const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)] - server[serverBundlePath] = getAppEntry({ - page, - name: serverBundlePath, - pagePath: absolutePagePath, - appDir, - appPaths: matchedAppPaths, - allNormalizedAppPaths: Object.keys(appPathsPerRoute), - pageExtensions, - basePath: config.basePath, - assetPrefix: config.assetPrefix, - nextConfigOutput: config.output, - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: encodeToBase64(staticInfo.middleware || {}), - isGlobalNotFoundEnabled: config.experimental.globalNotFound - ? true - : undefined, - }) - } else if (isInstrumentation) { - server[serverBundlePath.replace('src/', '')] = - getInstrumentationEntry({ - absolutePagePath, - isEdgeServer: false, - isDev: false, - }) - } else if (isMiddlewareFile(page)) { - server[serverBundlePath.replace('src/', '')] = getEdgeServerEntry({ - ...params, - rootDir, - absolutePagePath: absolutePagePath, - bundlePath: clientBundlePath, - isDev: false, - isServerComponent, - page, - middleware: staticInfo?.middleware, - pagesType, - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: staticInfo.middleware, - }) - } else if (isAPIRoute(page)) { - server[serverBundlePath] = [ - getRouteLoaderEntry({ - kind: RouteKind.PAGES_API, - page, - absolutePagePath, - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: staticInfo.middleware || {}, - }), - ] - } else if ( - !isMiddlewareFile(page) && - !isInternalComponent(absolutePagePath) && - !isNonRoutePagesPage(page) - ) { - server[serverBundlePath] = [ - getRouteLoaderEntry({ - kind: RouteKind.PAGES, - page, - pages, - absolutePagePath, - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: staticInfo.middleware ?? {}, - }), - ] - } else { - server[serverBundlePath] = [absolutePagePath] - } - }, - onEdgeServer: () => { - let appDirLoader: string = '' - if (isInstrumentation) { - edgeServer[serverBundlePath.replace('src/', '')] = - getInstrumentationEntry({ - absolutePagePath, - isEdgeServer: true, - isDev: false, - }) - } else { - if (pagesType === 'app') { - const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)] - appDirLoader = getAppEntry({ - name: serverBundlePath, - page, - pagePath: absolutePagePath, - appDir: appDir!, - appPaths: matchedAppPaths, - allNormalizedAppPaths: Object.keys(appPathsPerRoute), - pageExtensions, - basePath: config.basePath, - assetPrefix: config.assetPrefix, - nextConfigOutput: config.output, - // This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead. - // Still passing it here for consistency. - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: Buffer.from( - JSON.stringify(staticInfo.middleware || {}) - ).toString('base64'), - isGlobalNotFoundEnabled: config.experimental.globalNotFound - ? true - : undefined, - }).import - } - edgeServer[serverBundlePath] = getEdgeServerEntry({ - ...params, - rootDir, - absolutePagePath: absolutePagePath, - bundlePath: clientBundlePath, - isDev: false, - isServerComponent, - page, - middleware: staticInfo?.middleware, - pagesType, - appDirLoader, - preferredRegion: staticInfo.preferredRegion, - middlewareConfig: staticInfo.middleware, - }) - } - }, - }) - } - - const promises: Promise[] = [] - - if (appPaths) { - const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP) - promises.push(Promise.all(Object.keys(appPaths).map(entryHandler))) - } - if (rootPaths) { - promises.push( - Promise.all( - Object.keys(rootPaths).map(getEntryHandler(rootPaths, PAGE_TYPES.ROOT)) - ) - ) - } - promises.push( - Promise.all( - Object.keys(pages).map(getEntryHandler(pages, PAGE_TYPES.PAGES)) - ) - ) - - await Promise.all(promises) - - // Optimization: If there's only one instrumentation hook in edge compiler, which means there's no edge server entry. - // We remove the edge instrumentation entry from edge compiler as it can be pure server side. - if (edgeServer.instrumentation && Object.keys(edgeServer).length === 1) { - delete edgeServer.instrumentation - } - - return { - client, - server, - edgeServer, - middlewareMatchers, - } -} - -export function finalizeEntrypoint({ - name, - compilerType, - value, - isServerComponent, - hasAppDir, -}: { - compilerType: CompilerNameValues - name: string - value: ObjectValue - isServerComponent?: boolean - hasAppDir?: boolean -}): ObjectValue { - const entry = - typeof value !== 'object' || Array.isArray(value) - ? { import: value } - : value - - const isApi = name.startsWith('pages/api/') - const isInstrumentation = isInstrumentationHookFilename(name) - - switch (compilerType) { - case COMPILER_NAMES.server: { - const layer = isApi - ? WEBPACK_LAYERS.apiNode - : isInstrumentation - ? WEBPACK_LAYERS.instrument - : isServerComponent - ? WEBPACK_LAYERS.reactServerComponents - : name.startsWith('pages/') - ? WEBPACK_LAYERS.pagesDirNode - : undefined - - return { - publicPath: isApi ? '' : undefined, - runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime', - layer, - ...entry, - } - } - case COMPILER_NAMES.edgeServer: { - return { - layer: isApi - ? WEBPACK_LAYERS.apiEdge - : isMiddlewareFilename(name) || isInstrumentation - ? WEBPACK_LAYERS.middleware - : name.startsWith('pages/') - ? WEBPACK_LAYERS.pagesDirEdge - : undefined, - library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' }, - runtime: EDGE_RUNTIME_WEBPACK, - asyncChunks: false, - ...entry, - } - } - case COMPILER_NAMES.client: { - const isAppLayer = - hasAppDir && - (name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || - name === APP_CLIENT_INTERNALS || - name.startsWith('app/')) - - if ( - // Client special cases - name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && - name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && - name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && - name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH - ) { - if (isAppLayer) { - return { - dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, - layer: WEBPACK_LAYERS.appPagesBrowser, - ...entry, - } - } - - return { - dependOn: - name.startsWith('pages/') && name !== 'pages/_app' - ? 'pages/_app' - : CLIENT_STATIC_FILES_RUNTIME_MAIN, - layer: WEBPACK_LAYERS.pagesDirBrowser, - ...entry, - } - } - - if (isAppLayer) { - return { - layer: WEBPACK_LAYERS.appPagesBrowser, - ...entry, - } - } - - return { - layer: WEBPACK_LAYERS.pagesDirBrowser, - ...entry, - } - } - default: - return compilerType satisfies never - } } diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index f4f190650766..c64176db4c40 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -1,11 +1,11 @@ -import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from './manifests' import type { ExportPathMap, NextConfigComplete, NextConfigRuntime, } from '../server/config-shared' -import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin' -import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin' +import type { MiddlewareManifest } from './manifests' +import type { ActionManifest } from './manifests' import type { CacheControl, Revalidate } from '../server/lib/cache-control' import type { PrefetchHints } from '../shared/lib/app-router-types' @@ -161,7 +161,6 @@ import { type NEXT_REWRITTEN_PATH_HEADER, type NEXT_REWRITTEN_QUERY_HEADER, } from '../client/components/app-router-headers' -import { webpackBuild } from './webpack-build' import { NextBuildContext } from './build-context' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { isAppRouteRoute } from '../lib/is-app-route-route' @@ -170,7 +169,7 @@ import { startTypeChecking } from './type-check' import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites' import { buildDataRoute } from '../server/lib/router-utils/build-data-route' -import type { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin' +import type { BuildTraceContext } from './manifests' import { formatManifest } from './manifests/formatter/format-manifest' import { recordFrameworkVersion, @@ -197,7 +196,7 @@ import { FallbackMode, fallbackModeToFallbackField } from '../lib/fallback' import { RenderingMode } from './rendering-mode' import { InvariantError } from '../shared/lib/invariant-error' 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 './manifests' import { turbopackBuild } from './turbopack-build' import { inlineStaticEnv } from '../lib/inline-static-env' @@ -230,6 +229,17 @@ import { import { generateRoutesManifest } from './generate-routes-manifest' import { validateAppPaths } from './validate-app-paths' +type WebpackBuild = ( + useBuildWorker: boolean, + compilerNames: string[] | null +) => Promise + +function getWebpackBuild(): WebpackBuild { + return ( + require('next/dist/webpack/next-integration') as typeof import('next/dist/webpack/next-integration') + ).webpackBuild +} + type Fallback = null | boolean | string export interface PrerenderManifestRoute { @@ -1659,6 +1669,8 @@ export default async function build( }) ) } else { + const webpackBuild = getWebpackBuild() + if ( runServerAndEdgeInParallel || collectServerBuildTracesInParallel diff --git a/packages/next/src/build/manifests/index.ts b/packages/next/src/build/manifests/index.ts new file mode 100644 index 000000000000..9d17d2fd3ee7 --- /dev/null +++ b/packages/next/src/build/manifests/index.ts @@ -0,0 +1,350 @@ +import type { + ProxyConfig, + ProxyMatcher, + RSCModuleType, +} from '../analysis/get-page-static-info' +import type { CustomRoutes, Rewrite } from '../../lib/load-custom-routes' +import type { BuildManifest } from '../../server/get-page-files' + +export type PagesManifest = { [page: string]: string } + +export interface EdgeFunctionDefinition { + files: string[] + name: string + page: string + entrypoint: string + matchers: ProxyMatcher[] + env: Record + wasm?: AssetBinding[] + assets?: AssetBinding[] + regions?: string[] | string +} + +export interface MiddlewareManifest { + version: 3 + sortedMiddleware: string[] + middleware: { [page: string]: EdgeFunctionDefinition } + functions: { [page: string]: EdgeFunctionDefinition } +} + +export const SUPPORTED_NATIVE_MODULES = [ + 'buffer', + 'events', + 'assert', + 'util', + 'async_hooks', +] as const + +export interface EdgeMiddlewareMeta { + page: string + matchers?: ProxyMatcher[] +} + +export interface EdgeSSRMeta { + isServerComponent: boolean + isAppDir?: boolean + page: string +} + +export interface AssetBinding { + filePath: string + name: string +} + +export interface ServerActionLocation { + line: number + col: number +} + +export interface ServerActionInfo { + name: string + loc?: ServerActionLocation +} + +export interface RSCMeta { + type: RSCModuleType + actionIds?: Record + clientRefs?: string[] + clientEntryType?: 'cjs' | 'auto' + isClientRef?: boolean + requests?: string[] +} + +export interface RouteMeta { + page: string + absolutePagePath: string + preferredRegion: string | string[] | undefined + middlewareConfig: ProxyConfig + relatedModules?: string[] +} + +export type ModuleId = string | number +export type ManifestChunks = ReadonlyArray + +export interface ManifestNode { + [moduleExport: string]: { + id: ModuleId + name: string + chunks: ManifestChunks + async?: boolean + } +} + +export interface ClientReferenceManifestForRsc { + clientModules: ManifestNode + rscModuleMapping: { + [moduleId: string]: ManifestNode + } + edgeRscModuleMapping: { + [moduleId: string]: ManifestNode + } +} + +export type CssResource = InlinedCssFile | UninlinedCssFile + +interface InlinedCssFile { + path: string + inlined: true + content: string +} + +interface UninlinedCssFile { + path: string + inlined: false +} + +export interface ClientReferenceManifest extends ClientReferenceManifestForRsc { + readonly moduleLoading: { + prefix: string + crossOrigin?: 'use-credentials' | '' + } + ssrModuleMapping: { + [moduleId: string]: ManifestNode + } + edgeSSRModuleMapping: { + [moduleId: string]: ManifestNode + } + entryCSSFiles: { + [entry: string]: CssResource[] + } + entryJSFiles?: { + [entry: string]: string[] + } +} + +type Actions = { + [actionId: string]: { + exportedName?: string + filename?: string + workers: { + [name: string]: { + moduleId: string | number + async: boolean + } + } + layer?: { + [name: string]: string + } + } +} + +export type ActionManifest = { + encryptionKey: string + node: Actions + edge: Actions +} + +export interface ModuleInfo { + moduleId: string | number + async: boolean +} + +export type NextFontManifest = { + pages: { + [path: string]: string[] + } + app: { + [entry: string]: string[] + } + appUsingSizeAdjust: boolean + pagesUsingSizeAdjust: boolean +} + +export type SubresourceIntegrityAlgorithm = 'sha256' | 'sha384' | 'sha512' + +export type ModuleGetter = () => any +export type ModuleTuple = [getModule: ModuleGetter, filePath: string] + +export type CollectedMetadata = { + icon: ModuleGetter[] + apple: ModuleGetter[] + twitter: ModuleGetter[] | null + openGraph: ModuleGetter[] | null + manifest?: string +} + +export type MetadataImageModule = { + url: string + type?: string + alt?: string +} & ( + | { sizes?: string } + | { + width?: number + height?: number + } +) + +type AppDirFileType = + | 'layout' + | 'template' + | 'error' + | 'loading' + | 'global-error' + | 'global-not-found' + | 'not-found' + | 'forbidden' + | 'unauthorized' + +export type AppDirModules = { + readonly [moduleKey in AppDirFileType]?: ModuleTuple +} & { + readonly page?: ModuleTuple +} & { + readonly metadata?: CollectedMetadata +} & { + readonly defaultPage?: ModuleTuple +} + +export type ClientBuildManifest = { + [key: string]: string[] +} + +export const srcEmptySsgManifest = `self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()` + +function normalizeRewrite(item: { + source: string + destination: string + has?: any +}): CustomRoutes['rewrites']['beforeFiles'][0] { + return { + has: item.has, + source: item.source, + destination: item.destination, + } +} + +export const processRoute = (r: Rewrite) => { + const rewrite = { ...r } + + if (!rewrite?.destination?.startsWith('/')) { + delete (rewrite as any).destination + } + return rewrite +} + +export function normalizeRewritesForBuildManifest( + rewrites: CustomRoutes['rewrites'] +): CustomRoutes['rewrites'] { + return { + afterFiles: rewrites.afterFiles + ?.map(processRoute) + ?.map((item) => normalizeRewrite(item)), + beforeFiles: rewrites.beforeFiles + ?.map(processRoute) + ?.map((item) => normalizeRewrite(item)), + fallback: rewrites.fallback + ?.map(processRoute) + ?.map((item) => normalizeRewrite(item)), + } +} + +export function createEdgeRuntimeManifest( + assetMap: Partial +): string { + return `globalThis.__BUILD_MANIFEST = ${JSON.stringify(assetMap, null, 2)};\n` +} + +export type UseCacheTrackerKey = `useCache/${string}` + +export type SWC_TARGET_TRIPLE = + | 'x86_64-apple-darwin' + | 'x86_64-unknown-linux-gnu' + | 'x86_64-pc-windows-msvc' + | 'i686-pc-windows-msvc' + | 'aarch64-unknown-linux-gnu' + | 'armv7-unknown-linux-gnueabihf' + | 'aarch64-apple-darwin' + | 'aarch64-linux-android' + | 'arm-linux-androideabi' + | 'x86_64-unknown-freebsd' + | 'x86_64-unknown-linux-musl' + | 'aarch64-unknown-linux-musl' + | 'aarch64-pc-windows-msvc' + +export type TelemetryFeature = + | 'next/image' + | 'next/future/image' + | 'next/legacy/image' + | 'next/script' + | 'next/dynamic' + | '@next/font/google' + | '@next/font/local' + | 'next/font/google' + | 'next/font/local' + | 'swcLoader' + | 'swcRelay' + | 'swcStyledComponents' + | 'swcReactRemoveProperties' + | 'swcExperimentalDecorators' + | 'swcRemoveConsole' + | 'swcImportSource' + | 'swcEmotion' + | `swc/target/${SWC_TARGET_TRIPLE}` + | 'turbotrace' + | 'transpilePackages' + | 'skipProxyUrlNormalize' + | 'skipTrailingSlashRedirect' + | 'modularizeImports' + | 'esmExternals' + | 'webpackPlugins' + | UseCacheTrackerKey + +export interface TelemetryPlugin { + usages(): Array<{ featureName: TelemetryFeature; invocationCount: number }> + packagesUsedInServerSideProps(): string[] + getUseCacheTracker(): Record +} + +export type TelemetryPluginState = { + usages: ReturnType + packagesUsedInServerSideProps: ReturnType< + TelemetryPlugin['packagesUsedInServerSideProps'] + > + useCacheTracker: ReturnType +} + +export interface TurbotraceAction { + action: 'print' | 'annotate' + input: string[] + contextDirectory: string + processCwd: string + showAll?: boolean + memoryLimit?: number +} + +export interface BuildTraceContext { + entriesTrace?: { + action: TurbotraceAction + appDir: string + outputPath: string + depModArray: string[] + entryNameMap: Record + absolutePathByEntryName: Record + } + chunksTrace?: { + action: TurbotraceAction + outputPath: string + entryNameFilesMap: Record> + } +} diff --git a/packages/next/src/build/output/index.ts b/packages/next/src/build/output/index.ts index 3b4a2dace98a..ebad51409d2b 100644 --- a/packages/next/src/build/output/index.ts +++ b/packages/next/src/build/output/index.ts @@ -2,10 +2,12 @@ import createStore from 'next/dist/compiled/unistore' import formatWebpackMessages from '../../shared/lib/format-webpack-messages' import { store as consoleStore } from './store' import type { OutputState } from './store' -import type { webpack } from 'next/dist/compiled/webpack/webpack' import { COMPILER_NAMES } from '../../shared/lib/constants' import type { CompilerNameValues } from '../../shared/lib/constants' +type WebpackCompiler = any +type WebpackStats = any + type CompilerDiagnostics = { totalModulesCount: number errors: string[] | null @@ -123,9 +125,9 @@ buildStore.subscribe((state) => { }) export function watchCompilers( - client: webpack.Compiler, - server: webpack.Compiler, - edgeServer: webpack.Compiler + client: WebpackCompiler, + server: WebpackCompiler, + edgeServer: WebpackCompiler ) { buildStore.setState({ client: { loading: true }, @@ -137,14 +139,14 @@ export function watchCompilers( function tapCompiler( key: CompilerNameValues, - compiler: webpack.Compiler, + compiler: WebpackCompiler, onEvent: (status: WebpackStatus) => void ) { compiler.hooks.invalid.tap(`NextJsInvalid-${key}`, () => { onEvent({ loading: true }) }) - compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: webpack.Stats) => { + compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: WebpackStats) => { const { errors, warnings } = formatWebpackMessages( stats.toJson({ preset: 'errors-warnings', diff --git a/packages/next/src/build/webpack/loaders/resolve-url-loader/index.ts b/packages/next/src/build/resolve-url-loader/index.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/resolve-url-loader/index.ts rename to packages/next/src/build/resolve-url-loader/index.ts diff --git a/packages/next/src/build/webpack/loaders/resolve-url-loader/lib/file-protocol.ts b/packages/next/src/build/resolve-url-loader/lib/file-protocol.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/resolve-url-loader/lib/file-protocol.ts rename to packages/next/src/build/resolve-url-loader/lib/file-protocol.ts diff --git a/packages/next/src/build/webpack/loaders/resolve-url-loader/lib/join-function.ts b/packages/next/src/build/resolve-url-loader/lib/join-function.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/resolve-url-loader/lib/join-function.ts rename to packages/next/src/build/resolve-url-loader/lib/join-function.ts diff --git a/packages/next/src/build/webpack/loaders/resolve-url-loader/lib/postcss.ts b/packages/next/src/build/resolve-url-loader/lib/postcss.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/resolve-url-loader/lib/postcss.ts rename to packages/next/src/build/resolve-url-loader/lib/postcss.ts diff --git a/packages/next/src/build/webpack/loaders/resolve-url-loader/lib/value-processor.ts b/packages/next/src/build/resolve-url-loader/lib/value-processor.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/resolve-url-loader/lib/value-processor.ts rename to packages/next/src/build/resolve-url-loader/lib/value-processor.ts diff --git a/packages/next/src/build/trace-utils.ts b/packages/next/src/build/trace-utils.ts new file mode 100644 index 000000000000..c37ed0c724e1 --- /dev/null +++ b/packages/next/src/build/trace-utils.ts @@ -0,0 +1,56 @@ +import type { NodeFileTraceReasons } from 'next/dist/compiled/@vercel/nft' + +export const TRACE_IGNORES = [ + '**/*/next/dist/server/next.js', + '**/*/next/dist/bin/next', +] + +export function getFilesMapFromReasons( + fileList: Set, + reasons: NodeFileTraceReasons, + ignoreFn?: (file: string, parent?: string) => Boolean +) { + const parentFilesMap = new Map>() + + function propagateToParents( + parents: Set, + file: string, + seen = new Set() + ) { + for (const parent of parents || []) { + if (!seen.has(parent)) { + seen.add(parent) + let parentFiles = parentFilesMap.get(parent) + + if (!parentFiles) { + parentFiles = new Map() + parentFilesMap.set(parent, parentFiles) + } + const ignored = Boolean(ignoreFn?.(file, parent)) + parentFiles.set(file, { ignored }) + + const parentReason = reasons.get(parent) + + if (parentReason?.parents) { + propagateToParents(parentReason.parents, file, seen) + } + } + } + } + + for (const file of fileList) { + const reason = reasons.get(file) + const isInitial = + reason?.type.length === 1 && reason.type.includes('initial') + + if ( + !reason || + !reason.parents || + (isInitial && reason.parents.size === 0) + ) { + continue + } + propagateToParents(reason.parents, file) + } + return parentFilesMap +} diff --git a/packages/next/src/build/utils.ts b/packages/next/src/build/utils.ts index 0b9f7ffd525c..edec6593f747 100644 --- a/packages/next/src/build/utils.ts +++ b/packages/next/src/build/utils.ts @@ -4,7 +4,7 @@ import type { } from '../server/config-shared' import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr' import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr' -import type { AssetBinding } from './webpack/loaders/get-module-build-info' +import type { AssetBinding } from './manifests' import type { ServerRuntime } from '../types' import type { BuildManifest } from '../server/get-page-files' import { @@ -14,10 +14,7 @@ import { type Redirect, type Rewrite, } from '../lib/load-custom-routes' -import type { - EdgeFunctionDefinition, - MiddlewareManifest, -} from './webpack/plugins/middleware-plugin' +import type { EdgeFunctionDefinition, MiddlewareManifest } from './manifests' import type { WebpackLayerName } from '../lib/constants' import { INSTRUMENTATION_HOOK_FILENAME, diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/cache-wrapper.ts b/packages/next/src/build/webpack/loaders/next-flight-loader/cache-wrapper.ts deleted file mode 100644 index c225f960175d..000000000000 --- a/packages/next/src/build/webpack/loaders/next-flight-loader/cache-wrapper.ts +++ /dev/null @@ -1 +0,0 @@ -export { cache } from '../../../../server/use-cache/use-cache-wrapper' diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts b/packages/next/src/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts deleted file mode 100644 index 3f3468038ae9..000000000000 --- a/packages/next/src/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts +++ /dev/null @@ -1 +0,0 @@ -export { trackDynamicImport } from '../../../../server/app-render/module-loading/track-dynamic-import' diff --git a/packages/next/src/client/app-webpack.ts b/packages/next/src/client/app-webpack.ts index 30eb8ca969f1..b99382fcb4ea 100644 --- a/packages/next/src/client/app-webpack.ts +++ b/packages/next/src/client/app-webpack.ts @@ -1,41 +1,3 @@ -// Override chunk URL mapping 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-path' - -declare const __webpack_require__: any - -// If we have a deployment ID, we need to append it to the webpack chunk names -// I am keeping the process check explicit so this can be statically optimized -if (getAssetToken()) { - const suffix = getAssetTokenQuery() - const getChunkScriptFilename = __webpack_require__.u - __webpack_require__.u = (...args: any[]) => - // We encode the chunk filename because our static server matches against and encoded - // filename path. - encodeURIPath(getChunkScriptFilename(...args)) + suffix - - const getChunkCssFilename = __webpack_require__.k - __webpack_require__.k = (...args: any[]) => - getChunkCssFilename(...args) + suffix - - const getMiniCssFilename = __webpack_require__.miniCssF - __webpack_require__.miniCssF = (...args: any[]) => - getMiniCssFilename(...args) + suffix -} else { - const getChunkScriptFilename = __webpack_require__.u - __webpack_require__.u = (...args: any[]) => - // We encode the chunk filename because our static server matches against and encoded - // filename path. - encodeURIPath(getChunkScriptFilename(...args)) - - // We don't need to override __webpack_require__.k because we don't modify - // the css chunk name when not using deployment id suffixes - - // WE don't need to override __webpack_require__.miniCssF because we don't modify - // the mini css chunk name when not using deployment id suffixes -} +import 'next/dist/webpack/client/app-webpack' export {} diff --git a/packages/next/src/client/webpack.ts b/packages/next/src/client/webpack.ts index 3127438a1057..7ed18ffd2020 100644 --- a/packages/next/src/client/webpack.ts +++ b/packages/next/src/client/webpack.ts @@ -1,30 +1,3 @@ -declare const __webpack_require__: any -declare let __webpack_public_path__: string - -import { getAssetToken, getAssetTokenQuery } from '../shared/lib/deployment-id' - -// If we have a deployment ID query string, we need to append it to the webpack chunk names -// I am keeping the process check explicit so this can be statically optimized -if (getAssetToken()) { - const suffix = getAssetTokenQuery() - const getChunkScriptFilename = __webpack_require__.u - __webpack_require__.u = (...args: any[]) => - // We enode the chunk filename because our static server matches against and encoded - // filename path. - getChunkScriptFilename(...args) + suffix - - const getChunkCssFilename = __webpack_require__.k - __webpack_require__.k = (...args: any[]) => - getChunkCssFilename(...args) + suffix - - const getMiniCssFilename = __webpack_require__.miniCssF - __webpack_require__.miniCssF = (...args: any[]) => - getMiniCssFilename(...args) + suffix -} - -// Ignore the module ID transform in client. -;(self as any).__next_set_public_path__ = (path: string) => { - __webpack_public_path__ = path -} +import 'next/dist/webpack/client/webpack' export {} diff --git a/packages/next/src/compiled/webpack/webpack.d.ts b/packages/next/src/compiled/webpack/webpack.d.ts deleted file mode 100644 index 867d7d63fcaf..000000000000 --- a/packages/next/src/compiled/webpack/webpack.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -export namespace webpack { - export type Compiler = any - export type Plugin = any - export type Configuration = any - export type StatsError = any - export type Stats = any - export type MultiCompiler = any - export type EntryObject = any - export type ProgressPlugin = any - export type Compilation = any - export type javascript = any - export type Module = any - export type ModuleGraph = any - export type WebpackPluginInstance = any -} diff --git a/packages/next/src/export/index.ts b/packages/next/src/export/index.ts index c0e6ae40481a..69e7388ccab9 100644 --- a/packages/next/src/export/index.ts +++ b/packages/next/src/export/index.ts @@ -10,7 +10,7 @@ import { type PrerenderManifest, type StaticWorker, } from '../build' -import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from '../build/manifests' import { bold, yellow } from '../lib/picocolors' import findUp from 'next/dist/compiled/find-up' @@ -56,7 +56,7 @@ import { loadEnvConfig } from '@next/env' import { isAPIRoute } from '../lib/is-api-route' import { getPagePath } from '../server/require' import type { Span } from '../trace' -import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' +import type { MiddlewareManifest } from '../build/manifests' import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppPageRoute } from '../lib/is-app-page-route' import isError from '../lib/is-error' @@ -65,7 +65,7 @@ import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace' import { createProgress } from '../build/progress' import type { DeepReadonly } from '../shared/lib/deep-readonly' import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite' -import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin' +import type { ActionManifest } from '../build/manifests' import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info' import { convertSegmentPathToStaticExportFilename } from '../shared/lib/segment-cache/segment-value-encoding' import { getNextBuildDebuggerPortOffset } from '../lib/worker' diff --git a/packages/next/src/lib/metadata/resolve-metadata.ts b/packages/next/src/lib/metadata/resolve-metadata.ts index 1ae86da5d768..82693211a89a 100644 --- a/packages/next/src/lib/metadata/resolve-metadata.ts +++ b/packages/next/src/lib/metadata/resolve-metadata.ts @@ -7,11 +7,11 @@ import type { Viewport, WithStringifiedURLs, } from './types/metadata-interface' -import type { MetadataImageModule } from '../../build/webpack/loaders/metadata/types' +import type { MetadataImageModule } from '../../build/manifests' import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' import type { Twitter } from './types/twitter-types' import type { OpenGraph } from './types/opengraph-types' -import type { AppDirModules } from '../../build/webpack/loaders/next-app-loader' +import type { AppDirModules } from '../../build/manifests' import type { MetadataContext } from './types/resolvers' import type { LoaderTree } from '../../server/lib/app-dir-module' import type { diff --git a/packages/next/src/next-devtools/server/restart-dev-server-middleware.ts b/packages/next/src/next-devtools/server/restart-dev-server-middleware.ts index f410e3a4a3f6..ad3f01f32e87 100644 --- a/packages/next/src/next-devtools/server/restart-dev-server-middleware.ts +++ b/packages/next/src/next-devtools/server/restart-dev-server-middleware.ts @@ -3,7 +3,6 @@ import type { Telemetry } from '../../telemetry/storage' import { RESTART_EXIT_CODE } from '../../server/lib/utils' import { middlewareResponse } from './middleware-response' import type { Project } from '../../build/swc/types' -import { invalidateFileSystemCache as invalidateWebpackFileSystemCache } from '../../build/webpack/cache-invalidation' const EVENT_DEV_OVERLAY_RESTART_SERVER = 'DEV_OVERLAY_RESTART_SERVER' @@ -42,6 +41,8 @@ export function getRestartDevServerMiddleware({ ) if (shouldInvalidateFileSystemCache) { if (webpackCacheDirectories != null) { + const { invalidateFileSystemCache: invalidateWebpackFileSystemCache } = + require('next/dist/webpack/next-integration') as typeof import('next/dist/webpack/next-integration') await Promise.all( Array.from(webpackCacheDirectories).map( invalidateWebpackFileSystemCache diff --git a/packages/next/src/pages/_document.tsx b/packages/next/src/pages/_document.tsx index 28269e98e01c..7eb27408016b 100644 --- a/packages/next/src/pages/_document.tsx +++ b/packages/next/src/pages/_document.tsx @@ -10,7 +10,7 @@ import type { NEXT_DATA, } from '../shared/lib/utils' import type { ScriptProps } from '../client/script' -import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../build/manifests' import { getPageFiles } from '../server/get-page-files' import type { BuildManifest } from '../server/get-page-files' diff --git a/packages/next/src/server/app-render/collect-segment-data.tsx b/packages/next/src/server/app-render/collect-segment-data.tsx index a177640e1e66..7f9176740eb3 100644 --- a/packages/next/src/server/app-render/collect-segment-data.tsx +++ b/packages/next/src/server/app-render/collect-segment-data.tsx @@ -12,7 +12,7 @@ import { StaticPrefetchDisabled, } from '../../shared/lib/app-router-types' import { readVaryParams } from '../../shared/lib/segment-cache/vary-params-decoding' -import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin' +import type { ManifestNode } from '../../build/manifests' // eslint-disable-next-line import/no-extraneous-dependencies import { createFromReadableStream } from 'react-server-dom-webpack/client' diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index a032afe67326..fca94ef81008 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -1,4 +1,4 @@ -import type { CssResource } from '../../build/webpack/plugins/flight-manifest-plugin' +import type { CssResource } from '../../build/manifests' import { getClientReferenceManifest } from './manifests-singleton' /** diff --git a/packages/next/src/server/app-render/get-preloadable-fonts.tsx b/packages/next/src/server/app-render/get-preloadable-fonts.tsx index 99e94cdfad19..3e85145f64e3 100644 --- a/packages/next/src/server/app-render/get-preloadable-fonts.tsx +++ b/packages/next/src/server/app-render/get-preloadable-fonts.tsx @@ -1,4 +1,4 @@ -import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../../build/manifests' import type { DeepReadonly } from '../../shared/lib/deep-readonly' /** diff --git a/packages/next/src/server/app-render/manifests-singleton.ts b/packages/next/src/server/app-render/manifests-singleton.ts index 5df89c9881e2..156763c987fc 100644 --- a/packages/next/src/server/app-render/manifests-singleton.ts +++ b/packages/next/src/server/app-render/manifests-singleton.ts @@ -1,5 +1,5 @@ -import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin' -import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' +import type { ActionManifest } from '../../build/manifests' +import type { ClientReferenceManifest } from '../../build/manifests' import type { DeepReadonly } from '../../shared/lib/deep-readonly' import { InvariantError } from '../../shared/lib/invariant-error' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' diff --git a/packages/next/src/server/app-render/render-css-resource.tsx b/packages/next/src/server/app-render/render-css-resource.tsx index 668370ba3004..647d250ce591 100644 --- a/packages/next/src/server/app-render/render-css-resource.tsx +++ b/packages/next/src/server/app-render/render-css-resource.tsx @@ -1,4 +1,4 @@ -import type { CssResource } from '../../build/webpack/plugins/flight-manifest-plugin' +import type { CssResource } from '../../build/manifests' import { encodeURIPath } from '../../shared/lib/encode-uri-path' import type { AppRenderContext } from './app-render' import { getAssetQueryString } from './get-asset-query-string' diff --git a/packages/next/src/server/app-render/types.ts b/packages/next/src/server/app-render/types.ts index f1b3d49132c3..241c4c485e53 100644 --- a/packages/next/src/server/app-render/types.ts +++ b/packages/next/src/server/app-render/types.ts @@ -6,7 +6,7 @@ import type { PrefetchInliningConfig, ValidationLevel, } from '../../server/config-shared' -import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../../build/manifests' import type { ParsedUrlQuery } from 'querystring' import type { AppPageModule } from '../route-modules/app-page/module' import type { DeepReadonly } from '../../shared/lib/deep-readonly' diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 3b27440d1e73..f7476e3108be 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -25,15 +25,15 @@ import { normalizeRepeatedSlashes, MissingStaticPage, } from '../shared/lib/utils' -import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from '../build/manifests' import type { BaseNextRequest, BaseNextResponse } from './base-http' import type { ManifestRewriteRoute, ManifestRoute, PrerenderManifest, } from '../build' -import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin' -import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' +import type { ClientReferenceManifest } from '../build/manifests' +import type { NextFontManifest } from '../build/manifests' import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match' import type { Server as HTTPServer, diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index 698ec2e636e7..cbe77e3fc40a 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -1,12 +1,11 @@ import os from 'os' -import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes' import { imageConfigDefault } from '../shared/lib/image-config' import type { ImageConfig, ImageConfigComplete, } from '../shared/lib/image-config' -import type { SubresourceIntegrityAlgorithm } from '../build/webpack/plugins/subresource-integrity-plugin' +import type { SubresourceIntegrityAlgorithm } from '../build/manifests' import type { WEB_VITALS } from '../shared/lib/utils' import type { NextParsedUrlQuery } from './request-meta' import type { SizeLimit } from '../types' @@ -366,7 +365,7 @@ export interface LoggingConfig { * related individual features at once. * * The name→bitmask mapping is duplicated in: - * - JS: `packages/next/src/build/webpack/loaders/lightningcss-loader/src/features.ts` + * - JS: `packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/features.ts` * - Rust: `crates/next-core/src/next_config.rs` (`lightningcss_feature_names_to_mask`) */ export const LIGHTNINGCSS_FEATURE_NAMES = [ @@ -591,7 +590,7 @@ export interface ExperimentalConfig { craCompat?: boolean esmExternals?: boolean | 'loose' fullySpecified?: boolean - urlImports?: NonNullable['buildHttp'] + urlImports?: any swcTraceProfiling?: boolean forceSwcTransforms?: boolean diff --git a/packages/next/src/server/config-utils.ts b/packages/next/src/server/config-utils.ts index bb3c80ecbaea..3705ff5209c2 100644 --- a/packages/next/src/server/config-utils.ts +++ b/packages/next/src/server/config-utils.ts @@ -1,4 +1,4 @@ -let installed: boolean = false +let installed = false export function loadWebpackHook() { if (installed) { @@ -6,139 +6,8 @@ export function loadWebpackHook() { } installed = true - // hook the Node.js require so that webpack requires are - // routed to the bundled and now initialized webpack version - ;( - require('../server/require-hook') as typeof import('../server/require-hook') - ).addHookAliases( - [ - ['webpack', 'next/dist/compiled/webpack/webpack-lib'], - ['webpack/package', 'next/dist/compiled/webpack/package'], - ['webpack/package.json', 'next/dist/compiled/webpack/package'], - ['webpack/lib/webpack', 'next/dist/compiled/webpack/webpack-lib'], - ['webpack/lib/webpack.js', 'next/dist/compiled/webpack/webpack-lib'], - [ - 'webpack/lib/node/NodeEnvironmentPlugin', - 'next/dist/compiled/webpack/NodeEnvironmentPlugin', - ], - [ - 'webpack/lib/node/NodeEnvironmentPlugin.js', - 'next/dist/compiled/webpack/NodeEnvironmentPlugin', - ], - [ - 'webpack/lib/BasicEvaluatedExpression', - 'next/dist/compiled/webpack/BasicEvaluatedExpression', - ], - [ - 'webpack/lib/BasicEvaluatedExpression.js', - 'next/dist/compiled/webpack/BasicEvaluatedExpression', - ], - [ - 'webpack/lib/node/NodeTargetPlugin', - 'next/dist/compiled/webpack/NodeTargetPlugin', - ], - [ - 'webpack/lib/node/NodeTargetPlugin.js', - 'next/dist/compiled/webpack/NodeTargetPlugin', - ], - [ - 'webpack/lib/node/NodeTemplatePlugin', - 'next/dist/compiled/webpack/NodeTemplatePlugin', - ], - [ - 'webpack/lib/node/NodeTemplatePlugin.js', - 'next/dist/compiled/webpack/NodeTemplatePlugin', - ], - [ - 'webpack/lib/LibraryTemplatePlugin', - 'next/dist/compiled/webpack/LibraryTemplatePlugin', - ], - [ - 'webpack/lib/LibraryTemplatePlugin.js', - 'next/dist/compiled/webpack/LibraryTemplatePlugin', - ], - [ - 'webpack/lib/SingleEntryPlugin', - 'next/dist/compiled/webpack/SingleEntryPlugin', - ], - [ - 'webpack/lib/SingleEntryPlugin.js', - 'next/dist/compiled/webpack/SingleEntryPlugin', - ], - [ - 'webpack/lib/optimize/LimitChunkCountPlugin', - 'next/dist/compiled/webpack/LimitChunkCountPlugin', - ], - [ - 'webpack/lib/optimize/LimitChunkCountPlugin.js', - 'next/dist/compiled/webpack/LimitChunkCountPlugin', - ], - [ - 'webpack/lib/webworker/WebWorkerTemplatePlugin', - 'next/dist/compiled/webpack/WebWorkerTemplatePlugin', - ], - [ - 'webpack/lib/webworker/WebWorkerTemplatePlugin.js', - 'next/dist/compiled/webpack/WebWorkerTemplatePlugin', - ], - [ - 'webpack/lib/ExternalsPlugin', - 'next/dist/compiled/webpack/ExternalsPlugin', - ], - [ - 'webpack/lib/ExternalsPlugin.js', - 'next/dist/compiled/webpack/ExternalsPlugin', - ], - [ - 'webpack/lib/web/FetchCompileWasmTemplatePlugin', - 'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin', - ], - [ - 'webpack/lib/web/FetchCompileWasmTemplatePlugin.js', - 'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin', - ], - [ - 'webpack/lib/web/FetchCompileWasmPlugin', - 'next/dist/compiled/webpack/FetchCompileWasmPlugin', - ], - [ - 'webpack/lib/web/FetchCompileWasmPlugin.js', - 'next/dist/compiled/webpack/FetchCompileWasmPlugin', - ], - [ - 'webpack/lib/web/FetchCompileAsyncWasmPlugin', - 'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', - ], - [ - 'webpack/lib/web/FetchCompileAsyncWasmPlugin.js', - 'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin', - ], - [ - 'webpack/lib/ModuleFilenameHelpers', - 'next/dist/compiled/webpack/ModuleFilenameHelpers', - ], - [ - 'webpack/lib/ModuleFilenameHelpers.js', - 'next/dist/compiled/webpack/ModuleFilenameHelpers', - ], - ['webpack/lib/GraphHelpers', 'next/dist/compiled/webpack/GraphHelpers'], - [ - 'webpack/lib/GraphHelpers.js', - 'next/dist/compiled/webpack/GraphHelpers', - ], - ['webpack/lib/NormalModule', 'next/dist/compiled/webpack/NormalModule'], - ['webpack-sources', 'next/dist/compiled/webpack/sources'], - ['webpack-sources/lib', 'next/dist/compiled/webpack/sources'], - ['webpack-sources/lib/index', 'next/dist/compiled/webpack/sources'], - ['webpack-sources/lib/index.js', 'next/dist/compiled/webpack/sources'], - ['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'], - [ - '@babel/runtime/package.json', - 'next/dist/compiled/@babel/runtime/package.json', - ], - ].map( - // Use dynamic require.resolve to avoid statically analyzable since they're only for build time - ([request, replacement]) => [request, require.resolve(replacement)] - ) - ) + const { loadWebpackHook: installWebpackHook } = + require('../webpack/load-webpack-hook') as typeof import('../webpack/load-webpack-hook') + + installWebpackHook() } diff --git a/packages/next/src/server/dev/browser-logs/source-map.ts b/packages/next/src/server/dev/browser-logs/source-map.ts index 34670b4c3ecb..939ccfcbc360 100644 --- a/packages/next/src/server/dev/browser-logs/source-map.ts +++ b/packages/next/src/server/dev/browser-logs/source-map.ts @@ -1,5 +1,5 @@ -import { getOriginalStackFrames as getOriginalStackFramesWebpack } from '../middleware-webpack' import { getOriginalStackFrames as getOriginalStackFramesTurbopack } from '../middleware-turbopack' +import type { OriginalStackFramesResponse } from '../../../next-devtools/server/shared' import type { Project } from '../../../build/swc/types' import { dim } from '../../../lib/picocolors' import { parseStack, type StackFrame } from '../../lib/parse-stack' @@ -32,9 +32,11 @@ export type MappingContext = WebpackMappingContext | TurbopackMappingContext export async function mapFramesUsingBundler( frames: StackFrame[], ctx: MappingContext -) { +): Promise { switch (ctx.bundler) { case 'webpack': { + const { getOriginalStackFrames: getOriginalStackFramesWebpack } = + require('next/dist/webpack/server/dev/middleware-webpack') as typeof import('next/dist/webpack/server/dev/middleware-webpack') const { isServer, isEdgeServer, diff --git a/packages/next/src/build/webpack/plugins/next-types-plugin/shared.ts b/packages/next/src/server/dev/dev-page-files.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/next-types-plugin/shared.ts rename to packages/next/src/server/dev/dev-page-files.ts diff --git a/packages/next/src/server/dev/hot-reloader-types.ts b/packages/next/src/server/dev/hot-reloader-types.ts index df507062fcc9..8a3ad140d50a 100644 --- a/packages/next/src/server/dev/hot-reloader-types.ts +++ b/packages/next/src/server/dev/hot-reloader-types.ts @@ -1,8 +1,6 @@ import type { IncomingMessage, ServerResponse } from 'http' import type { UrlObject } from 'url' import type { Duplex } from 'stream' -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type getBaseWebpackConfig from '../../build/webpack-config' import type { RouteDefinition } from '../route-definitions/route-definition' import type { Project, Update as TurbopackUpdate } from '../../build/swc/types' import type { VersionInfo } from './parse-version-info' @@ -219,9 +217,9 @@ export type TurbopackMessageSentToBrowser = export interface NextJsHotReloaderInterface { turbopackProject?: Project - activeWebpackConfigs?: Array>> - serverStats: webpack.Stats | null - edgeServerStats: webpack.Stats | null + activeWebpackConfigs?: any[] + serverStats: any | null + edgeServerStats: any | null run( req: IncomingMessage, res: ServerResponse, diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts index 918cb628b7ae..89c3207a4cd5 100644 --- a/packages/next/src/server/dev/next-dev-server.ts +++ b/packages/next/src/server/dev/next-dev-server.ts @@ -20,7 +20,7 @@ import type { IncrementalCache } from '../lib/incremental-cache' import type { UnwrapPromise } from '../../lib/coalesced-function' import type { NodeNextResponse, NodeNextRequest } from '../base-http/node' import type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager' -import type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from '../../build/manifests' import * as React from 'react' import fs from 'fs' diff --git a/packages/next/src/server/dev/on-demand-entry-handler.ts b/packages/next/src/server/dev/on-demand-entry-handler.ts index 8d172b87d68d..b540815f530b 100644 --- a/packages/next/src/server/dev/on-demand-entry-handler.ts +++ b/packages/next/src/server/dev/on-demand-entry-handler.ts @@ -1,5 +1,4 @@ import type ws from 'next/dist/compiled/ws' -import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { NextConfigComplete } from '../config-shared' import type { DynamicParamTypesShort, @@ -266,16 +265,18 @@ const lastServerAccessPagesForAppDir = [''] type BuildingTracker = Set type RebuildTracker = Set +type WebpackCompilation = any +type WebpackMultiCompiler = any // Make sure only one invalidation happens at a time // Otherwise, webpack hash gets changed and it'll force the client to reload. class Invalidator { - private multiCompiler: webpack.MultiCompiler + private multiCompiler: WebpackMultiCompiler private building: BuildingTracker = new Set() private rebuildAgain: RebuildTracker = new Set() - constructor(multiCompiler: webpack.MultiCompiler) { + constructor(multiCompiler: WebpackMultiCompiler) { this.multiCompiler = multiCompiler } @@ -550,7 +551,7 @@ export function onDemandEntryHandler({ }: { hotReloader: NextJsHotReloaderInterface maxInactiveAge: number - multiCompiler: webpack.MultiCompiler + multiCompiler: WebpackMultiCompiler nextConfig: NextConfigComplete pagesBufferLength: number pagesDir?: string @@ -638,7 +639,7 @@ export function onDemandEntryHandler({ } } - const startBuilding = (compilation: webpack.Compilation) => { + const startBuilding = (compilation: WebpackCompilation) => { const compilationName = compilation.name as any as CompilerNameValues curInvalidator.startBuilding(compilationName) // Reset deferred entries state for this compilation cycle @@ -683,7 +684,7 @@ export function onDemandEntryHandler({ ) } - multiCompiler.hooks.done.tap('NextJsOnDemandEntries', (multiStats) => { + multiCompiler.hooks.done.tap('NextJsOnDemandEntries', (multiStats: any) => { const [clientStats, serverStats, edgeServerStats] = multiStats.stats const entryNames = [ ...getPagePathsFromEntrypoints( diff --git a/packages/next/src/server/lib/app-dir-module.ts b/packages/next/src/server/lib/app-dir-module.ts index 609d0aead8e2..2ecb3a432e02 100644 --- a/packages/next/src/server/lib/app-dir-module.ts +++ b/packages/next/src/server/lib/app-dir-module.ts @@ -1,4 +1,4 @@ -import type { AppDirModules } from '../../build/webpack/loaders/next-app-loader' +import type { AppDirModules } from '../../build/manifests' import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment' /** diff --git a/packages/next/src/server/lib/router-utils/filesystem.ts b/packages/next/src/server/lib/router-utils/filesystem.ts index 6909eb2c7738..300141b7f277 100644 --- a/packages/next/src/server/lib/router-utils/filesystem.ts +++ b/packages/next/src/server/lib/router-utils/filesystem.ts @@ -5,7 +5,7 @@ import type { RoutesManifest, } from '../../../build' import type { NextConfigRuntime } from '../../config-shared' -import type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin' +import type { MiddlewareManifest } from '../../../build/manifests' import type { UnwrapPromise } from '../../../lib/coalesced-function' import type { PatchMatcher } from '../../../shared/lib/router/utils/path-match' import type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher' diff --git a/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts b/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts index d91df07f43cb..2ecf5664d52a 100644 --- a/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts +++ b/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts @@ -55,7 +55,7 @@ import { getPossibleMiddlewareFilenames, getPossibleInstrumentationHookFilenames, } from '../../../build/utils' -import { devPageFiles } from '../../../build/webpack/plugins/next-types-plugin/shared' +import { devPageFiles } from '../../dev/dev-page-files' import type { LazyRenderServerInstance } from '../router-server' import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../dev/hot-reloader-types' import { PAGE_TYPES } from '../../../lib/page-types' @@ -68,7 +68,6 @@ import { fillStaticMetadataSegment, normalizeMetadataPageToRoute, } from '../../../lib/metadata/get-metadata-route' -import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin' import { store as consoleStore } from '../../../build/output/store' import { isFileSystemCacheEnabledForDev, @@ -225,6 +224,7 @@ async function startWatcher( ) const serverFields: ServerFields = {} + let JsConfigPathsPlugin: any // Update logging state once based on next.config.js when initializing consoleStore.setState({ @@ -246,13 +246,15 @@ async function startWatcher( ) })() : await (async () => { + const { + HotReloaderRspack, + HotReloaderWebpack, + JsConfigPathsPlugin: WebpackJsConfigPathsPlugin, + } = require('next/dist/webpack/next-integration') as typeof import('next/dist/webpack/next-integration') + JsConfigPathsPlugin = WebpackJsConfigPathsPlugin const HotReloader = process.env.NEXT_RSPACK - ? ( - require('../../dev/hot-reloader-rspack') as typeof import('../../dev/hot-reloader-rspack') - ).default - : ( - require('../../dev/hot-reloader-webpack') as typeof import('../../dev/hot-reloader-webpack') - ).default + ? HotReloaderRspack + : HotReloaderWebpack return new HotReloader(opts.dir, { isSrcDir: opts.isSrcDir, appDir, @@ -866,11 +868,15 @@ async function startWatcher( config.resolve?.plugins?.forEach((plugin: any) => { // look for the JsConfigPathsPlugin and update with // the latest paths/baseUrl config - if (plugin instanceof JsConfigPathsPlugin && tsconfigResult) { + if ( + JsConfigPathsPlugin && + plugin instanceof JsConfigPathsPlugin && + tsconfigResult + ) { const { resolvedBaseUrl, jsConfig } = tsconfigResult const currentResolvedBaseUrl = plugin.resolvedBaseUrl const resolvedUrlIndex = config.resolve?.modules?.findIndex( - (item) => item === currentResolvedBaseUrl?.baseUrl + (item: string) => item === currentResolvedBaseUrl?.baseUrl ) if (resolvedBaseUrl) { diff --git a/packages/next/src/server/load-components.ts b/packages/next/src/server/load-components.ts index 11555f0dfdfc..edd15997d019 100644 --- a/packages/next/src/server/load-components.ts +++ b/packages/next/src/server/load-components.ts @@ -4,7 +4,7 @@ import type { DocumentType, NextComponentType, } from '../shared/lib/utils' -import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin' +import type { ClientReferenceManifest } from '../build/manifests' import type { PageConfig, GetStaticPaths, @@ -13,7 +13,7 @@ import type { } from '../types' import type { RouteModule } from './route-modules/route-module' import type { BuildManifest } from './get-page-files' -import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin' +import type { ActionManifest } from '../build/manifests' import { BUILD_MANIFEST, diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index 73525886c660..9a93814daa76 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -8,11 +8,11 @@ import { PageNotFoundError, MiddlewareNotFoundError, } from '../shared/lib/utils' -import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' +import type { MiddlewareManifest } from '../build/manifests' import type RenderResult from './render-result' import type { FetchEventResult } from './web/types' import type { PrerenderManifest, RoutesManifest } from '../build' -import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from '../build/manifests' import type { NextParsedUrlQuery, NextUrlWithParsedQuery, @@ -109,7 +109,7 @@ import { lazyRenderAppPage } from './route-modules/app-page/module.render' import { lazyRenderPagesPage } from './route-modules/pages/module.render' import { interopDefault } from '../lib/interop-default' import { formatDynamicImportPath } from '../lib/format-dynamic-import-path' -import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../build/manifests' import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite' import type { ServerOnInstrumentationRequestError } from './app-render/types' import type { PrefetchHints } from '../shared/lib/app-router-types' diff --git a/packages/next/src/server/next.ts b/packages/next/src/server/next.ts index adf3cc25b4d1..db8fe60be879 100644 --- a/packages/next/src/server/next.ts +++ b/packages/next/src/server/next.ts @@ -15,6 +15,7 @@ import * as log from '../build/output/log' import loadConfig from './config' import path from 'node:path' import { NON_STANDARD_NODE_ENV } from '../lib/constants' +import { Bundler } from '../lib/bundler' import { PHASE_DEVELOPMENT_SERVER, SERVER_FILES_MANIFEST, @@ -282,6 +283,7 @@ export class NextServer implements NextWrapperServer { const dir = path.resolve( /* turbopackIgnore: true */ this.options.dir || '.' ) + const bundlerOptions = this.options as NextBundlerOptions const config = await loadConfig( this.options.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER, @@ -289,6 +291,11 @@ export class NextServer implements NextWrapperServer { { customConfig: this.options.conf, silent: true, + bundler: bundlerOptions.webpack + ? Bundler.Webpack + : bundlerOptions.turbopack || bundlerOptions.turbo + ? Bundler.Turbopack + : undefined, } ) diff --git a/packages/next/src/server/render.tsx b/packages/next/src/server/render.tsx index af6f36d91564..f9048a6725dd 100644 --- a/packages/next/src/server/render.tsx +++ b/packages/next/src/server/render.tsx @@ -32,8 +32,8 @@ import type { SizeLimit, } from '../types' import type { UnwrapPromise } from '../lib/coalesced-function' -import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin' -import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' +import type { ClientReferenceManifest } from '../build/manifests' +import type { NextFontManifest } from '../build/manifests' import type { PagesModule } from './route-modules/pages/module' import type { ComponentsEnhancer } from '../shared/lib/utils' import type { NextParsedUrlQuery } from './request-meta' diff --git a/packages/next/src/server/require-hook.ts b/packages/next/src/server/require-hook.ts index 2e87b1141775..b91b3af01e58 100644 --- a/packages/next/src/server/require-hook.ts +++ b/packages/next/src/server/require-hook.ts @@ -1,6 +1,6 @@ -// Synchronously inject a require hook for webpack and webpack/. It's required to use the internal ncc webpack version. -// This is needed for userland plugins to attach to the same webpack instance as Next.js'. -// Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*. +// Synchronously inject a require hook for shared runtime aliases. +// Webpack aliases are registered lazily by the webpack integration provider +// so default Turbopack paths do not load the webpack implementation. // This module will only be loaded once per process. const path = require('path') as typeof import('path') diff --git a/packages/next/src/server/require.ts b/packages/next/src/server/require.ts index 9bcda1c14cdd..3fdc1a534363 100644 --- a/packages/next/src/server/require.ts +++ b/packages/next/src/server/require.ts @@ -7,7 +7,7 @@ import { import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' -import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' +import type { PagesManifest } from '../build/manifests' import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils' import { LRUCache } from '../server/lib/lru-cache' import { loadManifest } from './load-manifest.external' diff --git a/packages/next/src/server/route-modules/route-module.ts b/packages/next/src/server/route-modules/route-module.ts index 1159e775f175..ffe5fecdc257 100644 --- a/packages/next/src/server/route-modules/route-module.ts +++ b/packages/next/src/server/route-modules/route-module.ts @@ -41,7 +41,7 @@ import { checkIsOnDemandRevalidate } from '../api-utils' import type { PreviewData } from '../../types' import type { BuildManifest } from '../get-page-files' import type { ReactLoadableManifest } from '../load-components' -import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../../build/manifests' import { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts index c320d4a4f281..090890f28933 100644 --- a/packages/next/src/server/use-cache/use-cache-wrapper.ts +++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts @@ -44,7 +44,7 @@ import { makeHangingPromise, } from '../dynamic-rendering-utils' -import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' +import type { ClientReferenceManifest } from '../../build/manifests' import { getClientReferenceManifest, diff --git a/packages/next/src/server/web/sandbox/context.ts b/packages/next/src/server/web/sandbox/context.ts index 431505ae5165..6b232192d7ef 100644 --- a/packages/next/src/server/web/sandbox/context.ts +++ b/packages/next/src/server/web/sandbox/context.ts @@ -1,8 +1,6 @@ -import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info' -import type { - EdgeFunctionDefinition, - SUPPORTED_NATIVE_MODULES, -} from '../../../build/webpack/plugins/middleware-plugin' +import type { SUPPORTED_NATIVE_MODULES } from '../../../build/manifests' +import type { AssetBinding } from '../../../build/manifests' +import type { EdgeFunctionDefinition } from '../../../build/manifests' import type { UnwrapPromise } from '../../../lib/coalesced-function' import { AsyncLocalStorage } from 'async_hooks' import { diff --git a/packages/next/src/server/web/sandbox/fetch-inline-assets.ts b/packages/next/src/server/web/sandbox/fetch-inline-assets.ts index 8d4866f43c3f..a31a2e0e8d9d 100644 --- a/packages/next/src/server/web/sandbox/fetch-inline-assets.ts +++ b/packages/next/src/server/web/sandbox/fetch-inline-assets.ts @@ -1,4 +1,4 @@ -import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin' +import type { EdgeFunctionDefinition } from '../../../build/manifests' import { createReadStream, promises as fs } from 'fs' import { requestToBodyStream } from '../../body-streams' import { resolve } from 'path' diff --git a/packages/next/src/server/web/sandbox/sandbox.ts b/packages/next/src/server/web/sandbox/sandbox.ts index 64708bab518a..3b72dc245f2d 100644 --- a/packages/next/src/server/web/sandbox/sandbox.ts +++ b/packages/next/src/server/web/sandbox/sandbox.ts @@ -1,5 +1,5 @@ import type { NodejsRequestData, FetchEventResult } from '../types' -import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin' +import type { EdgeFunctionDefinition } from '../../../build/manifests' import type { EdgeRuntime } from 'next/dist/compiled/edge-runtime' import { getModuleContext, diff --git a/packages/next/src/shared/lib/html-context.shared-runtime.ts b/packages/next/src/shared/lib/html-context.shared-runtime.ts index 457822ed4bb6..28414431a2bc 100644 --- a/packages/next/src/shared/lib/html-context.shared-runtime.ts +++ b/packages/next/src/shared/lib/html-context.shared-runtime.ts @@ -1,7 +1,7 @@ import type { BuildManifest } from '../../server/get-page-files' import type { ServerRuntime } from '../../types' import type { NEXT_DATA } from './utils' -import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' +import type { NextFontManifest } from '../../build/manifests' import type { DeepReadonly } from './deep-readonly' import { createContext, useContext, type JSX } from 'react' diff --git a/packages/next/src/shared/lib/turbopack/manifest-loader.ts b/packages/next/src/shared/lib/turbopack/manifest-loader.ts index f6ef56c554fd..abb800151b13 100644 --- a/packages/next/src/shared/lib/turbopack/manifest-loader.ts +++ b/packages/next/src/shared/lib/turbopack/manifest-loader.ts @@ -1,11 +1,11 @@ import type { EdgeFunctionDefinition, MiddlewareManifest, -} from '../../../build/webpack/plugins/middleware-plugin' +} from '../../../build/manifests' import type { BuildManifest } from '../../../server/get-page-files' -import type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin' -import type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin' -import type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin' +import type { PagesManifest } from '../../../build/manifests' +import type { ActionManifest } from '../../../build/manifests' +import type { NextFontManifest } from '../../../build/manifests' import type { REACT_LOADABLE_MANIFEST } from '../constants' import { APP_PATHS_MANIFEST, @@ -45,7 +45,7 @@ import { srcEmptySsgManifest, processRoute, createEdgeRuntimeManifest, -} from '../../../build/webpack/plugins/build-manifest-plugin-utils' +} from '../../../build/manifests' import type { SubresourceIntegrityManifest } from '../../../build' interface InstrumentationDefinition { diff --git a/packages/next/src/telemetry/events/build.ts b/packages/next/src/telemetry/events/build.ts index ab1c71d9fc51..60305a50f365 100644 --- a/packages/next/src/telemetry/events/build.ts +++ b/packages/next/src/telemetry/events/build.ts @@ -1,6 +1,6 @@ -import type { TelemetryPlugin } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin' -import type { SWC_TARGET_TRIPLE } from '../../build/webpack/plugins/telemetry-plugin/telemetry-plugin' -import type { UseCacheTrackerKey } from '../../build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils' +import type { TelemetryPlugin } from '../../build/manifests' +import type { SWC_TARGET_TRIPLE } from '../../build/manifests' +import type { UseCacheTrackerKey } from '../../build/manifests' import { extractNextErrorCode } from '../../lib/error-telemetry-utils' const REGEXP_DIRECTORY_DUNDER = diff --git a/packages/next/src/webpack/README.md b/packages/next/src/webpack/README.md new file mode 100644 index 000000000000..46e47bc9fa66 --- /dev/null +++ b/packages/next/src/webpack/README.md @@ -0,0 +1,8 @@ +# Webpack Integration + +This subtree contains the webpack implementation used when users opt in with +`next dev --webpack` or `next build --webpack`. + +Core Next.js code should reach it through `next/dist/webpack/next-integration` +or other `next/dist/webpack/*` paths so webpack support can be removed cleanly +in a future release. diff --git a/packages/next/src/build/compiler.ts b/packages/next/src/webpack/build/compiler.ts similarity index 95% rename from packages/next/src/build/compiler.ts rename to packages/next/src/webpack/build/compiler.ts index 681416862bfa..2ef55ee73d3b 100644 --- a/packages/next/src/build/compiler.ts +++ b/packages/next/src/webpack/build/compiler.ts @@ -1,5 +1,5 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type { Span } from '../trace' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { Span } from 'next/dist/trace' import getWebpackBundler from '../shared/lib/get-webpack-bundler' export type CompilerResult = { diff --git a/packages/next/src/build/create-compiler-aliases.ts b/packages/next/src/webpack/build/create-compiler-aliases.ts similarity index 94% rename from packages/next/src/build/create-compiler-aliases.ts rename to packages/next/src/webpack/build/create-compiler-aliases.ts index c9ef02997af2..c765d2111e4f 100644 --- a/packages/next/src/build/create-compiler-aliases.ts +++ b/packages/next/src/webpack/build/create-compiler-aliases.ts @@ -12,12 +12,12 @@ import { RSC_CACHE_WRAPPER_ALIAS, type WebpackLayerName, RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS, -} from '../lib/constants' -import type { NextConfigComplete } from '../server/config-shared' -import { defaultOverrides } from '../server/require-hook' +} from 'next/dist/lib/constants' +import type { NextConfigComplete } from 'next/dist/server/config-shared' +import { defaultOverrides } from 'next/dist/server/require-hook' import { hasExternalOtelApiPackage } from './webpack-config' -import { NEXT_PROJECT_ROOT } from './next-dir-paths' -import { shouldUseReactServerCondition } from './utils' +import { shouldUseReactServerCondition } from 'next/dist/build/utils' +import { NEXT_PROJECT_ROOT } from 'next/dist/build/next-dir-paths' interface CompilerAliases { [alias: string]: string | string[] @@ -31,9 +31,8 @@ const isReact19 = typeof React.use === 'function' * `next-instrumentation-client-loader` via a `module.rules` entry in * `webpack-config.ts`. */ -const INSTRUMENTATION_CLIENT_STUB_PATH = path.join( - NEXT_PROJECT_ROOT, - 'dist/build/webpack/loaders/instrumentation-client-stub.js' +const INSTRUMENTATION_CLIENT_STUB_PATH = require.resolve( + './webpack/loaders/instrumentation-client-stub' ) export function createWebpackAliases({ @@ -175,20 +174,20 @@ export function createWebpackAliases({ ...(reactProductionProfiling ? getReactProfilingInProduction() : {}), [RSC_ACTION_VALIDATE_ALIAS]: - 'next/dist/build/webpack/loaders/next-flight-loader/action-validate', + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/action-validate', [RSC_ACTION_CLIENT_WRAPPER_ALIAS]: - 'next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper', + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/action-client-wrapper', [RSC_ACTION_PROXY_ALIAS]: - 'next/dist/build/webpack/loaders/next-flight-loader/server-reference', + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/server-reference', [RSC_ACTION_ENCRYPTION_ALIAS]: 'next/dist/server/app-render/encryption', [RSC_CACHE_WRAPPER_ALIAS]: - 'next/dist/build/webpack/loaders/next-flight-loader/cache-wrapper', + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/cache-wrapper', [RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS]: - 'next/dist/build/webpack/loaders/next-flight-loader/track-dynamic-import', + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/track-dynamic-import', '@swc/helpers/_': path.join( path.dirname(require.resolve('@swc/helpers/package.json')), @@ -364,7 +363,7 @@ export function createVendoredReactAliases( 'react-dom/server$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, 'react-dom/server.browser$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ❌ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ❌ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.browser$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, @@ -391,7 +390,7 @@ export function createVendoredReactAliases( 'react-dom/server$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, 'react-dom/server.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ❌ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ❌ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, @@ -415,7 +414,7 @@ export function createVendoredReactAliases( 'react-dom/server$': /* ❔ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.node`, 'react-dom/server.browser$': /* ❔ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ✅ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ✅ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ❔ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.node`, 'react-dom/static.browser$': /* ❔ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ❔ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, @@ -439,7 +438,7 @@ export function createVendoredReactAliases( 'react-dom/server$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.node`, 'react-dom/server.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ❌ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ❌ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.node`, 'react-dom/static.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, @@ -460,10 +459,10 @@ export function createVendoredReactAliases( // file:///./../compiled/react-dom/package.json 'react-dom$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}`, 'react-dom/client$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/client`, - 'react-dom/server$': /* ✅ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server$': /* ✅ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/server.browser$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ✅ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ✅ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, 'react-dom/static.browser$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, @@ -484,10 +483,10 @@ export function createVendoredReactAliases( // file:///./../compiled/react-dom/package.json 'react-dom$': /* ✅ */ `next/dist/compiled/react-dom${bundledReactChannel}/react-dom.react-server`, 'react-dom/client$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/client`, - 'react-dom/server$': /* ❌ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server$': /* ❌ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/server.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, // optimizations to ignore the legacy build of react-dom/server in `server.edge` build - 'react-dom/server.edge$': /* ❌ */ `next/dist/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, + 'react-dom/server.edge$': /* ❌ */ `next/dist/webpack/build/webpack/alias/react-dom-server${bundledReactChannel}.js`, 'react-dom/static$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, 'react-dom/static.browser$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.browser`, 'react-dom/static.edge$': /* ❌ */ `next/dist/compiled/react-dom${bundledReactChannel}/static.edge`, diff --git a/packages/next/src/webpack/build/entries.ts b/packages/next/src/webpack/build/entries.ts new file mode 100644 index 000000000000..fc2c179e8209 --- /dev/null +++ b/packages/next/src/webpack/build/entries.ts @@ -0,0 +1,776 @@ +import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' +import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' +import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader' +import type { EdgeAppRouteLoaderQuery } from './webpack/loaders/next-edge-app-route-loader' +import type { NextConfigComplete } from 'next/dist/server/config-shared' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { + ProxyConfig, + ProxyMatcher, + PageStaticInfo, +} from 'next/dist/build/analysis/get-page-static-info' +import type { LoadedEnvFiles } from '@next/env' +import type { AppLoaderOptions } from './webpack/loaders/next-app-loader' + +import { posix, join, normalize } from 'path' +import { stringify } from 'querystring' +import { + PAGES_DIR_ALIAS, + ROOT_DIR_ALIAS, + APP_DIR_ALIAS, + WEBPACK_LAYERS, + INSTRUMENTATION_HOOK_FILENAME, +} from 'next/dist/lib/constants' +import { isAPIRoute } from 'next/dist/lib/is-api-route' +import { isEdgeRuntime } from 'next/dist/lib/is-edge-runtime' +import { + APP_CLIENT_INTERNALS, + RSC_MODULE_TYPES, +} from 'next/dist/shared/lib/constants' +import { + CLIENT_STATIC_FILES_RUNTIME_MAIN, + CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, + CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, + CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, + COMPILER_NAMES, + EDGE_RUNTIME_WEBPACK, +} from 'next/dist/shared/lib/constants' +import type { CompilerNameValues } from 'next/dist/shared/lib/constants' +import type { __ApiPreviewProps } from 'next/dist/server/api-utils' +import { + isMiddlewareFile, + isMiddlewareFilename, + isProxyFile, + isInstrumentationHookFile, + isInstrumentationHookFilename, +} from 'next/dist/build/utils' +import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' +import type { ServerRuntime } from 'next/dist/types' +import { + normalizeAppPath, + compareAppPaths, +} from 'next/dist/shared/lib/router/utils/app-paths' +import { encodeMatchers } from './webpack/loaders/next-middleware-loader' +import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' +import { isAppRouteRoute } from 'next/dist/lib/is-app-route-route' +import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' +import { + isInternalComponent, + isNonRoutePagesPage, +} from 'next/dist/lib/is-internal-component' +import { RouteKind } from 'next/dist/server/route-kind' +import { encodeToBase64 } from './webpack/loaders/utils' +import { normalizeCatchAllRoutes } from 'next/dist/build/normalize-catchall-routes' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' +import type { MappedPages } from 'next/dist/build/build-context' +import { PAGE_TYPES } from 'next/dist/lib/page-types' + +type ObjectValue = T extends { [key: string]: infer V } ? V : never +import { getStaticInfoIncludingLayouts } from 'next/dist/build/get-static-info-including-layouts' +import { getPageFromPath } from 'next/dist/build/route-discovery' + +export function getPageFilePath({ + absolutePagePath, + pagesDir, + appDir, + rootDir, +}: { + absolutePagePath: string + pagesDir: string | undefined + appDir: string | undefined + rootDir: string +}) { + if (absolutePagePath.startsWith(PAGES_DIR_ALIAS) && pagesDir) { + return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir) + } + + if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) { + return absolutePagePath.replace(APP_DIR_ALIAS, appDir) + } + + if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) { + return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir) + } + + return require.resolve(absolutePagePath) +} + +export interface CreateEntrypointsParams { + buildId: string + config: NextConfigComplete + envFiles: LoadedEnvFiles + isDev: boolean + pages: MappedPages + pagesDir?: string + previewMode: __ApiPreviewProps + rootDir: string + rootPaths?: MappedPages + appDir?: string + appPaths?: MappedPages + pageExtensions: PageExtensions + hasInstrumentationHook?: boolean + /** + * When set to 'exclude', deferred entries are excluded from the result. + * When set to 'only', only deferred entries are included in the result. + * When undefined, all entries are included. + */ + deferredEntriesFilter?: 'exclude' | 'only' +} + +/** + * Checks if a page path matches any of the deferred entry patterns. + * @param page - The page path (e.g., '/about', '/api/hello') + * @param deferredEntries - Array of path patterns to match against + * @returns true if the page matches a deferred entry pattern + */ +export function isDeferredEntry( + page: string, + deferredEntries: string[] | undefined +): boolean { + if (!deferredEntries || deferredEntries.length === 0) { + return false + } + + // Normalize the page path + const normalizedPage = page.startsWith('/') ? page : `/${page}` + + for (const pattern of deferredEntries) { + // Normalize the pattern + const normalizedPattern = pattern.startsWith('/') ? pattern : `/${pattern}` + + // Check for exact match or prefix match for directories + if (normalizedPage === normalizedPattern) { + return true + } + + // Check if the page is under the deferred directory + if (normalizedPage.startsWith(normalizedPattern + '/')) { + return true + } + } + + return false +} + +export function getEdgeServerEntry(opts: { + rootDir: string + absolutePagePath: string + buildId: string + bundlePath: string + config: NextConfigComplete + isDev: boolean + isServerComponent: boolean + page: string + pages: MappedPages + middleware?: Partial + pagesType: PAGE_TYPES + appDirLoader?: string + hasInstrumentationHook?: boolean + preferredRegion: string | string[] | undefined + middlewareConfig?: ProxyConfig +}) { + const cacheHandler = opts.config.cacheHandler || undefined + + if ( + opts.pagesType === 'app' && + isAppRouteRoute(opts.page) && + opts.appDirLoader + ) { + const loaderParams: EdgeAppRouteLoaderQuery = { + absolutePagePath: opts.absolutePagePath, + page: opts.page, + appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), + preferredRegion: opts.preferredRegion, + middlewareConfig: Buffer.from( + JSON.stringify(opts.middlewareConfig || {}) + ).toString('base64'), + cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}), + ...(cacheHandler ? { cacheHandler } : {}), + } + + return { + import: `next-edge-app-route-loader?${stringify(loaderParams)}!`, + layer: WEBPACK_LAYERS.reactServerComponents, + } + } + + if (isMiddlewareFile(opts.page)) { + const loaderParams: MiddlewareLoaderOptions = { + absolutePagePath: opts.absolutePagePath, + page: opts.page, + rootDir: opts.rootDir, + matchers: opts.middleware?.matchers + ? encodeMatchers(opts.middleware.matchers) + : '', + preferredRegion: opts.preferredRegion, + middlewareConfig: Buffer.from( + JSON.stringify(opts.middlewareConfig || {}) + ).toString('base64'), + ...(cacheHandler ? { cacheHandler } : {}), + } + + return { + import: `next-middleware-loader?${stringify(loaderParams)}!`, + layer: WEBPACK_LAYERS.middleware, + filename: opts.isDev ? 'middleware.js' : undefined, + } + } + + if (isAPIRoute(opts.page)) { + const loaderParams: EdgeFunctionLoaderOptions = { + absolutePagePath: opts.absolutePagePath, + page: opts.page, + rootDir: opts.rootDir, + preferredRegion: opts.preferredRegion, + middlewareConfig: Buffer.from( + JSON.stringify(opts.middlewareConfig || {}) + ).toString('base64'), + ...(cacheHandler ? { cacheHandler } : {}), + } + + return { + import: `next-edge-function-loader?${stringify(loaderParams)}!`, + layer: WEBPACK_LAYERS.apiEdge, + } + } + + const loaderParams: EdgeSSRLoaderQuery = { + absolute500Path: opts.pages['/500'] || '', + absoluteAppPath: opts.pages['/_app'], + absoluteDocumentPath: opts.pages['/_document'], + absoluteErrorPath: opts.pages['/_error'], + absolutePagePath: opts.absolutePagePath, + dev: opts.isDev, + isServerComponent: opts.isServerComponent, + page: opts.page, + pagesType: opts.pagesType, + appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'), + sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm, + preferredRegion: opts.preferredRegion, + middlewareConfig: Buffer.from( + JSON.stringify(opts.middlewareConfig || {}) + ).toString('base64'), + serverActions: opts.config.experimental.serverActions, + cacheHandlers: JSON.stringify(opts.config.cacheHandlers || {}), + ...(cacheHandler ? { cacheHandler } : {}), + } + + return { + import: `next-edge-ssr-loader?${JSON.stringify(loaderParams)}!`, + // The Edge bundle includes the server in its entrypoint, so it has to + // be in the SSR layer — we later convert the page request to the RSC layer + // via a webpack rule. + layer: opts.appDirLoader ? WEBPACK_LAYERS.serverSideRendering : undefined, + } +} + +export function getInstrumentationEntry(opts: { + absolutePagePath: string + isEdgeServer: boolean + isDev: boolean +}) { + // the '../' is needed to make sure the file is not chunked + const filename = `${ + opts.isEdgeServer ? 'edge-' : opts.isDev ? '' : '../' + }${INSTRUMENTATION_HOOK_FILENAME}.js` + + return { + import: opts.absolutePagePath, + filename, + layer: WEBPACK_LAYERS.instrument, + } +} + +export function getAppLoader() { + return process.env.BUILTIN_APP_LOADER + ? `builtin:next-app-loader` + : 'next-app-loader' +} + +export function getAppEntry(opts: Readonly) { + if (process.env.NEXT_RSPACK && process.env.BUILTIN_APP_LOADER) { + ;(opts as any).projectRoot = normalize(join(__dirname, '../../../..')) + } + return { + import: `${getAppLoader()}?${stringify(opts)}!`, + layer: WEBPACK_LAYERS.reactServerComponents, + } +} + +export function getClientEntry(opts: { + absolutePagePath: string + page: string +}) { + const loaderOptions: ClientPagesLoaderOptions = { + absolutePagePath: opts.absolutePagePath, + page: opts.page, + } + + const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!` + + // Make sure next/router is a dependency of _app or else chunk splitting + // might cause the router to not be able to load causing hydration + // to fail + return opts.page === '/_app' + ? [pageLoader, require.resolve('next/dist/client/router')] + : pageLoader +} + +export function runDependingOnPageType(params: { + onClient: () => T + onEdgeServer: () => T + onServer: () => T + page: string + pageRuntime: ServerRuntime + pageType?: PAGE_TYPES +}): void { + if ( + params.pageType === PAGE_TYPES.ROOT && + isInstrumentationHookFile(params.page) + ) { + params.onServer() + params.onEdgeServer() + return + } + + if (isProxyFile(params.page)) { + params.onServer() + return + } + + if (isMiddlewareFile(params.page)) { + if (params.pageRuntime === 'nodejs') { + params.onServer() + return + } else { + params.onEdgeServer() + return + } + } + + if (isAPIRoute(params.page)) { + if (isEdgeRuntime(params.pageRuntime)) { + params.onEdgeServer() + return + } + + params.onServer() + return + } + if (params.page === '/_document') { + params.onServer() + return + } + if ( + params.page === '/_app' || + params.page === '/_error' || + params.page === '/404' || + params.page === '/500' + ) { + params.onClient() + params.onServer() + return + } + if (isEdgeRuntime(params.pageRuntime)) { + params.onClient() + params.onEdgeServer() + return + } + + params.onClient() + params.onServer() + return +} + +export async function createEntrypoints( + params: CreateEntrypointsParams +): Promise<{ + client: webpack.EntryObject + server: webpack.EntryObject + edgeServer: webpack.EntryObject + middlewareMatchers: undefined +}> { + const { + config, + pages, + pagesDir, + isDev, + rootDir, + rootPaths, + appDir, + appPaths, + pageExtensions, + deferredEntriesFilter, + } = params + + const deferredEntries = config.experimental.deferredEntries + const edgeServer: webpack.EntryObject = {} + const server: webpack.EntryObject = {} + const client: webpack.EntryObject = {} + let middlewareMatchers: ProxyMatcher[] | undefined = undefined + + let appPathsPerRoute: Record = {} + if (appDir && appPaths) { + for (const pathname in appPaths) { + const normalizedPath = normalizeAppPath(pathname) + const actualPath = appPaths[pathname] + if (!appPathsPerRoute[normalizedPath]) { + appPathsPerRoute[normalizedPath] = [] + } + appPathsPerRoute[normalizedPath].push( + // TODO-APP: refactor to pass the page path from createPagesMapping instead. + getPageFromPath(actualPath, pageExtensions).replace(APP_DIR_ALIAS, '') + ) + } + + // TODO: find a better place to do this + normalizeCatchAllRoutes(appPathsPerRoute) + + // Make sure to sort parallel routes to make the result deterministic. + appPathsPerRoute = Object.fromEntries( + Object.entries(appPathsPerRoute).map(([k, v]) => [ + k, + v.sort(compareAppPaths), + ]) + ) + } + + const getEntryHandler = + (mappings: MappedPages, pagesType: PAGE_TYPES): ((page: string) => void) => + async (page) => { + // Apply deferred entries filter if specified + if (deferredEntriesFilter) { + const isDeferred = isDeferredEntry(page, deferredEntries) + if (deferredEntriesFilter === 'exclude' && isDeferred) { + // Skip deferred entries when excluding them + return + } + if (deferredEntriesFilter === 'only' && !isDeferred) { + // Skip non-deferred entries when only including deferred ones + return + } + } + + const bundleFile = normalizePagePath(page) + const clientBundlePath = posix.join(pagesType, bundleFile) + const serverBundlePath = + pagesType === PAGE_TYPES.PAGES + ? posix.join('pages', bundleFile) + : pagesType === PAGE_TYPES.APP + ? posix.join('app', bundleFile) + : bundleFile.slice(1) + + const absolutePagePath = mappings[page] + + // Handle paths that have aliases + const pageFilePath = getPageFilePath({ + absolutePagePath, + pagesDir, + appDir, + rootDir, + }) + + const isInsideAppDir = + !!appDir && + (absolutePagePath.startsWith(APP_DIR_ALIAS) || + absolutePagePath.startsWith(appDir)) + + const staticInfo: PageStaticInfo = await getStaticInfoIncludingLayouts({ + isInsideAppDir, + pageExtensions, + pageFilePath, + appDir, + config, + isDev, + page, + }) + + // TODO(timneutkens): remove this + const isServerComponent = + isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client + + if (isMiddlewareFile(page)) { + middlewareMatchers = staticInfo.middleware?.matchers ?? [ + { regexp: '.*', originalSource: '/:path*' }, + ] + } + + const isInstrumentation = + isInstrumentationHookFile(page) && pagesType === PAGE_TYPES.ROOT + + runDependingOnPageType({ + page, + pageRuntime: staticInfo.runtime, + pageType: pagesType, + onClient: () => { + if (isServerComponent || isInsideAppDir) { + // We skip the initial entries for server component pages and let the + // server compiler inject them instead. + } else { + client[clientBundlePath] = getClientEntry({ + absolutePagePath, + page, + }) + } + }, + onServer: () => { + if (pagesType === 'app' && appDir) { + const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)] + server[serverBundlePath] = getAppEntry({ + page, + name: serverBundlePath, + pagePath: absolutePagePath, + appDir, + appPaths: matchedAppPaths, + allNormalizedAppPaths: Object.keys(appPathsPerRoute), + pageExtensions, + basePath: config.basePath, + assetPrefix: config.assetPrefix, + nextConfigOutput: config.output, + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: encodeToBase64(staticInfo.middleware || {}), + isGlobalNotFoundEnabled: config.experimental.globalNotFound + ? true + : undefined, + }) + } else if (isInstrumentation) { + server[serverBundlePath.replace('src/', '')] = + getInstrumentationEntry({ + absolutePagePath, + isEdgeServer: false, + isDev: false, + }) + } else if (isMiddlewareFile(page)) { + server[serverBundlePath.replace('src/', '')] = getEdgeServerEntry({ + ...params, + rootDir, + absolutePagePath: absolutePagePath, + bundlePath: clientBundlePath, + isDev: false, + isServerComponent, + page, + middleware: staticInfo?.middleware, + pagesType, + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: staticInfo.middleware, + }) + } else if (isAPIRoute(page)) { + server[serverBundlePath] = [ + getRouteLoaderEntry({ + kind: RouteKind.PAGES_API, + page, + absolutePagePath, + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: staticInfo.middleware || {}, + }), + ] + } else if ( + !isMiddlewareFile(page) && + !isInternalComponent(absolutePagePath) && + !isNonRoutePagesPage(page) + ) { + server[serverBundlePath] = [ + getRouteLoaderEntry({ + kind: RouteKind.PAGES, + page, + pages, + absolutePagePath, + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: staticInfo.middleware ?? {}, + }), + ] + } else { + server[serverBundlePath] = [absolutePagePath] + } + }, + onEdgeServer: () => { + let appDirLoader: string = '' + if (isInstrumentation) { + edgeServer[serverBundlePath.replace('src/', '')] = + getInstrumentationEntry({ + absolutePagePath, + isEdgeServer: true, + isDev: false, + }) + } else { + if (pagesType === 'app') { + const matchedAppPaths = appPathsPerRoute[normalizeAppPath(page)] + appDirLoader = getAppEntry({ + name: serverBundlePath, + page, + pagePath: absolutePagePath, + appDir: appDir!, + appPaths: matchedAppPaths, + allNormalizedAppPaths: Object.keys(appPathsPerRoute), + pageExtensions, + basePath: config.basePath, + assetPrefix: config.assetPrefix, + nextConfigOutput: config.output, + // This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead. + // Still passing it here for consistency. + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: Buffer.from( + JSON.stringify(staticInfo.middleware || {}) + ).toString('base64'), + isGlobalNotFoundEnabled: config.experimental.globalNotFound + ? true + : undefined, + }).import + } + edgeServer[serverBundlePath] = getEdgeServerEntry({ + ...params, + rootDir, + absolutePagePath: absolutePagePath, + bundlePath: clientBundlePath, + isDev: false, + isServerComponent, + page, + middleware: staticInfo?.middleware, + pagesType, + appDirLoader, + preferredRegion: staticInfo.preferredRegion, + middlewareConfig: staticInfo.middleware, + }) + } + }, + }) + } + + const promises: Promise[] = [] + + if (appPaths) { + const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP) + promises.push(Promise.all(Object.keys(appPaths).map(entryHandler))) + } + if (rootPaths) { + promises.push( + Promise.all( + Object.keys(rootPaths).map(getEntryHandler(rootPaths, PAGE_TYPES.ROOT)) + ) + ) + } + promises.push( + Promise.all( + Object.keys(pages).map(getEntryHandler(pages, PAGE_TYPES.PAGES)) + ) + ) + + await Promise.all(promises) + + // Optimization: If there's only one instrumentation hook in edge compiler, which means there's no edge server entry. + // We remove the edge instrumentation entry from edge compiler as it can be pure server side. + if (edgeServer.instrumentation && Object.keys(edgeServer).length === 1) { + delete edgeServer.instrumentation + } + + return { + client, + server, + edgeServer, + middlewareMatchers, + } +} + +export function finalizeEntrypoint({ + name, + compilerType, + value, + isServerComponent, + hasAppDir, +}: { + compilerType: CompilerNameValues + name: string + value: ObjectValue + isServerComponent?: boolean + hasAppDir?: boolean +}): ObjectValue { + const entry = + typeof value !== 'object' || Array.isArray(value) + ? { import: value } + : value + + const isApi = name.startsWith('pages/api/') + const isInstrumentation = isInstrumentationHookFilename(name) + + switch (compilerType) { + case COMPILER_NAMES.server: { + const layer = isApi + ? WEBPACK_LAYERS.apiNode + : isInstrumentation + ? WEBPACK_LAYERS.instrument + : isServerComponent + ? WEBPACK_LAYERS.reactServerComponents + : name.startsWith('pages/') + ? WEBPACK_LAYERS.pagesDirNode + : undefined + + return { + publicPath: isApi ? '' : undefined, + runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime', + layer, + ...entry, + } + } + case COMPILER_NAMES.edgeServer: { + return { + layer: isApi + ? WEBPACK_LAYERS.apiEdge + : isMiddlewareFilename(name) || isInstrumentation + ? WEBPACK_LAYERS.middleware + : name.startsWith('pages/') + ? WEBPACK_LAYERS.pagesDirEdge + : undefined, + library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' }, + runtime: EDGE_RUNTIME_WEBPACK, + asyncChunks: false, + ...entry, + } + } + case COMPILER_NAMES.client: { + const isAppLayer = + hasAppDir && + (name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || + name === APP_CLIENT_INTERNALS || + name.startsWith('app/')) + + if ( + // Client special cases + name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && + name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && + name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && + name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH + ) { + if (isAppLayer) { + return { + dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, + layer: WEBPACK_LAYERS.appPagesBrowser, + ...entry, + } + } + + return { + dependOn: + name.startsWith('pages/') && name !== 'pages/_app' + ? 'pages/_app' + : CLIENT_STATIC_FILES_RUNTIME_MAIN, + layer: WEBPACK_LAYERS.pagesDirBrowser, + ...entry, + } + } + + if (isAppLayer) { + return { + layer: WEBPACK_LAYERS.appPagesBrowser, + ...entry, + } + } + + return { + layer: WEBPACK_LAYERS.pagesDirBrowser, + ...entry, + } + } + default: + return compilerType satisfies never + } +} diff --git a/packages/next/src/build/get-babel-loader-config.ts b/packages/next/src/webpack/build/get-babel-loader-config.ts similarity index 92% rename from packages/next/src/build/get-babel-loader-config.ts rename to packages/next/src/webpack/build/get-babel-loader-config.ts index 523e2fa6f2d1..c625cf9456cf 100644 --- a/packages/next/src/build/get-babel-loader-config.ts +++ b/packages/next/src/webpack/build/get-babel-loader-config.ts @@ -1,7 +1,10 @@ import type { EnvironmentConfig } from 'babel-plugin-react-compiler' import path from 'path' -import type { JSONValue, ReactCompilerOptions } from '../server/config-shared' -import type { NextBabelLoaderOptions } from './babel/loader/types' +import type { + JSONValue, + ReactCompilerOptions, +} from 'next/dist/server/config-shared' +import type { NextBabelLoaderOptions } from 'next/dist/build/babel/loader/types' function getReactCompiler() { try { @@ -88,7 +91,7 @@ const getBabelLoader = ( reactCompilerExclude, } return { - loader: require.resolve('./babel/loader/index'), + loader: require.resolve('next/dist/build/babel/loader/index'), options, } } @@ -130,7 +133,7 @@ const getReactCompilerLoader = ( } return { - loader: require.resolve('./babel/loader/index'), + loader: require.resolve('next/dist/build/babel/loader/index'), options: babelLoaderOptions, } } diff --git a/packages/next/src/build/handle-externals.ts b/packages/next/src/webpack/build/handle-externals.ts similarity index 96% rename from packages/next/src/build/handle-externals.ts rename to packages/next/src/webpack/build/handle-externals.ts index af585379bcb7..bcbba6ca091b 100644 --- a/packages/next/src/build/handle-externals.ts +++ b/packages/next/src/webpack/build/handle-externals.ts @@ -1,17 +1,20 @@ -import type { WebpackLayerName } from '../lib/constants' -import type { NextConfigComplete } from '../server/config-shared' +import type { WebpackLayerName } from 'next/dist/lib/constants' +import type { NextConfigComplete } from 'next/dist/server/config-shared' import type { ResolveOptions } from 'webpack' -import { defaultOverrides } from '../server/require-hook' -import { BARREL_OPTIMIZATION_PREFIX } from '../shared/lib/constants' -import path from '../shared/lib/isomorphic/path' +import { defaultOverrides } from 'next/dist/server/require-hook' +import { BARREL_OPTIMIZATION_PREFIX } from 'next/dist/shared/lib/constants' +import path from 'next/dist/shared/lib/isomorphic/path' import { NODE_BASE_ESM_RESOLVE_OPTIONS, NODE_BASE_RESOLVE_OPTIONS, NODE_ESM_RESOLVE_OPTIONS, NODE_RESOLVE_OPTIONS, } from './webpack-config' -import { isWebpackBundledLayer, shouldUseReactServerCondition } from './utils' -import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' +import { + isWebpackBundledLayer, + shouldUseReactServerCondition, +} from 'next/dist/build/utils' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/ const pathSeparators = '[/\\\\]' diff --git a/packages/next/src/build/webpack-build/impl.ts b/packages/next/src/webpack/build/webpack-build/impl.ts similarity index 93% rename from packages/next/src/build/webpack-build/impl.ts rename to packages/next/src/webpack/build/webpack-build/impl.ts index 4eb04a1ab86f..15aca801cbe8 100644 --- a/packages/next/src/build/webpack-build/impl.ts +++ b/packages/next/src/webpack/build/webpack-build/impl.ts @@ -1,21 +1,21 @@ // Import cpu-profile first to start profiling early if enabled -import { saveCpuProfile } from '../../server/lib/cpu-profile' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import { saveCpuProfile } from 'next/dist/server/lib/cpu-profile' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { stringBufferUtils } from 'next/dist/compiled/webpack-sources3' -import { red } from '../../lib/picocolors' -import formatWebpackMessages from '../../shared/lib/format-webpack-messages' -import { nonNullable } from '../../lib/non-nullable' -import type { COMPILER_INDEXES } from '../../shared/lib/constants' +import { red } from 'next/dist/lib/picocolors' +import formatWebpackMessages from 'next/dist/shared/lib/format-webpack-messages' +import { nonNullable } from 'next/dist/lib/non-nullable' +import type { COMPILER_INDEXES } from 'next/dist/shared/lib/constants' import { COMPILER_NAMES, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, APP_CLIENT_INTERNALS, PHASE_PRODUCTION_BUILD, -} from '../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' import { runCompiler } from '../compiler' -import * as Log from '../output/log' +import * as Log from 'next/dist/build/output/log' import getBaseWebpackConfig, { loadProjectInfo } from '../webpack-config' -import type { NextError } from '../../lib/is-error' +import type { NextError } from 'next/dist/lib/is-error' import { TelemetryPlugin, type TelemetryPluginState, @@ -24,9 +24,9 @@ import { NextBuildContext, resumePluginState, getPluginState, -} from '../build-context' +} from 'next/dist/build/build-context' import { createEntrypoints } from '../entries' -import loadConfig from '../../server/config' +import loadConfig from 'next/dist/server/config' import { getTraceEvents, initializeTraceState, @@ -34,17 +34,20 @@ import { trace, type TraceEvent, type TraceState, -} from '../../trace' -import { WEBPACK_LAYERS } from '../../lib/constants' +} from 'next/dist/trace' +import { WEBPACK_LAYERS } from 'next/dist/lib/constants' import { TraceEntryPointsPlugin } from '../webpack/plugins/next-trace-entrypoints-plugin' import type { BuildTraceContext } from '../webpack/plugins/next-trace-entrypoints-plugin' -import type { UnwrapPromise } from '../../lib/coalesced-function' +import type { UnwrapPromise } from 'next/dist/lib/coalesced-function' import origDebug from 'next/dist/compiled/debug' -import { Telemetry } from '../../telemetry/storage' -import { durationToString, hrtimeToSeconds } from '../duration-to-string' -import { installBindings } from '../swc/install-bindings' -import { Bundler } from '../../lib/bundler' +import { Telemetry } from 'next/dist/telemetry/storage' +import { + durationToString, + hrtimeToSeconds, +} from 'next/dist/build/duration-to-string' +import { installBindings } from 'next/dist/build/swc/install-bindings' +import { Bundler } from 'next/dist/lib/bundler' const debug = origDebug('next:build:webpack-build') diff --git a/packages/next/src/build/webpack-build/index.ts b/packages/next/src/webpack/build/webpack-build/index.ts similarity index 93% rename from packages/next/src/build/webpack-build/index.ts rename to packages/next/src/webpack/build/webpack-build/index.ts index 61f6aa58ab6b..e750e42eb9db 100644 --- a/packages/next/src/build/webpack-build/index.ts +++ b/packages/next/src/webpack/build/webpack-build/index.ts @@ -1,13 +1,13 @@ -import type { COMPILER_INDEXES } from '../../shared/lib/constants' -import * as Log from '../output/log' -import { NextBuildContext } from '../build-context' +import type { COMPILER_INDEXES } from 'next/dist/shared/lib/constants' +import * as Log from 'next/dist/build/output/log' +import { NextBuildContext } from 'next/dist/build/build-context' import type { BuildTraceContext } from '../webpack/plugins/next-trace-entrypoints-plugin' -import { Worker } from '../../lib/worker' +import { Worker } from 'next/dist/lib/worker' import origDebug from 'next/dist/compiled/debug' import path from 'path' -import { exportTraceState, recordTraceEvents } from '../../trace' +import { exportTraceState, recordTraceEvents } from 'next/dist/trace' import { mergeUseCacheTrackers } from '../webpack/plugins/telemetry-plugin/use-cache-tracker-utils' -import { durationToString } from '../duration-to-string' +import { durationToString } from 'next/dist/build/duration-to-string' const debug = origDebug('next:build:webpack-build') diff --git a/packages/next/src/build/webpack-config-rules/resolve.ts b/packages/next/src/webpack/build/webpack-config-rules/resolve.ts similarity index 95% rename from packages/next/src/build/webpack-config-rules/resolve.ts rename to packages/next/src/webpack/build/webpack-config-rules/resolve.ts index ef88d8296e95..1ee614b8b848 100644 --- a/packages/next/src/build/webpack-config-rules/resolve.ts +++ b/packages/next/src/webpack/build/webpack-config-rules/resolve.ts @@ -1,7 +1,7 @@ import { COMPILER_NAMES, type CompilerNameValues, -} from '../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' export const edgeConditionName = 'edge-light' diff --git a/packages/next/src/build/webpack-config.ts b/packages/next/src/webpack/build/webpack-config.ts similarity index 97% rename from packages/next/src/build/webpack-config.ts rename to packages/next/src/webpack/build/webpack-config.ts index 59be2705f54e..d59b47b27ba6 100644 --- a/packages/next/src/build/webpack-config.ts +++ b/packages/next/src/webpack/build/webpack-config.ts @@ -1,23 +1,26 @@ import React from 'react' import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin' -import { yellow, bold } from '../lib/picocolors' +import { yellow, bold } from 'next/dist/lib/picocolors' import crypto from 'crypto' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import path from 'path' import fs from 'fs' -import { getDefineEnv } from './define-env' -import { escapeStringRegexp } from '../shared/lib/escape-regexp' -import { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES } from '../lib/constants' -import type { WebpackLayerName } from '../lib/constants' +import { getDefineEnv } from 'next/dist/build/define-env' +import { escapeStringRegexp } from 'next/dist/shared/lib/escape-regexp' +import { + WEBPACK_LAYERS, + WEBPACK_RESOURCE_QUERIES, +} from 'next/dist/lib/constants' +import type { WebpackLayerName } from 'next/dist/lib/constants' import { isWebpackBundledLayer, isWebpackClientOnlyLayer, shouldUseReactServerCondition, isWebpackDefaultLayer, RSPACK_DEFAULT_LAYERS_REGEX, -} from './utils' -import type { CustomRoutes } from '../lib/load-custom-routes.js' +} from 'next/dist/build/utils' +import type { CustomRoutes } from 'next/dist/lib/load-custom-routes' import { CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, @@ -28,13 +31,13 @@ import { REACT_LOADABLE_MANIFEST, SERVER_DIRECTORY, COMPILER_NAMES, -} from '../shared/lib/constants' -import type { CompilerNameValues } from '../shared/lib/constants' -import { execOnce } from '../shared/lib/utils' -import type { NextConfigComplete } from '../server/config-shared' -import { resolveCssChunkingMode } from '../server/config-shared' +} from 'next/dist/shared/lib/constants' +import type { CompilerNameValues } from 'next/dist/shared/lib/constants' +import { execOnce } from 'next/dist/shared/lib/utils' +import type { NextConfigComplete } from 'next/dist/server/config-shared' +import { resolveCssChunkingMode } from 'next/dist/server/config-shared' import { finalizeEntrypoint } from './entries' -import * as Log from './output/log' +import * as Log from 'next/dist/build/output/log' import { buildConfiguration } from './webpack/config' import ForceCompleteRuntimePlugin from './webpack/plugins/force-complete-runtime' import MiddlewarePlugin, { @@ -58,18 +61,18 @@ import type { Feature, SWC_TARGET_TRIPLE, } from './webpack/plugins/telemetry-plugin/telemetry-plugin' -import type { Span } from '../trace' -import type { ProxyMatcher } from './analysis/get-page-static-info' +import type { Span } from 'next/dist/trace' +import type { ProxyMatcher } from 'next/dist/build/analysis/get-page-static-info' import loadJsConfig, { type JsConfig, type ResolvedBaseUrl, -} from './load-jsconfig' +} from 'next/dist/build/load-jsconfig' import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin' import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin' -import { getSupportedBrowsers } from './get-supported-browsers' +import { getSupportedBrowsers } from 'next/dist/build/get-supported-browsers' import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin' -import { getBabelConfigFile } from './get-babel-config-file' -import { needsExperimentalReact } from '../lib/needs-experimental-react' +import { getBabelConfigFile } from 'next/dist/build/get-babel-config-file' +import { needsExperimentalReact } from 'next/dist/lib/needs-experimental-react' import type { SWCLoaderOptions } from './webpack/loaders/next-swc-loader' import { isResourceInPackages, makeExternalHandler } from './handle-externals' import { getMainField, edgeConditionName } from './webpack-config-rules/resolve' @@ -81,7 +84,7 @@ import { createNextApiEsmAliases, createAppRouterApiAliases, } from './create-compiler-aliases' -import { hasCustomExportOutput } from '../export/utils' +import { hasCustomExportOutput } from 'next/dist/export/utils' import { CssChunkingPlugin } from './webpack/plugins/css-chunking-plugin' import { getBabelLoader, @@ -90,16 +93,19 @@ import { import { NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT_DIST_CLIENT, -} from './next-dir-paths' -import { getRspackCore } from '../shared/lib/get-rspack' +} from 'next/dist/build/next-dir-paths' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' import { RspackProfilingPlugin } from './webpack/plugins/rspack-profiling-plugin' import getWebpackBundler from '../shared/lib/get-webpack-bundler' -import type { NextBuildContext } from './build-context' +import type { NextBuildContext } from 'next/dist/build/build-context' import type { RootParamsLoaderOpts } from './webpack/loaders/next-root-params-loader' import type { InvalidImportLoaderOpts } from './webpack/loaders/next-invalid-import-error-loader' -import { defaultOverrides } from '../server/require-hook' +import { defaultOverrides } from 'next/dist/server/require-hook' import JSON5 from 'next/dist/compiled/json5' +const nextVersion = (require('next/package.json') as { version: string }) + .version + type ExcludesFalse = (x: T | false) => x is T type ClientEntries = { [key: string]: string | string[] @@ -107,13 +113,13 @@ type ClientEntries = { const EXTERNAL_PACKAGES = JSON5.parse( fs.readFileSync( - path.join(__dirname, '../lib/server-external-packages.jsonc'), + require.resolve('next/dist/lib/server-external-packages.jsonc'), 'utf8' ) ) as string[] const DEFAULT_TRANSPILED_PACKAGES = - require('../lib/default-transpiled-packages.json') as string[] + require('next/dist/lib/default-transpiled-packages.json') as string[] if (parseInt(React.version) < 18) { throw new Error('Next.js requires react >= 18.2.0 to be installed.') @@ -365,10 +371,10 @@ export default async function getBaseWebpackConfig( supportedBrowsers: string[] | undefined clientRouterFilters?: { staticFilter: ReturnType< - import('../shared/lib/bloom-filter').BloomFilter['export'] + import('next/dist/shared/lib/bloom-filter').BloomFilter['export'] > dynamicFilter: ReturnType< - import('../shared/lib/bloom-filter').BloomFilter['export'] + import('next/dist/shared/lib/bloom-filter').BloomFilter['export'] > } fetchCacheKeyPrefix?: string @@ -414,7 +420,7 @@ export default async function getBaseWebpackConfig( if (useSWCLoader) { // TODO: we do not collect wasm target yet const binaryTarget = ( - require('./swc') as typeof import('./swc') + require('next/dist/build/swc') as typeof import('next/dist/build/swc') )?.getBinaryMetadata?.()?.target as SWC_TARGET_TRIPLE SWCBinaryTarget = binaryTarget ? [`swc/target/${binaryTarget}` as const, true] @@ -513,7 +519,7 @@ export default async function getBaseWebpackConfig( // to collect correct trace spans when they are called. swcTraceProfilingInitialized = true ;( - require('./swc') as typeof import('./swc') + require('next/dist/build/swc') as typeof import('next/dist/build/swc') )?.initCustomTraceSubscriber?.( path.join(distDir, `swc-trace-profile-${Date.now()}.json`) ) @@ -789,7 +795,7 @@ export default async function getBaseWebpackConfig( ...(isClient ? { fallback: { - process: require.resolve('./polyfills/process'), + process: require.resolve('next/dist/build/polyfills/process'), }, } : undefined), @@ -1808,7 +1814,9 @@ export default async function getBaseWebpackConfig( { resolve: { fallback: { - process: require.resolve('./polyfills/process'), + process: require.resolve( + 'next/dist/build/polyfills/process' + ), }, }, }, @@ -1874,7 +1882,9 @@ export default async function getBaseWebpackConfig( punycode: require.resolve( 'next/dist/compiled/punycode' ), - process: require.resolve('./polyfills/process'), + process: require.resolve( + 'next/dist/build/polyfills/process' + ), // Handled in separate alias querystring: require.resolve( 'next/dist/compiled/querystring-es3' @@ -1926,7 +1936,7 @@ export default async function getBaseWebpackConfig( // `export { a } from 'next-flight-server-reference-proxy-loader?id=idOfA&name=a! // `export { b } from 'next-flight-server-reference-proxy-loader?id=idOfB&name=b! { - test: /[\\/]next[\\/]dist[\\/](esm[\\/])?build[\\/]webpack[\\/]loaders[\\/]next-flight-loader[\\/]action-client-wrapper\.js/, + test: /[\\/]next[\\/]dist[\\/](esm[\\/])?webpack[\\/]build[\\/]webpack[\\/]loaders[\\/]next-flight-loader[\\/]action-client-wrapper\.js/, sideEffects: false, }, // The placeholder file aliased from `private-next-instrumentation-client`. @@ -1935,7 +1945,7 @@ export default async function getBaseWebpackConfig( // the user's `instrumentation-client.{pageExt}` (composing // `onRouterTransitionStart` hooks across all of them). { - test: /[\\/]next[\\/]dist[\\/](esm[\\/])?build[\\/]webpack[\\/]loaders[\\/]instrumentation-client-stub\.js$/, + test: /[\\/]next[\\/]dist[\\/](esm[\\/])?webpack[\\/]build[\\/]webpack[\\/]loaders[\\/]instrumentation-client-stub\.js$/, use: { loader: 'next-instrumentation-client-loader', options: { @@ -2156,8 +2166,10 @@ export default async function getBaseWebpackConfig( isClient && new CopyFilePlugin({ // file path to build output of `@next/polyfill-nomodule` - filePath: require.resolve('./polyfills/polyfill-nomodule'), - cacheKey: process.env.__NEXT_VERSION as string, + filePath: require.resolve( + 'next/dist/build/polyfills/polyfill-nomodule' + ), + cacheKey: process.env.__NEXT_VERSION ?? nextVersion, name: `static/chunks/polyfills${dev ? '' : '-[hash]'}.js`, minimize: false, info: { @@ -2402,7 +2414,7 @@ export default async function getBaseWebpackConfig( // - Next.js location on disk (some loaders use absolute paths and some resolve options depend on absolute paths) // - Next.js version // - next.config.js keys that affect compilation - version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}`, + version: `${__dirname}|${process.env.__NEXT_VERSION ?? nextVersion}|${configVars}`, cacheDirectory: path.join(distDir, 'cache', 'webpack'), // For production builds, it's more efficient to compress all cache files together instead of compression each one individually. // So we disable compression here and allow the build runner to take care of compressing the cache as a whole. @@ -2460,7 +2472,7 @@ export default async function getBaseWebpackConfig( type: 'filesystem', directory: cache.cacheDirectory, }, - version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}`, + version: `${__dirname}|${process.env.__NEXT_VERSION ?? nextVersion}|${configVars}`, } } diff --git a/packages/next/src/build/webpack/alias/react-dom-server-experimental.js b/packages/next/src/webpack/build/webpack/alias/react-dom-server-experimental.js similarity index 100% rename from packages/next/src/build/webpack/alias/react-dom-server-experimental.js rename to packages/next/src/webpack/build/webpack/alias/react-dom-server-experimental.js diff --git a/packages/next/src/build/webpack/alias/react-dom-server.js b/packages/next/src/webpack/build/webpack/alias/react-dom-server.js similarity index 100% rename from packages/next/src/build/webpack/alias/react-dom-server.js rename to packages/next/src/webpack/build/webpack/alias/react-dom-server.js diff --git a/packages/next/src/build/webpack/cache-invalidation.ts b/packages/next/src/webpack/build/webpack/cache-invalidation.ts similarity index 100% rename from packages/next/src/build/webpack/cache-invalidation.ts rename to packages/next/src/webpack/build/webpack/cache-invalidation.ts diff --git a/packages/next/src/build/webpack/config/blocks/base.ts b/packages/next/src/webpack/build/webpack/config/blocks/base.ts similarity index 93% rename from packages/next/src/build/webpack/config/blocks/base.ts rename to packages/next/src/webpack/build/webpack/config/blocks/base.ts index bba93853b35a..b032b67fa832 100644 --- a/packages/next/src/build/webpack/config/blocks/base.ts +++ b/packages/next/src/webpack/build/webpack/config/blocks/base.ts @@ -1,10 +1,10 @@ import curry from 'next/dist/compiled/lodash.curry' -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { COMPILER_NAMES } from '../../../../shared/lib/constants' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import { COMPILER_NAMES } from 'next/dist/shared/lib/constants' import type { ConfigurationContext } from '../utils' import DevToolsIgnorePlugin from '../../plugins/devtools-ignore-list-plugin' import EvalSourceMapDevToolPlugin from '../../plugins/eval-source-map-dev-tool-plugin' -import { getRspackCore } from '../../../../shared/lib/get-rspack' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' function shouldIgnorePath(modulePath: string): boolean { return ( diff --git a/packages/next/src/build/webpack/config/blocks/css/index.ts b/packages/next/src/webpack/build/webpack/config/blocks/css/index.ts similarity index 98% rename from packages/next/src/build/webpack/config/blocks/css/index.ts rename to packages/next/src/webpack/build/webpack/config/blocks/css/index.ts index 34f5822bdcaa..fe51952577a2 100644 --- a/packages/next/src/build/webpack/config/blocks/css/index.ts +++ b/packages/next/src/webpack/build/webpack/config/blocks/css/index.ts @@ -1,5 +1,5 @@ import curry from 'next/dist/compiled/lodash.curry' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { loader, plugin } from '../../helpers' import { pipe } from '../../utils' import type { ConfigurationContext, ConfigurationFn } from '../../utils' @@ -12,9 +12,9 @@ import { getLocalModuleImportError, } from './messages' import { getPostCssPlugins } from './plugins' -import { nonNullable } from '../../../../../lib/non-nullable' -import { WEBPACK_LAYERS } from '../../../../../lib/constants' -import { getRspackCore } from '../../../../../shared/lib/get-rspack' +import { nonNullable } from 'next/dist/lib/non-nullable' +import { WEBPACK_LAYERS } from 'next/dist/lib/constants' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' // RegExps for all Style Sheet variants export const regexLikeCss = /\.(css|scss|sass)$/ @@ -184,7 +184,7 @@ export const css: ( // To fix this, we use `resolve-url-loader` to rewrite the CSS // imports to real file paths. { - loader: require.resolve('../../../loaders/resolve-url-loader/index'), + loader: require.resolve('next/dist/build/resolve-url-loader/index'), options: { postcss: lazyPostCSSInitializer, // Source maps are not required here, but we may as well emit diff --git a/packages/next/src/build/webpack/config/blocks/css/loaders/client.ts b/packages/next/src/webpack/build/webpack/config/blocks/css/loaders/client.ts similarity index 93% rename from packages/next/src/build/webpack/config/blocks/css/loaders/client.ts rename to packages/next/src/webpack/build/webpack/config/blocks/css/loaders/client.ts index 55719d6ebd2e..35063ab3558d 100644 --- a/packages/next/src/build/webpack/config/blocks/css/loaders/client.ts +++ b/packages/next/src/webpack/build/webpack/config/blocks/css/loaders/client.ts @@ -1,5 +1,5 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { getRspackCore } from '../../../../../../shared/lib/get-rspack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' export function getClientStyleLoader({ hasAppDir, diff --git a/packages/next/src/build/webpack/config/blocks/css/loaders/file-resolve.ts b/packages/next/src/webpack/build/webpack/config/blocks/css/loaders/file-resolve.ts similarity index 100% rename from packages/next/src/build/webpack/config/blocks/css/loaders/file-resolve.ts rename to packages/next/src/webpack/build/webpack/config/blocks/css/loaders/file-resolve.ts diff --git a/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts b/packages/next/src/webpack/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts similarity index 95% rename from packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts rename to packages/next/src/webpack/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts index 2291a07484e4..939d2c9091ce 100644 --- a/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts +++ b/packages/next/src/webpack/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts @@ -1,6 +1,6 @@ import loaderUtils from 'next/dist/compiled/loader-utils3' import path from 'path' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' const regexLikeIndexModule = /(? 'export default {}' export default EmptyLoader diff --git a/packages/next/src/build/webpack/loaders/error-loader.ts b/packages/next/src/webpack/build/webpack/loaders/error-loader.ts similarity index 83% rename from packages/next/src/build/webpack/loaders/error-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/error-loader.ts index af57d692541e..8a0624fecf60 100644 --- a/packages/next/src/build/webpack/loaders/error-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/error-loader.ts @@ -1,6 +1,6 @@ -import { cyan } from '../../../lib/picocolors' +import { cyan } from 'next/dist/lib/picocolors' import path from 'path' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' const ErrorLoader: webpack.LoaderDefinitionFunction = function () { // @ts-ignore exists diff --git a/packages/next/src/build/webpack/loaders/get-module-build-info.ts b/packages/next/src/webpack/build/webpack/loaders/get-module-build-info.ts similarity index 93% rename from packages/next/src/build/webpack/loaders/get-module-build-info.ts rename to packages/next/src/webpack/build/webpack/loaders/get-module-build-info.ts index f677d988d685..4789cbea73de 100644 --- a/packages/next/src/build/webpack/loaders/get-module-build-info.ts +++ b/packages/next/src/webpack/build/webpack/loaders/get-module-build-info.ts @@ -2,8 +2,8 @@ import type { ProxyConfig, ProxyMatcher, RSCModuleType, -} from '../../analysis/get-page-static-info' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +} from 'next/dist/build/analysis/get-page-static-info' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' export type ModuleBuildInfo = { nextEdgeMiddleware?: EdgeMiddlewareMeta diff --git a/packages/next/src/build/webpack/loaders/instrumentation-client-stub.js b/packages/next/src/webpack/build/webpack/loaders/instrumentation-client-stub.js similarity index 100% rename from packages/next/src/build/webpack/loaders/instrumentation-client-stub.js rename to packages/next/src/webpack/build/webpack/loaders/instrumentation-client-stub.js diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/LICENSE b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/LICENSE similarity index 100% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/LICENSE rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/LICENSE diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/README.md b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/README.md similarity index 100% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/README.md rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/README.md diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/codegen.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/codegen.ts similarity index 98% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/codegen.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/codegen.ts index 11602c29a9d8..2ae402547aad 100644 --- a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/codegen.ts +++ b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/codegen.ts @@ -1,4 +1,4 @@ -import type { LoaderContext } from 'next/dist/compiled/webpack/webpack' +import type { LoaderContext } from 'next/dist/webpack/compiled/webpack/webpack' import camelCase from '../../css-loader/src/camelcase' import { dashesCamelCase, diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/index.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/index.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/index.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/index.ts diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/interface.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/interface.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/interface.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/interface.ts diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/loader.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/loader.ts similarity index 99% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/loader.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/loader.ts index 00f8f53e4c99..9995801c6a75 100644 --- a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/loader.ts @@ -19,8 +19,8 @@ import { } from '../../css-loader/src/utils' import { stringifyRequest } from '../../../stringify-request' import { ECacheKey } from './interface' -import { getBindingsSync } from '../../../../../build/swc' -import { installBindings } from '../../../../../build/swc/install-bindings' +import { getBindingsSync } from 'next/dist/build/swc' +import { installBindings } from 'next/dist/build/swc/install-bindings' const encoder = new TextEncoder() diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/minify.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/minify.ts similarity index 94% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/minify.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/minify.ts index 59843ba7183d..6fe7584d2175 100644 --- a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/minify.ts +++ b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/minify.ts @@ -1,13 +1,13 @@ // @ts-ignore -import { ModuleFilenameHelpers } from 'next/dist/compiled/webpack/webpack' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import { ModuleFilenameHelpers } from 'next/dist/webpack/compiled/webpack/webpack' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' // @ts-ignore import { RawSource, SourceMapSource } from 'next/dist/compiled/webpack-sources3' import { ECacheKey } from './interface' import type { Compilation, Compiler } from 'webpack' import { getTargets } from './utils' import { Buffer } from 'buffer' -import { getBindingsSync } from '../../../../../build/swc' +import { getBindingsSync } from 'next/dist/build/swc' const PLUGIN_NAME = 'lightning-css-minify' const CSS_FILE_REG = /\.css(?:\?.*)?$/i diff --git a/packages/next/src/build/webpack/loaders/lightningcss-loader/src/utils.ts b/packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/utils.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/lightningcss-loader/src/utils.ts rename to packages/next/src/webpack/build/webpack/loaders/lightningcss-loader/src/utils.ts diff --git a/packages/next/src/build/webpack/loaders/metadata/discover.ts b/packages/next/src/webpack/build/webpack/loaders/metadata/discover.ts similarity index 95% rename from packages/next/src/build/webpack/loaders/metadata/discover.ts rename to packages/next/src/webpack/build/webpack/loaders/metadata/discover.ts index 89d9f18baf00..69c4098443b1 100644 --- a/packages/next/src/build/webpack/loaders/metadata/discover.ts +++ b/packages/next/src/webpack/build/webpack/loaders/metadata/discover.ts @@ -4,10 +4,10 @@ import type { } from './types' import path from 'path' import { stringify } from 'querystring' -import { STATIC_METADATA_IMAGES } from '../../../../lib/metadata/is-metadata-route' -import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' +import { STATIC_METADATA_IMAGES } from 'next/dist/lib/metadata/is-metadata-route' +import { WEBPACK_RESOURCE_QUERIES } from 'next/dist/lib/constants' import type { MetadataResolver } from '../next-app-loader' -import type { PageExtensions } from '../../../page-extensions-type' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' const METADATA_TYPE = 'metadata' const NUMERIC_SUFFIX_ARRAY = Array(10).fill(0) diff --git a/packages/next/src/build/webpack/loaders/metadata/resolve-route-data.test.ts b/packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.test.ts similarity index 99% rename from packages/next/src/build/webpack/loaders/metadata/resolve-route-data.test.ts rename to packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.test.ts index b78d4665273b..47ecf78cf3ec 100644 --- a/packages/next/src/build/webpack/loaders/metadata/resolve-route-data.test.ts +++ b/packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.test.ts @@ -1,4 +1,4 @@ -import type { MetadataRoute } from '../../../../lib/metadata/types/metadata-interface' +import type { MetadataRoute } from 'next/dist/lib/metadata/types/metadata-interface' import { resolveRobots, resolveSitemap } from './resolve-route-data' describe('resolveRouteData', () => { diff --git a/packages/next/src/build/webpack/loaders/metadata/resolve-route-data.ts b/packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.ts similarity index 97% rename from packages/next/src/build/webpack/loaders/metadata/resolve-route-data.ts rename to packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.ts index 744d31ca8615..71d6474f4e10 100644 --- a/packages/next/src/build/webpack/loaders/metadata/resolve-route-data.ts +++ b/packages/next/src/webpack/build/webpack/loaders/metadata/resolve-route-data.ts @@ -1,5 +1,5 @@ -import type { MetadataRoute } from '../../../../lib/metadata/types/metadata-interface' -import { resolveArray } from '../../../../lib/metadata/generate/utils' +import type { MetadataRoute } from 'next/dist/lib/metadata/types/metadata-interface' +import { resolveArray } from 'next/dist/lib/metadata/generate/utils' // convert robots data to txt string export function resolveRobots(data: MetadataRoute.Robots): string { diff --git a/packages/next/src/build/webpack/loaders/metadata/types.ts b/packages/next/src/webpack/build/webpack/loaders/metadata/types.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/metadata/types.ts rename to packages/next/src/webpack/build/webpack/loaders/metadata/types.ts diff --git a/packages/next/src/build/webpack/loaders/modularize-import-loader.ts b/packages/next/src/webpack/build/webpack/loaders/modularize-import-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/modularize-import-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/modularize-import-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-app-loader/create-app-route-code.ts b/packages/next/src/webpack/build/webpack/loaders/next-app-loader/create-app-route-code.ts similarity index 81% rename from packages/next/src/build/webpack/loaders/next-app-loader/create-app-route-code.ts rename to packages/next/src/webpack/build/webpack/loaders/next-app-loader/create-app-route-code.ts index 4062d2a9b344..757d17800641 100644 --- a/packages/next/src/build/webpack/loaders/next-app-loader/create-app-route-code.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-app-loader/create-app-route-code.ts @@ -1,15 +1,15 @@ import path from 'path' import { stringify } from 'querystring' -import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' +import { WEBPACK_RESOURCE_QUERIES } from 'next/dist/lib/constants' import { DEFAULT_METADATA_ROUTE_EXTENSIONS, isMetadataRouteFile, -} from '../../../../lib/metadata/is-metadata-route' -import type { NextConfig } from '../../../../server/config-shared' -import { AppBundlePathNormalizer } from '../../../../server/normalizers/built/app/app-bundle-path-normalizer' -import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer' -import { loadEntrypoint } from '../../../load-entrypoint' -import type { PageExtensions } from '../../../page-extensions-type' +} from 'next/dist/lib/metadata/is-metadata-route' +import type { NextConfig } from 'next/dist/server/config-shared' +import { AppBundlePathNormalizer } from 'next/dist/server/normalizers/built/app/app-bundle-path-normalizer' +import { AppPathnameNormalizer } from 'next/dist/server/normalizers/built/app/app-pathname-normalizer' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' import { getFilenameAndExtension } from '../next-metadata-route-loader' export async function createAppRouteCode({ diff --git a/packages/next/src/build/webpack/loaders/next-app-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-app-loader/index.ts similarity index 96% rename from packages/next/src/build/webpack/loaders/next-app-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-app-loader/index.ts index 082468894f24..00f8c24fc357 100644 --- a/packages/next/src/build/webpack/loaders/next-app-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-app-loader/index.ts @@ -1,49 +1,49 @@ -import type webpack from 'next/dist/compiled/webpack/webpack' +import type webpack from 'next/dist/webpack/compiled/webpack/webpack' import { UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE, type ValueOf, -} from '../../../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' import { UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, -} from '../../../../shared/lib/entry-constants' +} from 'next/dist/shared/lib/entry-constants' import type { ModuleTuple, CollectedMetadata } from '../metadata/types' import path from 'path' -import { bold } from '../../../../lib/picocolors' +import { bold } from 'next/dist/lib/picocolors' import { getModuleBuildInfo } from '../get-module-build-info' -import { verifyRootLayout } from '../../../../lib/verify-root-layout' -import * as Log from '../../../output/log' -import { APP_DIR_ALIAS } from '../../../../lib/constants' +import { verifyRootLayout } from 'next/dist/lib/verify-root-layout' +import * as Log from 'next/dist/build/output/log' +import { APP_DIR_ALIAS } from 'next/dist/lib/constants' import { createMetadataExportsCode, createStaticMetadataFromRoute, } from '../metadata/discover' import { promises as fs } from 'fs' -import { isAppRouteRoute } from '../../../../lib/is-app-route-route' -import type { NextConfig } from '../../../../server/config-shared' -import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer' -import type { ProxyConfig } from '../../../analysis/get-page-static-info' -import { isAppBuiltinPage } from '../../../utils' -import { loadEntrypoint } from '../../../load-entrypoint' +import { isAppRouteRoute } from 'next/dist/lib/is-app-route-route' +import type { NextConfig } from 'next/dist/server/config-shared' +import { AppPathnameNormalizer } from 'next/dist/server/normalizers/built/app/app-pathname-normalizer' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' +import { isAppBuiltinPage } from 'next/dist/build/utils' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' import { isGroupSegment, DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY, -} from '../../../../shared/lib/segment' -import { getFilesInDir } from '../../../../lib/get-files-in-dir' -import type { PageExtensions } from '../../../page-extensions-type' -import { PARALLEL_ROUTE_DEFAULT_PATH } from '../../../../client/components/builtin/default' -import { PARALLEL_ROUTE_DEFAULT_NULL_PATH } from '../../../../client/components/builtin/default-null' +} from 'next/dist/shared/lib/segment' +import { getFilesInDir } from 'next/dist/lib/get-files-in-dir' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' +import { PARALLEL_ROUTE_DEFAULT_PATH } from 'next/dist/client/components/builtin/default' +import { PARALLEL_ROUTE_DEFAULT_NULL_PATH } from 'next/dist/client/components/builtin/default-null' import type { Compilation } from 'webpack' import { createAppRouteCode } from './create-app-route-code' -import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error' -import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes' -import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths' +import { MissingDefaultParallelRouteError } from 'next/dist/shared/lib/errors/missing-default-parallel-route-error' +import { isInterceptionRouteAppPath } from 'next/dist/shared/lib/router/utils/interception-routes' +import { normalizeAppPath } from 'next/dist/shared/lib/router/utils/app-paths' -import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep' -import { installBindings } from '../../../swc/install-bindings' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' +import { installBindings } from 'next/dist/build/swc/install-bindings' export type AppLoaderOptions = { name: string diff --git a/packages/next/src/build/webpack/loaders/next-barrel-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-barrel-loader.ts similarity index 98% rename from packages/next/src/build/webpack/loaders/next-barrel-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-barrel-loader.ts index a41db2082837..f226a1a06f2d 100644 --- a/packages/next/src/build/webpack/loaders/next-barrel-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-barrel-loader.ts @@ -87,8 +87,8 @@ import type webpack from 'webpack' import path from 'path' -import { transform } from '../../swc' -import { installBindings } from '../../swc/install-bindings' +import { transform } from 'next/dist/build/swc' +import { installBindings } from 'next/dist/build/swc/install-bindings' // This is a in-memory cache for the mapping of barrel exports. This only applies // to the packages that we optimize. It will never change (e.g. upgrading packages) diff --git a/packages/next/src/build/webpack/loaders/next-client-pages-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-client-pages-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-client-pages-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-client-pages-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-edge-app-route-loader/index.ts similarity index 90% rename from packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-edge-app-route-loader/index.ts index 1303263f2344..333deb8019f4 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-edge-app-route-loader/index.ts @@ -1,10 +1,10 @@ import { getModuleBuildInfo } from '../get-module-build-info' import { stringifyRequest } from '../../stringify-request' -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' -import type { ProxyConfig } from '../../../analysis/get-page-static-info' -import { loadEntrypoint } from '../../../load-entrypoint' -import { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import { WEBPACK_RESOURCE_QUERIES } from 'next/dist/lib/constants' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' +import { isMetadataRoute } from 'next/dist/lib/metadata/is-metadata-route' export type EdgeAppRouteLoaderQuery = { absolutePagePath: string diff --git a/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-edge-function-loader.ts similarity index 96% rename from packages/next/src/build/webpack/loaders/next-edge-function-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-edge-function-loader.ts index 6c30a4a97a25..e795e39421ce 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-edge-function-loader.ts @@ -1,7 +1,7 @@ import type webpack from 'webpack' import { getModuleBuildInfo } from './get-module-build-info' import { stringifyRequest } from '../stringify-request' -import type { ProxyConfig } from '../../analysis/get-page-static-info' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' export type EdgeFunctionLoaderOptions = { absolutePagePath: string diff --git a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-edge-ssr-loader/index.ts similarity index 92% rename from packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-edge-ssr-loader/index.ts index 44d44f2ab8b7..0a7e590de6f2 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-edge-ssr-loader/index.ts @@ -1,14 +1,14 @@ import type webpack from 'webpack' -import type { SizeLimit } from '../../../../types' -import type { PagesRouteModuleOptions } from '../../../../server/route-modules/pages/module' -import type { ProxyConfig } from '../../../analysis/get-page-static-info' +import type { SizeLimit } from 'next/dist/types' +import type { PagesRouteModuleOptions } from 'next/dist/server/route-modules/pages/module' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' import { getModuleBuildInfo } from '../get-module-build-info' -import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' -import { RouteKind } from '../../../../server/route-kind' -import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' -import { loadEntrypoint } from '../../../load-entrypoint' -import type { PAGE_TYPES } from '../../../../lib/page-types' +import { WEBPACK_RESOURCE_QUERIES } from 'next/dist/lib/constants' +import { RouteKind } from 'next/dist/server/route-kind' +import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' +import type { PAGE_TYPES } from 'next/dist/lib/page-types' export type EdgeSSRLoaderQuery = { absolute500Path: string diff --git a/packages/next/src/build/webpack/loaders/next-error-browser-binary-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-error-browser-binary-loader.ts similarity index 82% rename from packages/next/src/build/webpack/loaders/next-error-browser-binary-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-error-browser-binary-loader.ts index 36958fa050fa..b4a87f73a279 100644 --- a/packages/next/src/build/webpack/loaders/next-error-browser-binary-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-error-browser-binary-loader.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' export default function nextErrorBrowserBinaryLoader( this: webpack.LoaderContext diff --git a/packages/next/src/build/webpack/loaders/next-flight-action-entry-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-action-entry-loader.ts similarity index 93% rename from packages/next/src/build/webpack/loaders/next-flight-action-entry-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-action-entry-loader.ts index 6fa4898fdd27..0a4d51fb3e31 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-action-entry-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-action-entry-loader.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' export type NextFlightActionEntryLoaderOptions = { actions: string diff --git a/packages/next/src/build/webpack/loaders/next-flight-client-entry-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-client-entry-loader.ts similarity index 95% rename from packages/next/src/build/webpack/loaders/next-flight-client-entry-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-client-entry-loader.ts index 2346e14593d0..aa4a352f86a0 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-client-entry-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-client-entry-loader.ts @@ -1,8 +1,8 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { BARREL_OPTIMIZATION_PREFIX, RSC_MODULE_TYPES, -} from '../../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' import { getModuleBuildInfo } from './get-module-build-info' import { regexCSS } from './utils' diff --git a/packages/next/src/build/webpack/loaders/next-flight-client-module-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-client-module-loader.ts similarity index 92% rename from packages/next/src/build/webpack/loaders/next-flight-client-module-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-client-module-loader.ts index 9f4c9f82f59a..00549aaf1a15 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-client-module-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-client-module-loader.ts @@ -1,5 +1,5 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { getRSCModuleInformation } from '../../analysis/get-page-static-info' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import { getRSCModuleInformation } from 'next/dist/build/analysis/get-page-static-info' import { getModuleBuildInfo } from './get-module-build-info' const flightClientModuleLoader: webpack.LoaderDefinitionFunction = diff --git a/packages/next/src/build/webpack/loaders/next-flight-css-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-css-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-flight-css-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-css-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/action-validate.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/action-validate.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-flight-loader/action-validate.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-loader/action-validate.ts diff --git a/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/cache-wrapper.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/cache-wrapper.ts new file mode 100644 index 000000000000..c11e11664098 --- /dev/null +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/cache-wrapper.ts @@ -0,0 +1 @@ +export { cache } from 'next/dist/server/use-cache/use-cache-wrapper' diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/index.ts similarity index 95% rename from packages/next/src/build/webpack/loaders/next-flight-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-loader/index.ts index 0cf1ac6d525b..42295c5e7848 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/index.ts @@ -4,14 +4,14 @@ import { type LoaderContext, type NormalModule, type webpack, -} from 'next/dist/compiled/webpack/webpack' -import { RSC_MOD_REF_PROXY_ALIAS } from '../../../../lib/constants' +} from 'next/dist/webpack/compiled/webpack/webpack' +import { RSC_MOD_REF_PROXY_ALIAS } from 'next/dist/lib/constants' import { BARREL_OPTIMIZATION_PREFIX, RSC_MODULE_TYPES, -} from '../../../../shared/lib/constants' -import { warnOnce } from '../../../../shared/lib/utils/warn-once' -import { getRSCModuleInformation } from '../../../analysis/get-page-static-info' +} from 'next/dist/shared/lib/constants' +import { warnOnce } from 'next/dist/shared/lib/utils/warn-once' +import { getRSCModuleInformation } from 'next/dist/build/analysis/get-page-static-info' import { formatBarrelOptimizedResource } from '../../utils' import { getModuleBuildInfo } from '../get-module-build-info' @@ -20,7 +20,7 @@ type SourceType = javascript.JavascriptParser['sourceType'] | 'commonjs' const noopHeadPath = require.resolve('next/dist/client/components/noop-head') // For edge runtime it will be aliased to esm version by webpack const MODULE_PROXY_PATH = - 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy' + 'next/dist/webpack/build/webpack/loaders/next-flight-loader/module-proxy' export function getAssumedSourceType( mod: webpack.Module, diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/module-proxy.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/module-proxy.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-flight-loader/module-proxy.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-loader/module-proxy.ts diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/server-reference.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/server-reference.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-flight-loader/server-reference.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-loader/server-reference.ts diff --git a/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts new file mode 100644 index 000000000000..ec695f72af11 --- /dev/null +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts @@ -0,0 +1 @@ +export { trackDynamicImport } from 'next/dist/server/app-render/module-loading/track-dynamic-import' diff --git a/packages/next/src/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts similarity index 93% rename from packages/next/src/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts index 07ade3302b83..cf57acb8a567 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' // This is a virtual proxy loader that takes a Server Reference ID and a name, // creates a module that just re-exports the reference as that name. diff --git a/packages/next/src/build/webpack/loaders/next-font-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-font-loader/index.ts similarity index 98% rename from packages/next/src/build/webpack/loaders/next-font-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-font-loader/index.ts index aba3adc52a69..f488905e807c 100644 --- a/packages/next/src/build/webpack/loaders/next-font-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-font-loader/index.ts @@ -1,7 +1,7 @@ -import type { FontLoader } from '../../../../../font' +import type { FontLoader } from 'next/font' import path from 'path' -import { bold, cyan } from '../../../../lib/picocolors' +import { bold, cyan } from 'next/dist/lib/picocolors' import loaderUtils from 'next/dist/compiled/loader-utils3' import postcssNextFontPlugin from './postcss-next-font' import { promisify } from 'util' diff --git a/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts b/packages/next/src/webpack/build/webpack/loaders/next-font-loader/postcss-next-font.ts similarity index 98% rename from packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts rename to packages/next/src/webpack/build/webpack/loaders/next-font-loader/postcss-next-font.ts index 11b083a6433c..254906cb0473 100644 --- a/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-font-loader/postcss-next-font.ts @@ -1,4 +1,4 @@ -import type { AdjustFontFallback } from '../../../../../font' +import type { AdjustFontFallback } from 'next/font' import type { Declaration } from 'postcss' import postcss from 'postcss' diff --git a/packages/next/src/build/webpack/loaders/next-image-loader/blur.ts b/packages/next/src/webpack/build/webpack/loaders/next-image-loader/blur.ts similarity index 97% rename from packages/next/src/build/webpack/loaders/next-image-loader/blur.ts rename to packages/next/src/webpack/build/webpack/loaders/next-image-loader/blur.ts index b7dbb2508625..f3db2915354a 100644 --- a/packages/next/src/build/webpack/loaders/next-image-loader/blur.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-image-loader/blur.ts @@ -1,5 +1,5 @@ import isAnimated from 'next/dist/compiled/is-animated' -import { optimizeImage } from '../../../../server/image-optimizer' +import { optimizeImage } from 'next/dist/server/image-optimizer' const BLUR_IMG_SIZE = 8 const BLUR_QUALITY = 70 diff --git a/packages/next/src/build/webpack/loaders/next-image-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-image-loader/index.ts similarity index 94% rename from packages/next/src/build/webpack/loaders/next-image-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-image-loader/index.ts index 7590ea3e7671..6b922d71d9b4 100644 --- a/packages/next/src/build/webpack/loaders/next-image-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-image-loader/index.ts @@ -1,8 +1,8 @@ -import type { CompilerNameValues } from '../../../../shared/lib/constants' +import type { CompilerNameValues } from 'next/dist/shared/lib/constants' import path from 'path' import loaderUtils from 'next/dist/compiled/loader-utils3' -import { getImageSize } from '../../../../server/image-optimizer' +import { getImageSize } from 'next/dist/server/image-optimizer' import { getBlurImage } from './blur' interface Options { diff --git a/packages/next/src/build/webpack/loaders/next-instrumentation-client-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-instrumentation-client-loader.ts similarity index 97% rename from packages/next/src/build/webpack/loaders/next-instrumentation-client-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-instrumentation-client-loader.ts index 2c9efe1ab16d..f8b14abedc36 100644 --- a/packages/next/src/build/webpack/loaders/next-instrumentation-client-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-instrumentation-client-loader.ts @@ -1,5 +1,5 @@ import { promisify } from 'util' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' /** * Loader options for `next-instrumentation-client-loader`. The list of inject diff --git a/packages/next/src/build/webpack/loaders/next-invalid-import-error-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-invalid-import-error-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-invalid-import-error-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-invalid-import-error-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-metadata-image-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-metadata-image-loader.ts similarity index 92% rename from packages/next/src/build/webpack/loaders/next-metadata-image-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-metadata-image-loader.ts index 43433fe96237..c064c28698d4 100644 --- a/packages/next/src/build/webpack/loaders/next-metadata-image-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-metadata-image-loader.ts @@ -10,14 +10,14 @@ import type { import { existsSync, promises as fs } from 'fs' import path from 'path' import loaderUtils from 'next/dist/compiled/loader-utils3' -import { getImageSize } from '../../../server/image-optimizer' -import { imageExtMimeTypeMap } from '../../../lib/mime-type' -import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants' -import { fillStaticMetadataSegment } from '../../../lib/metadata/get-metadata-route' -import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' -import type { PageExtensions } from '../../page-extensions-type' +import { getImageSize } from 'next/dist/server/image-optimizer' +import { imageExtMimeTypeMap } from 'next/dist/lib/mime-type' +import { WEBPACK_RESOURCE_QUERIES } from 'next/dist/lib/constants' +import { fillStaticMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' import { getLoaderModuleNamedExports } from './utils' -import { installBindings } from '../../swc/install-bindings' +import { installBindings } from 'next/dist/build/swc/install-bindings' interface Options { segment: string diff --git a/packages/next/src/build/webpack/loaders/next-metadata-route-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-metadata-route-loader.ts similarity index 96% rename from packages/next/src/build/webpack/loaders/next-metadata-route-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-metadata-route-loader.ts index 0266d5e6138f..745828fafa81 100644 --- a/packages/next/src/build/webpack/loaders/next-metadata-route-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-metadata-route-loader.ts @@ -1,9 +1,9 @@ import type webpack from 'webpack' import fs from 'fs' import path from 'path' -import { imageExtMimeTypeMap } from '../../../lib/mime-type' +import { imageExtMimeTypeMap } from 'next/dist/lib/mime-type' import { getLoaderModuleNamedExports } from './utils' -import { installBindings } from '../../swc/install-bindings' +import { installBindings } from 'next/dist/build/swc/install-bindings' function errorOnBadHandler(resourcePath: string) { return ` @@ -135,7 +135,7 @@ async function getDynamicTextRouteCode( /* dynamic asset route */ import { NextResponse } from 'next/server' import handler from ${JSON.stringify(resourcePath)} -import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data' +import { resolveRouteData } from 'next/dist/webpack/build/webpack/loaders/metadata/resolve-route-data' const contentType = ${JSON.stringify(getContentType(resourcePath))} const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)} @@ -258,7 +258,7 @@ async function getSingleSitemapRouteCode( /* single sitemap route */ import { NextResponse } from 'next/server' import { default as handler } from ${JSON.stringify(resourcePath)} -import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data' +import { resolveRouteData } from 'next/dist/webpack/build/webpack/loaders/metadata/resolve-route-data' const contentType = ${JSON.stringify(getContentType(resourcePath))} const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)} @@ -288,7 +288,7 @@ async function getDynamicSitemapRouteCode( /* dynamic sitemap route with generateSitemaps */ import { NextResponse } from 'next/server' import { default as handler, generateSitemaps } from ${JSON.stringify(resourcePath)} -import { resolveRouteData } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data' +import { resolveRouteData } from 'next/dist/webpack/build/webpack/loaders/metadata/resolve-route-data' const contentType = ${JSON.stringify(getContentType(resourcePath))} const fileType = ${JSON.stringify(getFilenameAndExtension(resourcePath).name)} diff --git a/packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-middleware-asset-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-middleware-asset-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-middleware-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-middleware-loader.ts similarity index 93% rename from packages/next/src/build/webpack/loaders/next-middleware-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-middleware-loader.ts index e7bbfe7dcddd..b57134bc89f8 100644 --- a/packages/next/src/build/webpack/loaders/next-middleware-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-middleware-loader.ts @@ -1,13 +1,13 @@ import type { ProxyConfig, ProxyMatcher, -} from '../../analysis/get-page-static-info' +} from 'next/dist/build/analysis/get-page-static-info' import { getModuleBuildInfo } from './get-module-build-info' import { MIDDLEWARE_LOCATION_REGEXP, PROXY_LOCATION_REGEXP, -} from '../../../lib/constants' -import { loadEntrypoint } from '../../load-entrypoint' +} from 'next/dist/lib/constants' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' export type MiddlewareLoaderOptions = { absolutePagePath: string diff --git a/packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-middleware-wasm-loader.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-middleware-wasm-loader.ts diff --git a/packages/next/src/build/webpack/loaders/next-root-params-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-root-params-loader.ts similarity index 93% rename from packages/next/src/build/webpack/loaders/next-root-params-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-root-params-loader.ts index cf89abe1077d..1ffbde173e4a 100644 --- a/packages/next/src/build/webpack/loaders/next-root-params-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-root-params-loader.ts @@ -1,9 +1,9 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import * as path from 'node:path' import * as fs from 'node:fs/promises' -import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' -import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash' -import { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param' +import { normalizeAppPath } from 'next/dist/shared/lib/router/utils/app-paths' +import { ensureLeadingSlash } from 'next/dist/shared/lib/page-path/ensure-leading-slash' +import { getSegmentParam } from 'next/dist/shared/lib/router/utils/get-segment-param' export type RootParamsLoaderOpts = { appDir: string diff --git a/packages/next/src/build/webpack/loaders/next-route-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-route-loader/index.ts similarity index 91% rename from packages/next/src/build/webpack/loaders/next-route-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-route-loader/index.ts index d3bc1f95248f..e83f343d1e67 100644 --- a/packages/next/src/build/webpack/loaders/next-route-loader/index.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-route-loader/index.ts @@ -1,17 +1,17 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type { ProxyConfig } from '../../../analysis/get-page-static-info' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' import { stringify } from 'querystring' import { type ModuleBuildInfo, getModuleBuildInfo, } from '../get-module-build-info' -import { RouteKind } from '../../../../server/route-kind' -import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' +import { RouteKind } from 'next/dist/server/route-kind' +import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' import { decodeFromBase64, encodeToBase64 } from '../utils' -import { isInstrumentationHookFile } from '../../../utils' -import { loadEntrypoint } from '../../../load-entrypoint' -import type { MappedPages } from '../../../build-context' +import { isInstrumentationHookFile } from 'next/dist/build/utils' +import { loadEntrypoint } from 'next/dist/build/load-entrypoint' +import type { MappedPages } from 'next/dist/build/build-context' type RouteLoaderOptionsPagesAPIInput = { kind: RouteKind.PAGES_API diff --git a/packages/next/src/build/webpack/loaders/next-style-loader/LICENSE b/packages/next/src/webpack/build/webpack/loaders/next-style-loader/LICENSE similarity index 100% rename from packages/next/src/build/webpack/loaders/next-style-loader/LICENSE rename to packages/next/src/webpack/build/webpack/loaders/next-style-loader/LICENSE diff --git a/packages/next/src/build/webpack/loaders/next-style-loader/index.ts b/packages/next/src/webpack/build/webpack/loaders/next-style-loader/index.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-style-loader/index.ts rename to packages/next/src/webpack/build/webpack/loaders/next-style-loader/index.ts diff --git a/packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts b/packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts rename to packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts diff --git a/packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts b/packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts rename to packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts diff --git a/packages/next/src/build/webpack/loaders/next-style-loader/runtime/isEqualLocals.ts b/packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/isEqualLocals.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/next-style-loader/runtime/isEqualLocals.ts rename to packages/next/src/webpack/build/webpack/loaders/next-style-loader/runtime/isEqualLocals.ts diff --git a/packages/next/src/build/webpack/loaders/next-swc-loader.ts b/packages/next/src/webpack/build/webpack/loaders/next-swc-loader.ts similarity index 96% rename from packages/next/src/build/webpack/loaders/next-swc-loader.ts rename to packages/next/src/webpack/build/webpack/loaders/next-swc-loader.ts index ea696e4886b1..bf17a540f2a4 100644 --- a/packages/next/src/build/webpack/loaders/next-swc-loader.ts +++ b/packages/next/src/webpack/build/webpack/loaders/next-swc-loader.ts @@ -26,11 +26,11 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import type { NextConfig } from '../../../types' -import { type WebpackLayerName, WEBPACK_LAYERS } from '../../../lib/constants' -import { getBindingsSync, transform } from '../../swc' -import { installBindings } from '../../swc/install-bindings' -import { getLoaderSWCOptions } from '../../swc/options' +import type { NextConfig } from 'next/dist/types' +import { type WebpackLayerName, WEBPACK_LAYERS } from 'next/dist/lib/constants' +import { getBindingsSync, transform } from 'next/dist/build/swc' +import { installBindings } from 'next/dist/build/swc/install-bindings' +import { getLoaderSWCOptions } from 'next/dist/build/swc/options' import path, { isAbsolute } from 'path' import { babelIncludeRegexes } from '../../webpack-config' import { isResourceInPackages } from '../../handle-externals' @@ -43,7 +43,7 @@ import type { LoaderContext } from 'webpack' import { COMPILER_NAMES, type CompilerNameValues, -} from '../../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' const maybeExclude = ( excludePath: string, diff --git a/packages/next/src/build/webpack/loaders/postcss-loader/LICENSE b/packages/next/src/webpack/build/webpack/loaders/postcss-loader/LICENSE similarity index 100% rename from packages/next/src/build/webpack/loaders/postcss-loader/LICENSE rename to packages/next/src/webpack/build/webpack/loaders/postcss-loader/LICENSE diff --git a/packages/next/src/build/webpack/loaders/postcss-loader/src/Error.ts b/packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/Error.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/postcss-loader/src/Error.ts rename to packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/Error.ts diff --git a/packages/next/src/build/webpack/loaders/postcss-loader/src/Warning.ts b/packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/Warning.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/postcss-loader/src/Warning.ts rename to packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/Warning.ts diff --git a/packages/next/src/build/webpack/loaders/postcss-loader/src/index.ts b/packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/index.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/postcss-loader/src/index.ts rename to packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/index.ts diff --git a/packages/next/src/build/webpack/loaders/postcss-loader/src/utils.ts b/packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/utils.ts similarity index 100% rename from packages/next/src/build/webpack/loaders/postcss-loader/src/utils.ts rename to packages/next/src/webpack/build/webpack/loaders/postcss-loader/src/utils.ts diff --git a/packages/next/src/build/webpack/loaders/utils.ts b/packages/next/src/webpack/build/webpack/loaders/utils.ts similarity index 94% rename from packages/next/src/build/webpack/loaders/utils.ts rename to packages/next/src/webpack/build/webpack/loaders/utils.ts index df5d865c7a32..4acb9bc340b9 100644 --- a/packages/next/src/build/webpack/loaders/utils.ts +++ b/packages/next/src/webpack/build/webpack/loaders/utils.ts @@ -1,5 +1,5 @@ import type webpack from 'webpack' -import { RSC_MODULE_TYPES } from '../../../shared/lib/constants' +import { RSC_MODULE_TYPES } from 'next/dist/shared/lib/constants' import { getModuleBuildInfo } from './get-module-build-info' const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'ico', 'svg'] @@ -58,7 +58,8 @@ export async function getLoaderModuleNamedExports( if (process.env.NEXT_RSPACK) { // Currently, the loadModule method is not supported in Rspack. // Use getModuleNamedExports (implemented by us using SWC) to extract named exports from the module. - const binding = require('../../swc') as typeof import('../../swc') + const binding = + require('next/dist/build/swc') as typeof import('next/dist/build/swc') return binding.getModuleNamedExports(resourcePath) } diff --git a/packages/next/src/build/webpack/plugins/build-manifest-plugin-utils.ts b/packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin-utils.ts similarity index 91% rename from packages/next/src/build/webpack/plugins/build-manifest-plugin-utils.ts rename to packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin-utils.ts index 53c0f45db859..c27a6aedcdd3 100644 --- a/packages/next/src/build/webpack/plugins/build-manifest-plugin-utils.ts +++ b/packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin-utils.ts @@ -1,5 +1,5 @@ -import type { CustomRoutes, Rewrite } from '../../../lib/load-custom-routes' -import type { BuildManifest } from '../../../server/get-page-files' +import type { CustomRoutes, Rewrite } from 'next/dist/lib/load-custom-routes' +import type { BuildManifest } from 'next/dist/server/get-page-files' export type ClientBuildManifest = { [key: string]: string[] diff --git a/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin.ts similarity index 94% rename from packages/next/src/build/webpack/plugins/build-manifest-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin.ts index f0546967d722..2c6345ba8ea3 100644 --- a/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/build-manifest-plugin.ts @@ -1,7 +1,7 @@ -import type { BloomFilter } from '../../../shared/lib/bloom-filter' -import type { CustomRoutes } from '../../../lib/load-custom-routes' +import type { BloomFilter } from 'next/dist/shared/lib/bloom-filter' +import type { CustomRoutes } from 'next/dist/lib/load-custom-routes' import devalue from 'next/dist/compiled/devalue' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import { BUILD_MANIFEST, MIDDLEWARE_BUILD_MANIFEST, @@ -11,11 +11,11 @@ import { CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, SYSTEM_ENTRYPOINTS, -} from '../../../shared/lib/constants' -import type { BuildManifest } from '../../../server/get-page-files' -import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' -import { getSortedRoutes } from '../../../shared/lib/router/utils' -import { Span } from '../../../trace' +} from 'next/dist/shared/lib/constants' +import type { BuildManifest } from 'next/dist/server/get-page-files' +import getRouteFromEntrypoint from 'next/dist/server/get-route-from-entrypoint' +import { getSortedRoutes } from 'next/dist/shared/lib/router/utils' +import { Span } from 'next/dist/trace' import { getCompilationSpan } from '../utils' import { createEdgeRuntimeManifest, diff --git a/packages/next/src/build/webpack/plugins/copy-file-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/copy-file-plugin.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/copy-file-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/copy-file-plugin.ts index 91bf58c59ab7..63d0016e2817 100644 --- a/packages/next/src/build/webpack/plugins/copy-file-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/copy-file-plugin.ts @@ -1,6 +1,6 @@ import { promises as fs } from 'fs' import loaderUtils from 'next/dist/compiled/loader-utils3' -import { sources, webpack } from 'next/dist/compiled/webpack/webpack' +import { sources, webpack } from 'next/dist/webpack/compiled/webpack/webpack' const PLUGIN_NAME = 'CopyFilePlugin' diff --git a/packages/next/src/build/webpack/plugins/css-chunking-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/css-chunking-plugin.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/css-chunking-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/css-chunking-plugin.ts diff --git a/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/css-minimizer-plugin.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/css-minimizer-plugin.ts index 5f73cecca065..ab27298ea2f5 100644 --- a/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/css-minimizer-plugin.ts @@ -2,7 +2,7 @@ import cssnanoSimple from 'next/dist/compiled/cssnano-simple' import postcssScss from 'next/dist/compiled/postcss-scss' import postcss from 'postcss' import type { Parser } from 'postcss' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import { getCompilationSpan } from '../utils' // https://github.com/NMFR/optimize-css-assets-webpack-plugin/blob/0a410a9bf28c7b0e81a3470a13748e68ca2f50aa/src/index.js#L20 diff --git a/packages/next/src/build/webpack/plugins/deferred-entries-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/deferred-entries-plugin.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/deferred-entries-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/deferred-entries-plugin.ts index 285e5c0c1396..077ef75494cc 100644 --- a/packages/next/src/build/webpack/plugins/deferred-entries-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/deferred-entries-plugin.ts @@ -1,5 +1,5 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' -import type { NextConfigComplete } from '../../../server/config-shared' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { NextConfigComplete } from 'next/dist/server/config-shared' import createDebug from 'next/dist/compiled/debug' const debug = createDebug('next:deferred-entries-plugin') diff --git a/packages/next/src/build/webpack/plugins/devtools-ignore-list-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/devtools-ignore-list-plugin.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/devtools-ignore-list-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/devtools-ignore-list-plugin.ts index c335c07bb802..48585c52db8a 100644 --- a/packages/next/src/build/webpack/plugins/devtools-ignore-list-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/devtools-ignore-list-plugin.ts @@ -1,6 +1,6 @@ // Source: https://github.com/mondaychen/devtools-ignore-webpack-plugin/blob/e35ce41d9606a92a455ef247f509a1c2ccab5778/src/index.ts -import { webpack } from 'next/dist/compiled/webpack/webpack' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' // Following the naming conventions from // https://tc39.es/source-map/#source-map-format diff --git a/packages/next/src/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts similarity index 99% rename from packages/next/src/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts index df66ef9c91a9..3d2915485955 100644 --- a/packages/next/src/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/eval-source-map-dev-tool-plugin.ts @@ -13,7 +13,7 @@ import { NormalModule, RuntimeGlobals, SourceMapDevToolModuleOptionsPlugin, -} from 'next/dist/compiled/webpack/webpack' +} from 'next/dist/webpack/compiled/webpack/webpack' import type { RawSourceMap } from 'next/dist/compiled/source-map' const cache = new WeakMap() diff --git a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/flight-client-entry-plugin.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/flight-client-entry-plugin.ts index 508d1b5a735a..1464017bd2b9 100644 --- a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/flight-client-entry-plugin.ts @@ -3,20 +3,20 @@ import type { ClientComponentImports, } from '../loaders/next-flight-client-entry-loader' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { parse, stringify } from 'querystring' import path from 'path' -import { sources } from 'next/dist/compiled/webpack/webpack' +import { sources } from 'next/dist/webpack/compiled/webpack/webpack' import { getInvalidator, getEntries, EntryTypes, getEntryKey, -} from '../../../server/dev/on-demand-entry-handler' +} from 'next/dist/server/dev/on-demand-entry-handler' import { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES, -} from '../../../lib/constants' +} from 'next/dist/lib/constants' import { APP_CLIENT_INTERNALS, BARREL_OPTIMIZATION_PREFIX, @@ -24,11 +24,11 @@ import { DEFAULT_RUNTIME_WEBPACK, EDGE_RUNTIME_WEBPACK, SERVER_REFERENCE_MANIFEST, -} from '../../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' import { UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, -} from '../../../shared/lib/entry-constants' +} from 'next/dist/shared/lib/entry-constants' import { isClientComponentEntryModule, isCSSMod, @@ -40,20 +40,20 @@ import { formatBarrelOptimizedResource, getModuleReferencesInOrder, } from '../utils' -import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' -import { getProxiedPluginState } from '../../build-context' -import { PAGE_TYPES } from '../../../lib/page-types' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' +import { getProxiedPluginState } from 'next/dist/build/build-context' +import { PAGE_TYPES } from 'next/dist/lib/page-types' import { getModuleBuildInfo } from '../loaders/get-module-build-info' import { getAssumedSourceType } from '../loaders/next-flight-loader' -import { isAppRouteRoute } from '../../../lib/is-app-route-route' +import { isAppRouteRoute } from 'next/dist/lib/is-app-route-route' import { DEFAULT_METADATA_ROUTE_EXTENSIONS, isMetadataRouteFile, -} from '../../../lib/metadata/is-metadata-route' +} from 'next/dist/lib/metadata/is-metadata-route' import type { MetadataRouteLoaderOptions } from '../loaders/next-metadata-route-loader' import type { FlightActionEntryLoaderActions } from '../loaders/next-flight-action-entry-loader' import getWebpackBundler from '../../../shared/lib/get-webpack-bundler' -import { isAppBuiltinPage } from '../../utils' +import { isAppBuiltinPage } from 'next/dist/build/utils' interface Options { dev: boolean diff --git a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/flight-manifest-plugin.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/flight-manifest-plugin.ts index 43f2ee279121..c743e87f1dcb 100644 --- a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/flight-manifest-plugin.ts @@ -6,26 +6,26 @@ */ import path from 'path' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import { APP_CLIENT_INTERNALS, BARREL_OPTIMIZATION_PREFIX, CLIENT_REFERENCE_MANIFEST, SYSTEM_ENTRYPOINTS, -} from '../../../shared/lib/constants' +} from 'next/dist/shared/lib/constants' import { relative } from 'path' -import { getProxiedPluginState } from '../../build-context' +import { getProxiedPluginState } from 'next/dist/build/build-context' -import { WEBPACK_LAYERS } from '../../../lib/constants' -import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path' -import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP } from '../../../shared/lib/constants' -import { getAssetTokenQuery } from '../../../shared/lib/deployment-id' +import { WEBPACK_LAYERS } from 'next/dist/lib/constants' +import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' +import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP } from 'next/dist/shared/lib/constants' +import { getAssetTokenQuery } from 'next/dist/shared/lib/deployment-id' import { formatBarrelOptimizedResource, getModuleReferencesInOrder, } from '../utils' import type { ChunkGroup } from 'webpack' -import { encodeURIPath } from '../../../shared/lib/encode-uri-path' +import { encodeURIPath } from 'next/dist/shared/lib/encode-uri-path' import type { ModuleInfo } from './flight-client-entry-plugin' interface Options { diff --git a/packages/next/src/build/webpack/plugins/force-complete-runtime.ts b/packages/next/src/webpack/build/webpack/plugins/force-complete-runtime.ts similarity index 95% rename from packages/next/src/build/webpack/plugins/force-complete-runtime.ts rename to packages/next/src/webpack/build/webpack/plugins/force-complete-runtime.ts index ca6918ecdd59..eebdd3a380ba 100644 --- a/packages/next/src/build/webpack/plugins/force-complete-runtime.ts +++ b/packages/next/src/webpack/build/webpack/plugins/force-complete-runtime.ts @@ -1,4 +1,4 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' +import { webpack } from 'next/dist/webpack/compiled/webpack/webpack' export default class ForceCompleteRuntimePlugin { allSharedRuntimeGlobals = new Set([ diff --git a/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/jsconfig-paths-plugin.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/jsconfig-paths-plugin.ts index 4916d4ef16a4..2d8db2a74a67 100644 --- a/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/jsconfig-paths-plugin.ts @@ -4,9 +4,9 @@ * https://github.com/microsoft/TypeScript/blob/214df64e287804577afa1fea0184c18c40f7d1ca/LICENSE.txt */ import path from 'path' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { debug } from 'next/dist/compiled/debug' -import type { ResolvedBaseUrl } from '../../load-jsconfig' +import type { ResolvedBaseUrl } from 'next/dist/build/load-jsconfig' const log = debug('next:jsconfig-paths-plugin') diff --git a/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/memory-with-gc-cache-plugin.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/memory-with-gc-cache-plugin.ts index 65c734378270..9f36deb3a79e 100644 --- a/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/memory-with-gc-cache-plugin.ts @@ -32,8 +32,8 @@ The default for max generations is 5, so 1/5th of the modules would be marked fo This plugin instead always checks the cache and decreases the time to live of all entries. That way memory is cleaned up earlier. */ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import type { Compiler } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import type { Compiler } from 'next/dist/webpack/compiled/webpack/webpack' // Webpack doesn't expose Etag as a type so get it this way instead. type Etag = Parameters[1] diff --git a/packages/next/src/build/webpack/plugins/middleware-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/middleware-plugin.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/middleware-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/middleware-plugin.ts index 9e1e8c6ccbb5..0e8057f1d57b 100644 --- a/packages/next/src/build/webpack/plugins/middleware-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/middleware-plugin.ts @@ -3,11 +3,11 @@ import type { EdgeMiddlewareMeta, } from '../loaders/get-module-build-info' import type { EdgeSSRMeta } from '../loaders/get-module-build-info' -import type { ProxyMatcher } from '../../analysis/get-page-static-info' -import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex' +import type { ProxyMatcher } from 'next/dist/build/analysis/get-page-static-info' +import { getNamedMiddlewareRegex } from 'next/dist/shared/lib/router/utils/route-regex' import { getModuleBuildInfo } from '../loaders/get-module-build-info' -import { getSortedRoutes } from '../../../shared/lib/router/utils' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { getSortedRoutes } from 'next/dist/shared/lib/router/utils' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import picomatch from 'next/dist/compiled/picomatch' import path from 'path' import { @@ -23,23 +23,23 @@ import { INTERCEPTION_ROUTE_REWRITE_MANIFEST, DYNAMIC_CSS_MANIFEST, SERVER_FILES_MANIFEST, -} from '../../../shared/lib/constants' -import type { ProxyConfig } from '../../analysis/get-page-static-info' -import type { Telemetry } from '../../../telemetry/storage' -import { traceGlobals } from '../../../trace/shared' -import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events' -import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' +} from 'next/dist/shared/lib/constants' +import type { ProxyConfig } from 'next/dist/build/analysis/get-page-static-info' +import type { Telemetry } from 'next/dist/telemetry/storage' +import { traceGlobals } from 'next/dist/trace/shared' +import { EVENT_BUILD_FEATURE_USAGE } from 'next/dist/telemetry/events' +import { normalizeAppPath } from 'next/dist/shared/lib/router/utils/app-paths' import { INSTRUMENTATION_HOOK_FILENAME, WEBPACK_LAYERS, -} from '../../../lib/constants' -import type { CustomRoutes } from '../../../lib/load-custom-routes' -import { isInterceptionRouteRewrite } from '../../../lib/is-interception-route-rewrite' +} from 'next/dist/lib/constants' +import type { CustomRoutes } from 'next/dist/lib/load-custom-routes' +import { isInterceptionRouteRewrite } from 'next/dist/lib/is-interception-route-rewrite' import { getDynamicCodeEvaluationError } from './wellknown-errors-plugin/parse-dynamic-code-evaluation-error' import { getModuleReferencesInOrder } from '../utils' const KNOWN_SAFE_DYNAMIC_PACKAGES = - require('../../../lib/known-edge-safe-packages.json') as string[] + require('next/dist/lib/known-edge-safe-packages.json') as string[] export interface EdgeFunctionDefinition { files: string[] @@ -612,7 +612,8 @@ async function codeAnalyzerBySwc( modules: Iterable, dev: boolean ) { - const binding = require('../../swc') as typeof import('../../swc') + const binding = + require('next/dist/build/swc') as typeof import('next/dist/build/swc') for (const module of modules) { if ( module.layer !== WEBPACK_LAYERS.middleware && diff --git a/packages/next/src/build/webpack/plugins/mini-css-extract-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/mini-css-extract-plugin.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/mini-css-extract-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/mini-css-extract-plugin.ts diff --git a/packages/next/src/build/webpack/plugins/minify-webpack-plugin/LICENSE b/packages/next/src/webpack/build/webpack/plugins/minify-webpack-plugin/LICENSE similarity index 100% rename from packages/next/src/build/webpack/plugins/minify-webpack-plugin/LICENSE rename to packages/next/src/webpack/build/webpack/plugins/minify-webpack-plugin/LICENSE diff --git a/packages/next/src/build/webpack/plugins/minify-webpack-plugin/src/index.ts b/packages/next/src/webpack/build/webpack/plugins/minify-webpack-plugin/src/index.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/minify-webpack-plugin/src/index.ts rename to packages/next/src/webpack/build/webpack/plugins/minify-webpack-plugin/src/index.ts index 8c1a11e896d7..6388b098fe42 100644 --- a/packages/next/src/build/webpack/plugins/minify-webpack-plugin/src/index.ts +++ b/packages/next/src/webpack/build/webpack/plugins/minify-webpack-plugin/src/index.ts @@ -5,7 +5,7 @@ import { WebpackError, type CacheFacade, type Compilation, -} from 'next/dist/compiled/webpack/webpack' +} from 'next/dist/webpack/compiled/webpack/webpack' import pLimit from 'next/dist/compiled/p-limit' import { getCompilationSpan } from '../../../utils' @@ -128,7 +128,7 @@ export class MinifyPlugin { inputSourceMap: Object }) => { const result = await ( - require('../../../../swc') as typeof import('../../../../swc') + require('next/dist/build/swc') as typeof import('next/dist/build/swc') ).minify(options.input, { ...(options.inputSourceMap ? { diff --git a/packages/next/src/build/webpack/plugins/next-font-manifest-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/next-font-manifest-plugin.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/next-font-manifest-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/next-font-manifest-plugin.ts index 2172e3353752..15e5a2931997 100644 --- a/packages/next/src/build/webpack/plugins/next-font-manifest-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/next-font-manifest-plugin.ts @@ -1,6 +1,6 @@ -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' -import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' -import { NEXT_FONT_MANIFEST } from '../../../shared/lib/constants' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' +import getRouteFromEntrypoint from 'next/dist/server/get-route-from-entrypoint' +import { NEXT_FONT_MANIFEST } from 'next/dist/shared/lib/constants' import { traverseModules } from '../utils' import path from 'path' diff --git a/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/next-trace-entrypoints-plugin.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/next-trace-entrypoints-plugin.ts index 9691722243b6..80833e5d7570 100644 --- a/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/next-trace-entrypoints-plugin.ts @@ -1,25 +1,25 @@ import nodePath from 'path' -import type { Span } from '../../../trace' -import isError from '../../../lib/is-error' +import type { Span } from 'next/dist/trace' +import isError from 'next/dist/lib/is-error' import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' import type { NodeFileTraceReasons } from 'next/dist/compiled/@vercel/nft' import { CLIENT_REFERENCE_MANIFEST, TRACE_OUTPUT_VERSION, type CompilerNameValues, -} from '../../../shared/lib/constants' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +} from 'next/dist/shared/lib/constants' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import { NODE_ESM_RESOLVE_OPTIONS, NODE_RESOLVE_OPTIONS, } from '../../webpack-config' -import type { NextConfigComplete } from '../../../server/config-shared' +import type { NextConfigComplete } from 'next/dist/server/config-shared' import picomatch from 'next/dist/compiled/picomatch' import { getModuleBuildInfo } from '../loaders/get-module-build-info' import { getPageFilePath } from '../../entries' import { resolveExternal } from '../../handle-externals' -import { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route' -import { isMiddlewareFilename } from '../../utils' +import { isMetadataRouteFile } from 'next/dist/lib/metadata/is-metadata-route' +import { isMiddlewareFilename } from 'next/dist/build/utils' import { getCompilationSpan } from '../utils' const PLUGIN_NAME = 'TraceEntryPointsPlugin' diff --git a/packages/next/src/build/webpack/plugins/next-types-plugin/index.test.ts b/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/index.test.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/next-types-plugin/index.test.ts rename to packages/next/src/webpack/build/webpack/plugins/next-types-plugin/index.test.ts diff --git a/packages/next/src/build/webpack/plugins/next-types-plugin/index.ts b/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/index.ts similarity index 95% rename from packages/next/src/build/webpack/plugins/next-types-plugin/index.ts rename to packages/next/src/webpack/build/webpack/plugins/next-types-plugin/index.ts index c679d218940a..e662f7575b43 100644 --- a/packages/next/src/build/webpack/plugins/next-types-plugin/index.ts +++ b/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/index.ts @@ -2,22 +2,22 @@ // DOING SO PREVENTS THEM FROM WORKING FOR TURBOPACK USERS. // FOLLOW THE PATTERN OF TYPED-ROUTES AND CACHE-LIFE GENERATION -import type { Rewrite, Redirect } from '../../../../lib/load-custom-routes' +import type { Rewrite, Redirect } from 'next/dist/lib/load-custom-routes' import fs from 'fs/promises' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import path from 'path' -import { WEBPACK_LAYERS } from '../../../../lib/constants' -import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path' -import { ensureLeadingSlash } from '../../../../shared/lib/page-path/ensure-leading-slash' -import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep' -import { HTTP_METHODS } from '../../../../server/web/http' -import { isDynamicRoute } from '../../../../shared/lib/router/utils' -import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths' -import { getPageFromPath } from '../../../route-discovery' -import type { PageExtensions } from '../../../page-extensions-type' -import { getProxiedPluginState } from '../../../build-context' +import { WEBPACK_LAYERS } from 'next/dist/lib/constants' +import { denormalizePagePath } from 'next/dist/shared/lib/page-path/denormalize-page-path' +import { ensureLeadingSlash } from 'next/dist/shared/lib/page-path/ensure-leading-slash' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' +import { HTTP_METHODS } from 'next/dist/server/web/http' +import { isDynamicRoute } from 'next/dist/shared/lib/router/utils' +import { normalizeAppPath } from 'next/dist/shared/lib/router/utils/app-paths' +import { getPageFromPath } from 'next/dist/build/route-discovery' +import type { PageExtensions } from 'next/dist/build/page-extensions-type' +import { getProxiedPluginState } from 'next/dist/build/build-context' const PLUGIN_NAME = 'NextTypesPlugin' diff --git a/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/shared.ts b/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/shared.ts new file mode 100644 index 000000000000..f54ccbd400ad --- /dev/null +++ b/packages/next/src/webpack/build/webpack/plugins/next-types-plugin/shared.ts @@ -0,0 +1 @@ +export { devPageFiles } from 'next/dist/server/dev/dev-page-files' diff --git a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts b/packages/next/src/webpack/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts similarity index 87% rename from packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts rename to packages/next/src/webpack/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts index ffe05b3bbd4e..bfad9753ee79 100644 --- a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts +++ b/packages/next/src/webpack/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts @@ -1,6 +1,6 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { deleteCache } from '../../../server/dev/require-cache' -import { clearModuleContext } from '../../../server/web/sandbox' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' +import { deleteCache } from 'next/dist/server/dev/require-cache' +import { clearModuleContext } from 'next/dist/server/web/sandbox' import path from 'path' type Compiler = webpack.Compiler diff --git a/packages/next/src/build/webpack/plugins/optional-peer-dependency-resolve-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/optional-peer-dependency-resolve-plugin.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/optional-peer-dependency-resolve-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/optional-peer-dependency-resolve-plugin.ts diff --git a/packages/next/src/build/webpack/plugins/pages-manifest-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/pages-manifest-plugin.ts similarity index 94% rename from packages/next/src/build/webpack/plugins/pages-manifest-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/pages-manifest-plugin.ts index 8fe8e3deebce..565e71d0b454 100644 --- a/packages/next/src/build/webpack/plugins/pages-manifest-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/pages-manifest-plugin.ts @@ -1,12 +1,12 @@ import path from 'path' import fs from 'fs/promises' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import { PAGES_MANIFEST, APP_PATHS_MANIFEST, -} from '../../../shared/lib/constants' -import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' -import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' +} from 'next/dist/shared/lib/constants' +import getRouteFromEntrypoint from 'next/dist/server/get-route-from-entrypoint' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' export type PagesManifest = { [page: string]: string } diff --git a/packages/next/src/build/webpack/plugins/profiling-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/profiling-plugin.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/profiling-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/profiling-plugin.ts index a17746719193..60df57150c8c 100644 --- a/packages/next/src/build/webpack/plugins/profiling-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/profiling-plugin.ts @@ -1,6 +1,6 @@ -import { NormalModule } from 'next/dist/compiled/webpack/webpack' -import type { Span } from '../../../trace' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import { NormalModule } from 'next/dist/webpack/compiled/webpack/webpack' +import type { Span } from 'next/dist/trace' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import path from 'path' const pluginName = 'ProfilingPlugin' diff --git a/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/react-loadable-plugin.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/react-loadable-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/react-loadable-plugin.ts index dc4f23748a33..62c5c3ee2e29 100644 --- a/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/react-loadable-plugin.ts @@ -24,10 +24,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR import type { DynamicCssManifest, ReactLoadableManifest, -} from '../../../server/load-components' +} from 'next/dist/server/load-components' import path from 'path' -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' -import { DYNAMIC_CSS_MANIFEST } from '../../../shared/lib/constants' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' +import { DYNAMIC_CSS_MANIFEST } from 'next/dist/shared/lib/constants' function getModuleId(compilation: any, module: any): string | number { return compilation.chunkGraph.getModuleId(module) diff --git a/packages/next/src/build/webpack/plugins/rspack-flight-client-entry-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/rspack-flight-client-entry-plugin.ts similarity index 93% rename from packages/next/src/build/webpack/plugins/rspack-flight-client-entry-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/rspack-flight-client-entry-plugin.ts index af26d7fd159e..5a40b00517d7 100644 --- a/packages/next/src/build/webpack/plugins/rspack-flight-client-entry-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/rspack-flight-client-entry-plugin.ts @@ -4,12 +4,12 @@ import { getEntries, EntryTypes, getEntryKey, -} from '../../../server/dev/on-demand-entry-handler' -import { COMPILER_NAMES } from '../../../shared/lib/constants' +} from 'next/dist/server/dev/on-demand-entry-handler' +import { COMPILER_NAMES } from 'next/dist/shared/lib/constants' -import { getProxiedPluginState } from '../../build-context' -import { PAGE_TYPES } from '../../../lib/page-types' -import { getRspackCore } from '../../../shared/lib/get-rspack' +import { getProxiedPluginState } from 'next/dist/build/build-context' +import { PAGE_TYPES } from 'next/dist/lib/page-types' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' type Actions = { [actionId: string]: { diff --git a/packages/next/src/build/webpack/plugins/rspack-profiling-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/rspack-profiling-plugin.ts similarity index 94% rename from packages/next/src/build/webpack/plugins/rspack-profiling-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/rspack-profiling-plugin.ts index 49008e9660a5..b331ae0b75f3 100644 --- a/packages/next/src/build/webpack/plugins/rspack-profiling-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/rspack-profiling-plugin.ts @@ -1,8 +1,8 @@ // A basic implementation to allow loaders access to loaderContext.currentTraceSpan -import type { Span } from '../../../trace' +import type { Span } from 'next/dist/trace' -import { getRspackCore } from '../../../shared/lib/get-rspack' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' const pluginName = 'RspackProfilingPlugin' const moduleSpansByCompilation = new WeakMap() diff --git a/packages/next/src/build/webpack/plugins/slow-module-detection-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/slow-module-detection-plugin.ts similarity index 98% rename from packages/next/src/build/webpack/plugins/slow-module-detection-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/slow-module-detection-plugin.ts index 559c944b611a..a8ebcc691980 100644 --- a/packages/next/src/build/webpack/plugins/slow-module-detection-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/slow-module-detection-plugin.ts @@ -1,6 +1,6 @@ import type { Compiler, Module, Compilation } from 'webpack' -import type { CompilerNameValues } from '../../../shared/lib/constants' -import { yellow, green, blue } from '../../../lib/picocolors' +import type { CompilerNameValues } from 'next/dist/shared/lib/constants' +import { yellow, green, blue } from 'next/dist/lib/picocolors' const PLUGIN_NAME = 'SlowModuleDetectionPlugin' diff --git a/packages/next/src/build/webpack/plugins/subresource-integrity-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/subresource-integrity-plugin.ts similarity index 93% rename from packages/next/src/build/webpack/plugins/subresource-integrity-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/subresource-integrity-plugin.ts index fb24899991d4..9513f07e8d35 100644 --- a/packages/next/src/build/webpack/plugins/subresource-integrity-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/subresource-integrity-plugin.ts @@ -1,6 +1,6 @@ -import { webpack, sources } from 'next/dist/compiled/webpack/webpack' +import { webpack, sources } from 'next/dist/webpack/compiled/webpack/webpack' import crypto from 'crypto' -import { SUBRESOURCE_INTEGRITY_MANIFEST } from '../../../shared/lib/constants' +import { SUBRESOURCE_INTEGRITY_MANIFEST } from 'next/dist/shared/lib/constants' const PLUGIN_NAME = 'SubresourceIntegrityPlugin' diff --git a/packages/next/src/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts b/packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts similarity index 99% rename from packages/next/src/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts rename to packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts index b467fe60315b..1f44712180f4 100644 --- a/packages/next/src/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts +++ b/packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/telemetry-plugin.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { createUseCacheTracker, type UseCacheTrackerKey, diff --git a/packages/next/src/build/webpack/plugins/telemetry-plugin/update-telemetry-loader-context-from-swc.ts b/packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/update-telemetry-loader-context-from-swc.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/telemetry-plugin/update-telemetry-loader-context-from-swc.ts rename to packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/update-telemetry-loader-context-from-swc.ts diff --git a/packages/next/src/build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils.ts b/packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils.ts rename to packages/next/src/webpack/build/webpack/plugins/telemetry-plugin/use-cache-tracker-utils.ts diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts index 5d67ded10ca3..701adb6232bf 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import loaderUtils from 'next/dist/compiled/loader-utils3' import { relative } from 'path' diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/index.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/index.ts similarity index 94% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/index.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/index.ts index a4be9714c78c..06b668f1e704 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/index.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/index.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { getModuleBuildError } from './webpackModuleError' diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts similarity index 90% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts index da61731d0fdf..54c473893f25 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parse-dynamic-code-evaluation-error.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { formatModuleTrace, getModuleTrace } from './getModuleTrace' import { SimpleWebpackError } from './simpleWebpackError' diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts similarity index 93% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts index a3edb7899a06..fc45bcd0300a 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseBabel.ts @@ -1,4 +1,4 @@ -import { bold, cyan, red, yellow } from '../../../../lib/picocolors' +import { bold, cyan, red, yellow } from 'next/dist/lib/picocolors' import { SimpleWebpackError } from './simpleWebpackError' export function getBabelError( diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts similarity index 93% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts index 5187b8c8f0ca..c07eb8179b03 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseCss.ts @@ -1,4 +1,4 @@ -import { bold, cyan, red, yellow } from '../../../../lib/picocolors' +import { bold, cyan, red, yellow } from 'next/dist/lib/picocolors' import { SimpleWebpackError } from './simpleWebpackError' const regexCssError = diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts similarity index 88% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts index eb394740fcf4..155a363fc12e 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { relative } from 'path' import { SimpleWebpackError } from './simpleWebpackError' import { getAppLoader } from '../../../entries' diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.ts similarity index 100% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.ts diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts similarity index 92% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts index 68f2f91d3c8a..94b3ae5243fb 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { formatModuleTrace, getModuleTrace } from './getModuleTrace' import { SimpleWebpackError } from './simpleWebpackError' diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts similarity index 97% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts index 411b425bf265..a2a2615ad0bb 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts @@ -1,11 +1,11 @@ -import { bold, cyan, green, red, yellow } from '../../../../lib/picocolors' +import { bold, cyan, green, red, yellow } from 'next/dist/lib/picocolors' import { SimpleWebpackError } from './simpleWebpackError' import { createOriginalStackFrame, getIgnoredSources, } from '../../../../server/dev/middleware-webpack' -import isInternal from '../../../../shared/lib/is-internal' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import isInternal from 'next/dist/shared/lib/is-internal' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import type { RawSourceMap } from 'next/dist/compiled/source-map08' // Based on https://github.com/webpack/webpack/blob/fcdd04a833943394bbb0a9eeb54a962a24cc7e41/lib/stats/DefaultStatsFactoryPlugin.js#L422-L431 diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts similarity index 88% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts index fbb6442a557b..86656024e659 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/parseScss.ts @@ -1,7 +1,7 @@ -import { bold, cyan, red, yellow } from '../../../../lib/picocolors' +import { bold, cyan, red, yellow } from 'next/dist/lib/picocolors' import { SimpleWebpackError } from './simpleWebpackError' -import { codeFrameColumns } from '../../../../shared/lib/errors/code-frame' +import { codeFrameColumns } from 'next/dist/shared/lib/errors/code-frame' const regexScssError = /SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts similarity index 85% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts index c53e5bb1d873..839a5372f28c 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.ts @@ -1,4 +1,4 @@ -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' // This class creates a simplified webpack error that formats nicely based on // webpack's build in serializer. diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts similarity index 96% rename from packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts rename to packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts index 8b5706a0ced8..67344e7f7463 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts +++ b/packages/next/src/webpack/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts @@ -1,13 +1,13 @@ import { readFileSync } from 'fs' import * as path from 'path' -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import { getBabelError } from './parseBabel' import { getCssError } from './parseCss' import { getScssError } from './parseScss' import { getNotFoundError, getImageError } from './parseNotFoundError' import type { SimpleWebpackError } from './simpleWebpackError' -import isError from '../../../../lib/is-error' +import isError from 'next/dist/lib/is-error' import { getNextFontError } from './parseNextFontError' import { getNextAppLoaderError } from './parseNextAppLoaderError' import { getNextInvalidImportError } from './parseNextInvalidImportError' diff --git a/packages/next/src/build/webpack/stringify-request.ts b/packages/next/src/webpack/build/webpack/stringify-request.ts similarity index 100% rename from packages/next/src/build/webpack/stringify-request.ts rename to packages/next/src/webpack/build/webpack/stringify-request.ts diff --git a/packages/next/src/build/webpack/utils.ts b/packages/next/src/webpack/build/webpack/utils.ts similarity index 98% rename from packages/next/src/build/webpack/utils.ts rename to packages/next/src/webpack/build/webpack/utils.ts index 2fc6283e512b..808106a3b6c8 100644 --- a/packages/next/src/build/webpack/utils.ts +++ b/packages/next/src/webpack/build/webpack/utils.ts @@ -11,7 +11,7 @@ import type { ModuleGraphConnection } from 'webpack' import { getAppLoader } from '../entries' import { spans as webpackCompilationSpans } from './plugins/profiling-plugin' import { compilationSpans as rspackCompilationSpans } from './plugins/rspack-profiling-plugin' -import type { Span } from '../../trace' +import type { Span } from 'next/dist/trace' export function traverseModules( compilation: Compilation, diff --git a/packages/next/src/bundles/webpack/bundle5.js b/packages/next/src/webpack/bundles/webpack/bundle5.js similarity index 100% rename from packages/next/src/bundles/webpack/bundle5.js rename to packages/next/src/webpack/bundles/webpack/bundle5.js diff --git a/packages/next/src/bundles/webpack/packages/BasicEvaluatedExpression.js b/packages/next/src/webpack/bundles/webpack/packages/BasicEvaluatedExpression.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/BasicEvaluatedExpression.js rename to packages/next/src/webpack/bundles/webpack/packages/BasicEvaluatedExpression.js diff --git a/packages/next/src/bundles/webpack/packages/ExternalsPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/ExternalsPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/ExternalsPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/ExternalsPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/FetchCompileAsyncWasmPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/FetchCompileAsyncWasmPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/FetchCompileAsyncWasmPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/FetchCompileAsyncWasmPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/FetchCompileWasmPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/FetchCompileWasmPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/FetchCompileWasmPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/FetchCompileWasmPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/FetchCompileWasmTemplatePlugin.js b/packages/next/src/webpack/bundles/webpack/packages/FetchCompileWasmTemplatePlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/FetchCompileWasmTemplatePlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/FetchCompileWasmTemplatePlugin.js diff --git a/packages/next/src/bundles/webpack/packages/GraphHelpers.js b/packages/next/src/webpack/bundles/webpack/packages/GraphHelpers.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/GraphHelpers.js rename to packages/next/src/webpack/bundles/webpack/packages/GraphHelpers.js diff --git a/packages/next/src/bundles/webpack/packages/HotModuleReplacement.runtime.js b/packages/next/src/webpack/bundles/webpack/packages/HotModuleReplacement.runtime.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/HotModuleReplacement.runtime.js rename to packages/next/src/webpack/bundles/webpack/packages/HotModuleReplacement.runtime.js diff --git a/packages/next/src/bundles/webpack/packages/JavascriptHotModuleReplacement.runtime.js b/packages/next/src/webpack/bundles/webpack/packages/JavascriptHotModuleReplacement.runtime.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/JavascriptHotModuleReplacement.runtime.js rename to packages/next/src/webpack/bundles/webpack/packages/JavascriptHotModuleReplacement.runtime.js diff --git a/packages/next/src/bundles/webpack/packages/LibraryTemplatePlugin.js b/packages/next/src/webpack/bundles/webpack/packages/LibraryTemplatePlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/LibraryTemplatePlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/LibraryTemplatePlugin.js diff --git a/packages/next/src/bundles/webpack/packages/LimitChunkCountPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/LimitChunkCountPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/LimitChunkCountPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/LimitChunkCountPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/ModuleFilenameHelpers.js b/packages/next/src/webpack/bundles/webpack/packages/ModuleFilenameHelpers.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/ModuleFilenameHelpers.js rename to packages/next/src/webpack/bundles/webpack/packages/ModuleFilenameHelpers.js diff --git a/packages/next/src/bundles/webpack/packages/NodeEnvironmentPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/NodeEnvironmentPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/NodeEnvironmentPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/NodeEnvironmentPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/NodeTargetPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/NodeTargetPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/NodeTargetPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/NodeTargetPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/NodeTemplatePlugin.js b/packages/next/src/webpack/bundles/webpack/packages/NodeTemplatePlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/NodeTemplatePlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/NodeTemplatePlugin.js diff --git a/packages/next/src/bundles/webpack/packages/NormalModule.js b/packages/next/src/webpack/bundles/webpack/packages/NormalModule.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/NormalModule.js rename to packages/next/src/webpack/bundles/webpack/packages/NormalModule.js diff --git a/packages/next/src/bundles/webpack/packages/SingleEntryPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/SingleEntryPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/SingleEntryPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/SingleEntryPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/SourceMapDevToolModuleOptionsPlugin.js b/packages/next/src/webpack/bundles/webpack/packages/SourceMapDevToolModuleOptionsPlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/SourceMapDevToolModuleOptionsPlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/SourceMapDevToolModuleOptionsPlugin.js diff --git a/packages/next/src/bundles/webpack/packages/WebWorkerTemplatePlugin.js b/packages/next/src/webpack/bundles/webpack/packages/WebWorkerTemplatePlugin.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/WebWorkerTemplatePlugin.js rename to packages/next/src/webpack/bundles/webpack/packages/WebWorkerTemplatePlugin.js diff --git a/packages/next/src/bundles/webpack/packages/lazy-compilation-node.js b/packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-node.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/lazy-compilation-node.js rename to packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-node.js diff --git a/packages/next/src/bundles/webpack/packages/lazy-compilation-web.js b/packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-web.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/lazy-compilation-web.js rename to packages/next/src/webpack/bundles/webpack/packages/lazy-compilation-web.js diff --git a/packages/next/src/bundles/webpack/packages/package.js b/packages/next/src/webpack/bundles/webpack/packages/package.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/package.js rename to packages/next/src/webpack/bundles/webpack/packages/package.js diff --git a/packages/next/src/bundles/webpack/packages/sources.js b/packages/next/src/webpack/bundles/webpack/packages/sources.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/sources.js rename to packages/next/src/webpack/bundles/webpack/packages/sources.js diff --git a/packages/next/src/bundles/webpack/packages/webpack-lib.js b/packages/next/src/webpack/bundles/webpack/packages/webpack-lib.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/webpack-lib.js rename to packages/next/src/webpack/bundles/webpack/packages/webpack-lib.js diff --git a/packages/next/src/bundles/webpack/packages/webpack.d.ts b/packages/next/src/webpack/bundles/webpack/packages/webpack.d.ts similarity index 100% rename from packages/next/src/bundles/webpack/packages/webpack.d.ts rename to packages/next/src/webpack/bundles/webpack/packages/webpack.d.ts diff --git a/packages/next/src/bundles/webpack/packages/webpack.js b/packages/next/src/webpack/bundles/webpack/packages/webpack.js similarity index 100% rename from packages/next/src/bundles/webpack/packages/webpack.js rename to packages/next/src/webpack/bundles/webpack/packages/webpack.js diff --git a/packages/next/src/webpack/client/app-webpack.ts b/packages/next/src/webpack/client/app-webpack.ts new file mode 100644 index 000000000000..1b23f885d931 --- /dev/null +++ b/packages/next/src/webpack/client/app-webpack.ts @@ -0,0 +1,44 @@ +// Override chunk URL mapping in the webpack runtime +// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204 + +import 'next/dist/client/register-deployment-id-global' +import { + getAssetToken, + getAssetTokenQuery, +} from 'next/dist/shared/lib/deployment-id' +import { encodeURIPath } from 'next/dist/shared/lib/encode-uri-path' + +declare const __webpack_require__: any + +// If we have a deployment ID, we need to append it to the webpack chunk names +// I am keeping the process check explicit so this can be statically optimized +if (getAssetToken()) { + const suffix = getAssetTokenQuery() + const getChunkScriptFilename = __webpack_require__.u + __webpack_require__.u = (...args: any[]) => + // We encode the chunk filename because our static server matches against and encoded + // filename path. + encodeURIPath(getChunkScriptFilename(...args)) + suffix + + const getChunkCssFilename = __webpack_require__.k + __webpack_require__.k = (...args: any[]) => + getChunkCssFilename(...args) + suffix + + const getMiniCssFilename = __webpack_require__.miniCssF + __webpack_require__.miniCssF = (...args: any[]) => + getMiniCssFilename(...args) + suffix +} else { + const getChunkScriptFilename = __webpack_require__.u + __webpack_require__.u = (...args: any[]) => + // We encode the chunk filename because our static server matches against and encoded + // filename path. + encodeURIPath(getChunkScriptFilename(...args)) + + // We don't need to override __webpack_require__.k because we don't modify + // the css chunk name when not using deployment id suffixes + + // WE don't need to override __webpack_require__.miniCssF because we don't modify + // the mini css chunk name when not using deployment id suffixes +} + +export {} diff --git a/packages/next/src/webpack/client/webpack.ts b/packages/next/src/webpack/client/webpack.ts new file mode 100644 index 000000000000..f657bdec0f35 --- /dev/null +++ b/packages/next/src/webpack/client/webpack.ts @@ -0,0 +1,33 @@ +declare const __webpack_require__: any +declare let __webpack_public_path__: string + +import { + getAssetToken, + getAssetTokenQuery, +} from 'next/dist/shared/lib/deployment-id' + +// If we have a deployment ID query string, we need to append it to the webpack chunk names +// I am keeping the process check explicit so this can be statically optimized +if (getAssetToken()) { + const suffix = getAssetTokenQuery() + const getChunkScriptFilename = __webpack_require__.u + __webpack_require__.u = (...args: any[]) => + // We enode the chunk filename because our static server matches against and encoded + // filename path. + getChunkScriptFilename(...args) + suffix + + const getChunkCssFilename = __webpack_require__.k + __webpack_require__.k = (...args: any[]) => + getChunkCssFilename(...args) + suffix + + const getMiniCssFilename = __webpack_require__.miniCssF + __webpack_require__.miniCssF = (...args: any[]) => + getMiniCssFilename(...args) + suffix +} + +// Ignore the module ID transform in client. +;(self as any).__next_set_public_path__ = (path: string) => { + __webpack_public_path__ = path +} + +export {} diff --git a/packages/next/src/compiled/webpack/BasicEvaluatedExpression.js b/packages/next/src/webpack/compiled/webpack/BasicEvaluatedExpression.js similarity index 100% rename from packages/next/src/compiled/webpack/BasicEvaluatedExpression.js rename to packages/next/src/webpack/compiled/webpack/BasicEvaluatedExpression.js diff --git a/packages/next/src/compiled/webpack/ExternalsPlugin.js b/packages/next/src/webpack/compiled/webpack/ExternalsPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/ExternalsPlugin.js rename to packages/next/src/webpack/compiled/webpack/ExternalsPlugin.js diff --git a/packages/next/src/compiled/webpack/FetchCompileAsyncWasmPlugin.js b/packages/next/src/webpack/compiled/webpack/FetchCompileAsyncWasmPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/FetchCompileAsyncWasmPlugin.js rename to packages/next/src/webpack/compiled/webpack/FetchCompileAsyncWasmPlugin.js diff --git a/packages/next/src/compiled/webpack/FetchCompileWasmPlugin.js b/packages/next/src/webpack/compiled/webpack/FetchCompileWasmPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/FetchCompileWasmPlugin.js rename to packages/next/src/webpack/compiled/webpack/FetchCompileWasmPlugin.js diff --git a/packages/next/src/compiled/webpack/FetchCompileWasmTemplatePlugin.js b/packages/next/src/webpack/compiled/webpack/FetchCompileWasmTemplatePlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/FetchCompileWasmTemplatePlugin.js rename to packages/next/src/webpack/compiled/webpack/FetchCompileWasmTemplatePlugin.js diff --git a/packages/next/src/compiled/webpack/GraphHelpers.js b/packages/next/src/webpack/compiled/webpack/GraphHelpers.js similarity index 100% rename from packages/next/src/compiled/webpack/GraphHelpers.js rename to packages/next/src/webpack/compiled/webpack/GraphHelpers.js diff --git a/packages/next/src/compiled/webpack/HotModuleReplacement.runtime.js b/packages/next/src/webpack/compiled/webpack/HotModuleReplacement.runtime.js similarity index 100% rename from packages/next/src/compiled/webpack/HotModuleReplacement.runtime.js rename to packages/next/src/webpack/compiled/webpack/HotModuleReplacement.runtime.js diff --git a/packages/next/src/compiled/webpack/JavascriptHotModuleReplacement.runtime.js b/packages/next/src/webpack/compiled/webpack/JavascriptHotModuleReplacement.runtime.js similarity index 100% rename from packages/next/src/compiled/webpack/JavascriptHotModuleReplacement.runtime.js rename to packages/next/src/webpack/compiled/webpack/JavascriptHotModuleReplacement.runtime.js diff --git a/packages/next/src/compiled/webpack/LICENSE b/packages/next/src/webpack/compiled/webpack/LICENSE similarity index 100% rename from packages/next/src/compiled/webpack/LICENSE rename to packages/next/src/webpack/compiled/webpack/LICENSE diff --git a/packages/next/src/compiled/webpack/LibraryTemplatePlugin.js b/packages/next/src/webpack/compiled/webpack/LibraryTemplatePlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/LibraryTemplatePlugin.js rename to packages/next/src/webpack/compiled/webpack/LibraryTemplatePlugin.js diff --git a/packages/next/src/compiled/webpack/LimitChunkCountPlugin.js b/packages/next/src/webpack/compiled/webpack/LimitChunkCountPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/LimitChunkCountPlugin.js rename to packages/next/src/webpack/compiled/webpack/LimitChunkCountPlugin.js diff --git a/packages/next/src/compiled/webpack/ModuleFilenameHelpers.js b/packages/next/src/webpack/compiled/webpack/ModuleFilenameHelpers.js similarity index 100% rename from packages/next/src/compiled/webpack/ModuleFilenameHelpers.js rename to packages/next/src/webpack/compiled/webpack/ModuleFilenameHelpers.js diff --git a/packages/next/src/compiled/webpack/NodeEnvironmentPlugin.js b/packages/next/src/webpack/compiled/webpack/NodeEnvironmentPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/NodeEnvironmentPlugin.js rename to packages/next/src/webpack/compiled/webpack/NodeEnvironmentPlugin.js diff --git a/packages/next/src/compiled/webpack/NodeTargetPlugin.js b/packages/next/src/webpack/compiled/webpack/NodeTargetPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/NodeTargetPlugin.js rename to packages/next/src/webpack/compiled/webpack/NodeTargetPlugin.js diff --git a/packages/next/src/compiled/webpack/NodeTemplatePlugin.js b/packages/next/src/webpack/compiled/webpack/NodeTemplatePlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/NodeTemplatePlugin.js rename to packages/next/src/webpack/compiled/webpack/NodeTemplatePlugin.js diff --git a/packages/next/src/compiled/webpack/NormalModule.js b/packages/next/src/webpack/compiled/webpack/NormalModule.js similarity index 100% rename from packages/next/src/compiled/webpack/NormalModule.js rename to packages/next/src/webpack/compiled/webpack/NormalModule.js diff --git a/packages/next/src/compiled/webpack/SingleEntryPlugin.js b/packages/next/src/webpack/compiled/webpack/SingleEntryPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/SingleEntryPlugin.js rename to packages/next/src/webpack/compiled/webpack/SingleEntryPlugin.js diff --git a/packages/next/src/compiled/webpack/SourceMapDevToolModuleOptionsPlugin.js b/packages/next/src/webpack/compiled/webpack/SourceMapDevToolModuleOptionsPlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/SourceMapDevToolModuleOptionsPlugin.js rename to packages/next/src/webpack/compiled/webpack/SourceMapDevToolModuleOptionsPlugin.js diff --git a/packages/next/src/compiled/webpack/WebWorkerTemplatePlugin.js b/packages/next/src/webpack/compiled/webpack/WebWorkerTemplatePlugin.js similarity index 100% rename from packages/next/src/compiled/webpack/WebWorkerTemplatePlugin.js rename to packages/next/src/webpack/compiled/webpack/WebWorkerTemplatePlugin.js diff --git a/packages/next/src/compiled/webpack/bundle5.js b/packages/next/src/webpack/compiled/webpack/bundle5.js similarity index 100% rename from packages/next/src/compiled/webpack/bundle5.js rename to packages/next/src/webpack/compiled/webpack/bundle5.js diff --git a/packages/next/src/compiled/webpack/lazy-compilation-node.js b/packages/next/src/webpack/compiled/webpack/lazy-compilation-node.js similarity index 100% rename from packages/next/src/compiled/webpack/lazy-compilation-node.js rename to packages/next/src/webpack/compiled/webpack/lazy-compilation-node.js diff --git a/packages/next/src/compiled/webpack/lazy-compilation-web.js b/packages/next/src/webpack/compiled/webpack/lazy-compilation-web.js similarity index 100% rename from packages/next/src/compiled/webpack/lazy-compilation-web.js rename to packages/next/src/webpack/compiled/webpack/lazy-compilation-web.js diff --git a/packages/next/src/compiled/webpack/package.js b/packages/next/src/webpack/compiled/webpack/package.js similarity index 100% rename from packages/next/src/compiled/webpack/package.js rename to packages/next/src/webpack/compiled/webpack/package.js diff --git a/packages/next/src/compiled/webpack/package.json b/packages/next/src/webpack/compiled/webpack/package.json similarity index 100% rename from packages/next/src/compiled/webpack/package.json rename to packages/next/src/webpack/compiled/webpack/package.json diff --git a/packages/next/src/compiled/webpack/sources.js b/packages/next/src/webpack/compiled/webpack/sources.js similarity index 100% rename from packages/next/src/compiled/webpack/sources.js rename to packages/next/src/webpack/compiled/webpack/sources.js diff --git a/packages/next/src/compiled/webpack/webpack-lib.js b/packages/next/src/webpack/compiled/webpack/webpack-lib.js similarity index 100% rename from packages/next/src/compiled/webpack/webpack-lib.js rename to packages/next/src/webpack/compiled/webpack/webpack-lib.js diff --git a/packages/next/src/webpack/compiled/webpack/webpack.d.ts b/packages/next/src/webpack/compiled/webpack/webpack.d.ts new file mode 100644 index 000000000000..4e3de65af789 --- /dev/null +++ b/packages/next/src/webpack/compiled/webpack/webpack.d.ts @@ -0,0 +1,43 @@ +export namespace webpack { + export type Compiler = any + export type Plugin = any + export type Configuration = any + export type StatsError = any + export type Stats = any + export type MultiCompiler = any + export type EntryObject = any + export type ProgressPlugin = any + export type Compilation = any + export type javascript = any + export type Module = any + export type ModuleGraph = any + export type WebpackPluginInstance = any + export type Template = any + export type RuntimeModule = any + export type RuntimeGlobals = any + export type NormalModule = any + export type ResolvePluginInstance = any + export type ResolveOptions = any + export type Resolver = any + export type LoaderDefinitionFunction = any + export type LoaderContext = any + export type RuleSetUseItem = any + export type Chunk = any + export type ChunkGroup = any + export type DefinePlugin = any + export namespace sources { + export type RawSource = any + } +} + +export function init(): void +export let BasicEvaluatedExpression: any +export let ConcatenatedModule: any +export let GraphHelpers: any +export let ModuleFilenameHelpers: any +export let NormalModule: any +export let sources: any +export let StringXor: any +export let WebpackError: any +export let webpack: any +export default webpack diff --git a/packages/next/src/compiled/webpack/webpack.js b/packages/next/src/webpack/compiled/webpack/webpack.js similarity index 100% rename from packages/next/src/compiled/webpack/webpack.js rename to packages/next/src/webpack/compiled/webpack/webpack.js diff --git a/packages/next/src/webpack/load-webpack-hook.ts b/packages/next/src/webpack/load-webpack-hook.ts new file mode 100644 index 000000000000..7f7198004a8d --- /dev/null +++ b/packages/next/src/webpack/load-webpack-hook.ts @@ -0,0 +1,131 @@ +let installed = false + +export function loadWebpackHook() { + if (installed) { + return + } + installed = true + ;( + require('next/dist/server/require-hook') as typeof import('next/dist/server/require-hook') + ).addHookAliases( + [ + ['webpack', './compiled/webpack/webpack-lib'], + ['webpack/package', './compiled/webpack/package'], + ['webpack/package.json', './compiled/webpack/package'], + ['webpack/lib/webpack', './compiled/webpack/webpack-lib'], + ['webpack/lib/webpack.js', './compiled/webpack/webpack-lib'], + [ + 'webpack/lib/node/NodeEnvironmentPlugin', + './compiled/webpack/NodeEnvironmentPlugin', + ], + [ + 'webpack/lib/node/NodeEnvironmentPlugin.js', + './compiled/webpack/NodeEnvironmentPlugin', + ], + [ + 'webpack/lib/BasicEvaluatedExpression', + './compiled/webpack/BasicEvaluatedExpression', + ], + [ + 'webpack/lib/BasicEvaluatedExpression.js', + './compiled/webpack/BasicEvaluatedExpression', + ], + [ + 'webpack/lib/node/NodeTargetPlugin', + './compiled/webpack/NodeTargetPlugin', + ], + [ + 'webpack/lib/node/NodeTargetPlugin.js', + './compiled/webpack/NodeTargetPlugin', + ], + [ + 'webpack/lib/node/NodeTemplatePlugin', + './compiled/webpack/NodeTemplatePlugin', + ], + [ + 'webpack/lib/node/NodeTemplatePlugin.js', + './compiled/webpack/NodeTemplatePlugin', + ], + [ + 'webpack/lib/LibraryTemplatePlugin', + './compiled/webpack/LibraryTemplatePlugin', + ], + [ + 'webpack/lib/LibraryTemplatePlugin.js', + './compiled/webpack/LibraryTemplatePlugin', + ], + ['webpack/lib/SingleEntryPlugin', './compiled/webpack/SingleEntryPlugin'], + [ + 'webpack/lib/SingleEntryPlugin.js', + './compiled/webpack/SingleEntryPlugin', + ], + [ + 'webpack/lib/optimize/LimitChunkCountPlugin', + './compiled/webpack/LimitChunkCountPlugin', + ], + [ + 'webpack/lib/optimize/LimitChunkCountPlugin.js', + './compiled/webpack/LimitChunkCountPlugin', + ], + [ + 'webpack/lib/webworker/WebWorkerTemplatePlugin', + './compiled/webpack/WebWorkerTemplatePlugin', + ], + [ + 'webpack/lib/webworker/WebWorkerTemplatePlugin.js', + './compiled/webpack/WebWorkerTemplatePlugin', + ], + ['webpack/lib/ExternalsPlugin', './compiled/webpack/ExternalsPlugin'], + ['webpack/lib/ExternalsPlugin.js', './compiled/webpack/ExternalsPlugin'], + [ + 'webpack/lib/web/FetchCompileWasmTemplatePlugin', + './compiled/webpack/FetchCompileWasmTemplatePlugin', + ], + [ + 'webpack/lib/web/FetchCompileWasmTemplatePlugin.js', + './compiled/webpack/FetchCompileWasmTemplatePlugin', + ], + [ + 'webpack/lib/web/FetchCompileWasmPlugin', + './compiled/webpack/FetchCompileWasmPlugin', + ], + [ + 'webpack/lib/web/FetchCompileWasmPlugin.js', + './compiled/webpack/FetchCompileWasmPlugin', + ], + [ + 'webpack/lib/web/FetchCompileAsyncWasmPlugin', + './compiled/webpack/FetchCompileAsyncWasmPlugin', + ], + [ + 'webpack/lib/web/FetchCompileAsyncWasmPlugin.js', + './compiled/webpack/FetchCompileAsyncWasmPlugin', + ], + [ + 'webpack/lib/ModuleFilenameHelpers', + './compiled/webpack/ModuleFilenameHelpers', + ], + [ + 'webpack/lib/ModuleFilenameHelpers.js', + './compiled/webpack/ModuleFilenameHelpers', + ], + ['webpack/lib/GraphHelpers', './compiled/webpack/GraphHelpers'], + ['webpack/lib/GraphHelpers.js', './compiled/webpack/GraphHelpers'], + ['webpack/lib/NormalModule', './compiled/webpack/NormalModule'], + ['webpack-sources', './compiled/webpack/sources'], + ['webpack-sources/lib', './compiled/webpack/sources'], + ['webpack-sources/lib/index', './compiled/webpack/sources'], + ['webpack-sources/lib/index.js', './compiled/webpack/sources'], + ['@babel/runtime', 'next/dist/compiled/@babel/runtime/package.json'], + [ + '@babel/runtime/package.json', + 'next/dist/compiled/@babel/runtime/package.json', + ], + ].map(([request, replacement]) => [ + request, + replacement.startsWith('.') + ? require.resolve(replacement) + : require.resolve(replacement), + ]) + ) +} diff --git a/packages/next/src/webpack/next-integration.ts b/packages/next/src/webpack/next-integration.ts new file mode 100644 index 000000000000..5abdb35bf459 --- /dev/null +++ b/packages/next/src/webpack/next-integration.ts @@ -0,0 +1,22 @@ +export { webpackBuild } from './build/webpack-build' +export { + checkFileSystemCacheInvalidationAndCleanup, + invalidateFileSystemCache, +} from './build/webpack/cache-invalidation' +export { loadWebpackHook } from './load-webpack-hook' +export { default as HotReloaderWebpack } from './server/dev/hot-reloader-webpack' +export { default as HotReloaderRspack } from './server/dev/hot-reloader-rspack' +export { + default as getBaseWebpackConfig, + getCacheDirectories, + loadProjectInfo, + attachReactRefresh, + babelIncludeRegexes, + hasExternalOtelApiPackage, + nextImageLoaderRegex, + NODE_RESOLVE_OPTIONS, + NODE_BASE_RESOLVE_OPTIONS, + NODE_ESM_RESOLVE_OPTIONS, + NODE_BASE_ESM_RESOLVE_OPTIONS, +} from './build/webpack-config' +export { JsConfigPathsPlugin } from './build/webpack/plugins/jsconfig-paths-plugin' diff --git a/packages/next/src/server/dev/hot-middleware.ts b/packages/next/src/webpack/server/dev/hot-middleware.ts similarity index 93% rename from packages/next/src/server/dev/hot-middleware.ts rename to packages/next/src/webpack/server/dev/hot-middleware.ts index 3a7e0623262b..b0f5831e9026 100644 --- a/packages/next/src/server/dev/hot-middleware.ts +++ b/packages/next/src/webpack/server/dev/hot-middleware.ts @@ -21,16 +21,16 @@ // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/webpack/compiled/webpack/webpack' import type ws from 'next/dist/compiled/ws' -import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared' -import { isMiddlewareFilename } from '../../build/utils' -import type { VersionInfo } from './parse-version-info' -import type { HmrMessageSentToBrowser } from './hot-reloader-types' -import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types' -import { devIndicatorServerState } from './dev-indicator-server-state' -import { createBinaryHmrMessageData } from './messages' -import type { NextConfigComplete } from '../config-shared' +import type { DevToolsConfig } from 'next/dist/next-devtools/dev-overlay/shared' +import { isMiddlewareFilename } from 'next/dist/build/utils' +import type { VersionInfo } from 'next/dist/server/dev/parse-version-info' +import type { HmrMessageSentToBrowser } from 'next/dist/server/dev/hot-reloader-types' +import { HMR_MESSAGE_SENT_TO_BROWSER } from 'next/dist/server/dev/hot-reloader-types' +import { devIndicatorServerState } from 'next/dist/server/dev/dev-indicator-server-state' +import { createBinaryHmrMessageData } from 'next/dist/server/dev/messages' +import type { NextConfigComplete } from 'next/dist/server/config-shared' function isMiddlewareStats(stats: webpack.Stats) { for (const key of stats.compilation.entrypoints.keys()) { diff --git a/packages/next/src/server/dev/hot-reloader-rspack.ts b/packages/next/src/webpack/server/dev/hot-reloader-rspack.ts similarity index 96% rename from packages/next/src/server/dev/hot-reloader-rspack.ts rename to packages/next/src/webpack/server/dev/hot-reloader-rspack.ts index babe31e16a92..62d24c6228a0 100644 --- a/packages/next/src/server/dev/hot-reloader-rspack.ts +++ b/packages/next/src/webpack/server/dev/hot-reloader-rspack.ts @@ -2,11 +2,15 @@ import path from 'path' import fs from 'fs/promises' import { createHash } from 'crypto' import HotReloaderWebpack from './hot-reloader-webpack' -import { BUILT, EntryTypes, getEntries } from './on-demand-entry-handler' -import type { __ApiPreviewProps } from '../api-utils' -import type { RouteDefinition } from '../route-definitions/route-definition' +import { + BUILT, + EntryTypes, + getEntries, +} from 'next/dist/server/dev/on-demand-entry-handler' +import type { __ApiPreviewProps } from 'next/dist/server/api-utils' +import type { RouteDefinition } from 'next/dist/server/route-definitions/route-definition' import type { MultiCompiler } from 'webpack' -import { COMPILER_NAMES } from '../../shared/lib/constants' +import { COMPILER_NAMES } from 'next/dist/shared/lib/constants' /** * Rspack Persistent Cache Strategy for Next.js Development diff --git a/packages/next/src/server/dev/hot-reloader-webpack.ts b/packages/next/src/webpack/server/dev/hot-reloader-webpack.ts similarity index 94% rename from packages/next/src/server/dev/hot-reloader-webpack.ts rename to packages/next/src/webpack/server/dev/hot-reloader-webpack.ts index 063ebe195a89..f2a395fcf815 100644 --- a/packages/next/src/server/dev/hot-reloader-webpack.ts +++ b/packages/next/src/webpack/server/dev/hot-reloader-webpack.ts @@ -1,13 +1,16 @@ -import type { NextConfigComplete } from '../config-shared' -import type { CustomRoutes } from '../../lib/load-custom-routes' +import type { NextConfigComplete } from 'next/dist/server/config-shared' +import type { CustomRoutes } from 'next/dist/lib/load-custom-routes' import type { Duplex } from 'stream' -import type { Telemetry } from '../../telemetry/storage' +import type { Telemetry } from 'next/dist/telemetry/storage' import type { IncomingMessage, ServerResponse } from 'http' import type { UrlObject } from 'url' -import type { RouteDefinition } from '../route-definitions/route-definition' -import type { AnyStream } from '../app-render/stream-ops' +import type { RouteDefinition } from 'next/dist/server/route-definitions/route-definition' +import type { AnyStream } from 'next/dist/server/app-render/stream-ops' -import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack' +import { + type webpack, + StringXor, +} from 'next/dist/webpack/compiled/webpack/webpack' import { getOverlayMiddleware, getSourceMapMiddleware, @@ -25,16 +28,16 @@ import { runDependingOnPageType, getInstrumentationEntry, } from '../../build/entries' -import { createPagesMapping } from '../../build/route-discovery' -import { getStaticInfoIncludingLayouts } from '../../build/get-static-info-including-layouts' -import { watchCompilers } from '../../build/output' -import * as Log from '../../build/output/log' +import { createPagesMapping } from 'next/dist/build/route-discovery' +import { getStaticInfoIncludingLayouts } from 'next/dist/build/get-static-info-including-layouts' +import { watchCompilers } from 'next/dist/build/output' +import * as Log from 'next/dist/build/output/log' import getBaseWebpackConfig, { getCacheDirectories, loadProjectInfo, } from '../../build/webpack-config' -import { APP_DIR_ALIAS, WEBPACK_LAYERS } from '../../lib/constants' -import { recursiveDeleteSyncWithAsyncRetries } from '../../lib/recursive-delete' +import { APP_DIR_ALIAS, WEBPACK_LAYERS } from 'next/dist/lib/constants' +import { recursiveDeleteSyncWithAsyncRetries } from 'next/dist/lib/recursive-delete' import { BLOCKED_PAGES, CLIENT_STATIC_FILES_RUNTIME_MAIN, @@ -42,82 +45,82 @@ import { CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, COMPILER_NAMES, RSC_MODULE_TYPES, -} from '../../shared/lib/constants' -import type { __ApiPreviewProps } from '../api-utils' -import { findPageFile } from '../lib/find-page-file' +} from 'next/dist/shared/lib/constants' +import type { __ApiPreviewProps } from 'next/dist/server/api-utils' +import { findPageFile } from 'next/dist/server/lib/find-page-file' import { BUILDING, getEntries, EntryTypes, getInvalidator, onDemandEntryHandler, -} from './on-demand-entry-handler' -import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path' -import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' -import getRouteFromEntrypoint from '../get-route-from-entrypoint' +} from 'next/dist/server/dev/on-demand-entry-handler' +import { denormalizePagePath } from 'next/dist/shared/lib/page-path/denormalize-page-path' +import { normalizePathSep } from 'next/dist/shared/lib/page-path/normalize-path-sep' +import getRouteFromEntrypoint from 'next/dist/server/get-route-from-entrypoint' import { difference, isInstrumentationHookFile, isMiddlewareFile, isMiddlewareFilename, -} from '../../build/utils' -import { DecodeError } from '../../shared/lib/utils' -import { type Span, trace } from '../../trace' -import { getProperError } from '../../lib/is-error' +} from 'next/dist/build/utils' +import { DecodeError } from 'next/dist/shared/lib/utils' +import { type Span, trace } from 'next/dist/trace' +import { getProperError } from 'next/dist/lib/is-error' import ws from 'next/dist/compiled/ws' import { existsSync, promises as fs } from 'fs' -import type { UnwrapPromise } from '../../lib/coalesced-function' -import type { VersionInfo } from './parse-version-info' -import { isAPIRoute } from '../../lib/is-api-route' +import type { UnwrapPromise } from 'next/dist/lib/coalesced-function' +import type { VersionInfo } from 'next/dist/server/dev/parse-version-info' +import { isAPIRoute } from 'next/dist/lib/is-api-route' import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader' import { isInternalComponent, isNonRoutePagesPage, -} from '../../lib/is-internal-component' -import { RouteKind } from '../route-kind' +} from 'next/dist/lib/is-internal-component' +import { RouteKind } from 'next/dist/server/route-kind' import { HMR_MESSAGE_SENT_TO_BROWSER, type NextJsHotReloaderInterface, -} from './hot-reloader-types' -import type { HmrMessageSentToBrowser } from './hot-reloader-types' +} from 'next/dist/server/dev/hot-reloader-types' +import type { HmrMessageSentToBrowser } from 'next/dist/server/dev/hot-reloader-types' import type { WebpackError } from 'webpack' -import { PAGE_TYPES } from '../../lib/page-types' -import { FAST_REFRESH_RUNTIME_RELOAD } from './messages' -import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware' -import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware' -import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware' +import { PAGE_TYPES } from 'next/dist/lib/page-types' +import { FAST_REFRESH_RUNTIME_RELOAD } from 'next/dist/server/dev/messages' +import { getNextErrorFeedbackMiddleware } from 'next/dist/next-devtools/server/get-next-error-feedback-middleware' +import { getDevOverlayFontMiddleware } from 'next/dist/next-devtools/server/font/get-dev-overlay-font-middleware' +import { getDisableDevIndicatorMiddleware } from 'next/dist/next-devtools/server/dev-indicator-middleware' import getWebpackBundler from '../../shared/lib/get-webpack-bundler' -import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware' +import { getRestartDevServerMiddleware } from 'next/dist/next-devtools/server/restart-dev-server-middleware' import { checkFileSystemCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation' -import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs' +import { receiveBrowserLogsWebpack } from 'next/dist/server/dev/browser-logs/receive-logs' import { devToolsConfigMiddleware, getDevToolsConfig, -} from '../../next-devtools/server/devtools-config-middleware' -import { getAttachNodejsDebuggerMiddleware } from '../../next-devtools/server/attach-nodejs-debugger-middleware' -import { InvariantError } from '../../shared/lib/invariant-error' +} from 'next/dist/next-devtools/server/devtools-config-middleware' +import { getAttachNodejsDebuggerMiddleware } from 'next/dist/next-devtools/server/attach-nodejs-debugger-middleware' +import { InvariantError } from 'next/dist/shared/lib/invariant-error' import { connectReactDebugChannel, connectReactDebugChannelForHtmlRequest, deleteReactDebugChannelForHtmlRequest, setReactDebugChannelForHtmlRequest, type ReactDebugChannelForBrowser, -} from './debug-channel' +} from 'next/dist/server/dev/debug-channel' import { getVersionInfo, matchNextPageBundleRequest, -} from './hot-reloader-shared-utils' -import { getMcpMiddleware } from '../mcp/get-mcp-middleware' -import { setStackFrameResolver } from '../mcp/tools/utils/format-errors' -import { recordMcpTelemetry } from '../mcp/mcp-telemetry-tracker' -import { getFileLogger } from './browser-logs/file-logger' -import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator' -import type { Lockfile } from '../../build/lockfile' +} from 'next/dist/server/dev/hot-reloader-shared-utils' +import { getMcpMiddleware } from 'next/dist/server/mcp/get-mcp-middleware' +import { setStackFrameResolver } from 'next/dist/server/mcp/tools/utils/format-errors' +import { recordMcpTelemetry } from 'next/dist/server/mcp/mcp-telemetry-tracker' +import { getFileLogger } from 'next/dist/server/dev/browser-logs/file-logger' +import type { ServerCacheStatus } from 'next/dist/next-devtools/dev-overlay/cache-indicator' +import type { Lockfile } from 'next/dist/build/lockfile' import { sendSerializedErrorsToClient, sendSerializedErrorsToClientForHtmlRequest, setErrorsRscStreamForHtmlRequest, -} from './serialized-errors' +} from 'next/dist/server/dev/serialized-errors' const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000) diff --git a/packages/next/src/server/dev/middleware-webpack.ts b/packages/next/src/webpack/server/dev/middleware-webpack.ts similarity index 97% rename from packages/next/src/server/dev/middleware-webpack.ts rename to packages/next/src/webpack/server/dev/middleware-webpack.ts index 556cb652497d..5ce05fe861a5 100644 --- a/packages/next/src/server/dev/middleware-webpack.ts +++ b/packages/next/src/webpack/server/dev/middleware-webpack.ts @@ -2,15 +2,15 @@ import { findSourceMap, type SourceMap } from 'module' import path from 'path' import { fileURLToPath, pathToFileURL } from 'url' import { SourceMapConsumer } from 'next/dist/compiled/source-map08' -import { getSourceMapFromFile } from './get-source-map-from-file' +import { getSourceMapFromFile } from 'next/dist/server/dev/get-source-map-from-file' import { devirtualizeReactServerURL, findApplicableSourceMapPayload, sourceMapIgnoreListsEverything, type BasicSourceMapPayload, type ModernSourceMapPayload, -} from '../lib/source-maps' -import { openFileInEditor } from '../../next-devtools/server/launch-editor' +} from 'next/dist/server/lib/source-maps' +import { openFileInEditor } from 'next/dist/next-devtools/server/launch-editor' import { DEVTOOLS_CODE_FRAME_MAX_WIDTH, getOriginalCodeFrame, @@ -20,8 +20,8 @@ import { type OriginalStackFrameResponse, type OriginalStackFramesRequest, type OriginalStackFramesResponse, -} from '../../next-devtools/server/shared' -import { middlewareResponse } from '../../next-devtools/server/middleware-response' +} from 'next/dist/next-devtools/server/shared' +import { middlewareResponse } from 'next/dist/next-devtools/server/middleware-response' import type { IncomingMessage, ServerResponse } from 'http' import type webpack from 'webpack' @@ -29,7 +29,7 @@ import type { NullableMappedPosition, RawSourceMap, } from 'next/dist/compiled/source-map08' -import { formatStackFrameFile } from '../../next-devtools/shared/webpack-module-path' +import { formatStackFrameFile } from 'next/dist/next-devtools/shared/webpack-module-path' import type { MappedPosition } from 'source-map' import { inspect } from 'util' diff --git a/packages/next/src/shared/lib/get-webpack-bundler.ts b/packages/next/src/webpack/shared/lib/get-webpack-bundler.ts similarity index 68% rename from packages/next/src/shared/lib/get-webpack-bundler.ts rename to packages/next/src/webpack/shared/lib/get-webpack-bundler.ts index 3a9b0eb905ed..7f8f733dc940 100644 --- a/packages/next/src/shared/lib/get-webpack-bundler.ts +++ b/packages/next/src/webpack/shared/lib/get-webpack-bundler.ts @@ -1,5 +1,5 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' -import { getRspackCore } from './get-rspack' +import { webpack } from '../../compiled/webpack/webpack' +import { getRspackCore } from 'next/dist/shared/lib/get-rspack' /** * Depending on if Rspack is active or not, returns the appropriate set of diff --git a/packages/next/taskfile.js b/packages/next/taskfile.js index 738f6af47b88..206bc092513c 100644 --- a/packages/next/taskfile.js +++ b/packages/next/taskfile.js @@ -1,4 +1,4 @@ -const { relative, basename, resolve, join, dirname } = require('path') +const { relative, resolve, join, dirname } = require('path') const glob = require('glob') const fs = require('fs/promises') const resolveFrom = require('resolve-from') @@ -86,7 +86,7 @@ const externals = { 'jest-worker': 'jest-worker', 'terser-webpack-plugin': - 'next/dist/build/webpack/plugins/terser-webpack-plugin/src', + 'next/dist/webpack/build/webpack/plugins/terser-webpack-plugin/src', punycode: 'punycode/', // TODO: Add @swc/helpers to externals once @vercel/ncc switch to swc-loader @@ -2066,44 +2066,6 @@ export async function ncc_ua_parser_js(task, opts) { .ncc({ packageName: 'ua-parser-js', externals }) .target('src/compiled/ua-parser-js') } -export async function ncc_webpack_bundle5(task, opts) { - const bundleExternals = { - ...externals, - 'schema-utils': externals['schema-utils3'], - 'webpack-sources': externals['webpack-sources3'], - } - for (const pkg of Object.keys(webpackBundlePackages)) { - delete bundleExternals[pkg] - } - await task - .source('src/bundles/webpack/bundle5.js') - .ncc({ - packageName: 'webpack', - bundleName: 'webpack', - customEmit(path) { - if (path.endsWith('.runtime.js')) return `'./${basename(path)}'` - }, - externals: bundleExternals, - target: 'es5', - }) - .target('src/compiled/webpack') -} - -const webpackBundlePackages = { - webpack: 'next/dist/compiled/webpack/webpack-lib', - 'webpack/lib/NormalModule': 'next/dist/compiled/webpack/NormalModule', - 'webpack/lib/node/NodeTargetPlugin': - 'next/dist/compiled/webpack/NodeTargetPlugin', -} - -Object.assign(externals, webpackBundlePackages) - -export async function ncc_webpack_bundle_packages(task, opts) { - await task - .source('src/bundles/webpack/packages/*') - .target('src/compiled/webpack/') -} - externals['write-file-atomic'] = 'next/dist/compiled/write-file-atomic' export async function ncc_write_file_atomic(task, opts) { await task @@ -2314,7 +2276,6 @@ export async function ncc(task, opts) { 'ncc_watchpack', 'ncc_web_vitals', 'ncc_web_vitals_attribution', - 'ncc_webpack_bundle5', 'ncc_webpack_sources1', 'ncc_webpack_sources3', 'ncc_write_file_atomic', @@ -2328,7 +2289,6 @@ export async function ncc(task, opts) { ], opts ) - await task.parallel(['ncc_webpack_bundle_packages'], opts) await task.parallel(['ncc_babel_bundle_packages'], opts) await task.serial( [ @@ -2395,6 +2355,7 @@ export async function next_compile(task, opts) { ], opts ) + await task.start('webpack', opts) } export async function compile(task, opts) { @@ -2489,6 +2450,46 @@ export async function nextbuild_esm(task, opts) { .target('dist/esm/build') } +export async function webpack(task, opts) { + await rmrf(join(__dirname, 'dist/webpack')) + + await task + .source('src/webpack/**/!(*.test).+(js|ts|tsx)', { + ignore: [ + 'src/webpack/bundles/**', + 'src/webpack/compiled/**', + '**/*.test.+(js|ts|tsx)', + ], + }) + .swc('server', { dev: opts.dev }) + .target('dist/webpack') + + await fs.cp( + join(__dirname, 'src/webpack/compiled'), + join(__dirname, 'dist/webpack/compiled'), + { recursive: true, force: true } + ) + await fs.cp( + join(__dirname, 'src/webpack/bundles'), + join(__dirname, 'dist/webpack/bundles'), + { recursive: true, force: true } + ) + + for (const file of glob.sync('src/webpack/build/**/*', { + cwd: __dirname, + nodir: true, + ignore: ['**/*.+(js|ts|tsx)'], + })) { + const outputPath = join( + __dirname, + 'dist/webpack', + file.slice('src/webpack/'.length) + ) + await fs.mkdir(dirname(outputPath), { recursive: true }) + await fs.copyFile(join(__dirname, file), outputPath) + } +} + export async function nextbuildjest(task, opts) { await task .source('src/build/jest/**/*.+(js|ts|tsx)', { @@ -2752,6 +2753,7 @@ export default async function (task) { ['nextbuild', 'nextbuild_esm', 'nextbuildjest'], opts ) + await task.watch('src/webpack', 'webpack', opts) await task.watch( 'src/next-devtools', [ diff --git a/packages/next/tsconfig.build.json b/packages/next/tsconfig.build.json index 6afefe2f685b..472947331665 100644 --- a/packages/next/tsconfig.build.json +++ b/packages/next/tsconfig.build.json @@ -12,6 +12,7 @@ "compat/*.d.ts", "legacy/*.d.ts", "types/compiled.d.ts", + "src/webpack/**/*", "navigation-types/*.d.ts", "navigation-types/compat/*.d.ts", "experimental/**/*.d.ts", diff --git a/packages/next/tsconfig.json b/packages/next/tsconfig.json index 9a79d046fff5..2ba2ffe27466 100644 --- a/packages/next/tsconfig.json +++ b/packages/next/tsconfig.json @@ -25,6 +25,17 @@ "next/dist/compiled/@vercel/og/satori": [ "./src/compiled/@vercel/og/satori" ], + "next/dist/build/*": ["./src/build/*"], + "next/dist/client/*": ["./src/client/*"], + "next/dist/export/*": ["./src/export/*"], + "next/dist/lib/*": ["./src/lib/*"], + "next/dist/next-devtools/*": ["./src/next-devtools/*"], + "next/dist/server/*": ["./src/server/*"], + "next/dist/shared/*": ["./src/shared/*"], + "next/dist/telemetry/*": ["./src/telemetry/*"], + "next/dist/trace": ["./src/trace/index.ts"], + "next/dist/trace/*": ["./src/trace/*"], + "next/dist/types": ["./src/types.ts"], // TODO: Enable types by telling Turbopack to ignore this alias. // tsconfig#paths are for type locations not source locations. // "next/dist/compiled/next-devtools": [ @@ -43,6 +54,7 @@ "compat/*.d.ts", "legacy/*.d.ts", "types/compiled.d.ts", + "src/webpack/**/*", "navigation-types/*.d.ts", "navigation-types/compat/*.d.ts", "experimental/**/*.d.ts" diff --git a/packages/next/types/$$compiled.internal.d.ts b/packages/next/types/$$compiled.internal.d.ts index b23c852c3d5f..9a32de7e5ad0 100644 --- a/packages/next/types/$$compiled.internal.d.ts +++ b/packages/next/types/$$compiled.internal.d.ts @@ -965,7 +965,7 @@ declare module 'next/dist/compiled/webpack-sources3' { export let stringBufferUtils: StringBufferUtils } -declare module 'next/dist/compiled/webpack/webpack' { +declare module 'next/dist/webpack/compiled/webpack/webpack' { import { type Compilation, Module } from 'webpack' export function init(): void @@ -1092,3 +1092,31 @@ declare module 'next/dist/compiled/webpack/webpack' { export type CacheFacade = ReturnType } + +declare module 'next/dist/webpack/next-integration' { + export const webpackBuild: any + export const checkFileSystemCacheInvalidationAndCleanup: any + export const invalidateFileSystemCache: any + export function loadWebpackHook(): void + export const HotReloaderWebpack: any + export const HotReloaderRspack: any + export const getBaseWebpackConfig: any + export const getCacheDirectories: any + export const loadProjectInfo: any + export const attachReactRefresh: any + export const babelIncludeRegexes: any + export const hasExternalOtelApiPackage: any + export const nextImageLoaderRegex: any + export const NODE_RESOLVE_OPTIONS: any + export const NODE_BASE_RESOLVE_OPTIONS: any + export const NODE_ESM_RESOLVE_OPTIONS: any + export const NODE_BASE_ESM_RESOLVE_OPTIONS: any + export const JsConfigPathsPlugin: any +} + +declare module 'next/dist/webpack/server/dev/middleware-webpack' { + export const getOriginalStackFrames: any +} + +declare module 'next/dist/webpack/client/app-webpack' +declare module 'next/dist/webpack/client/webpack' diff --git a/packages/next/types/compiled.d.ts b/packages/next/types/compiled.d.ts index 3168fb5488ae..5c2ce98021ee 100644 --- a/packages/next/types/compiled.d.ts +++ b/packages/next/types/compiled.d.ts @@ -5,7 +5,7 @@ // TODO: Use tsconfig#paths instead declare module 'next/dist/compiled/next-devtools' -declare module 'next/dist/compiled/webpack/webpack' { +declare module 'next/dist/webpack/compiled/webpack/webpack' { export function init(): void export let BasicEvaluatedExpression: any export let GraphHelpers: any @@ -65,6 +65,34 @@ declare module 'next/dist/compiled/amphtml-validator' { export type ValidationError = any } +declare module 'next/dist/compiled/source-map08' { + export type NullableMappedPosition = any + export type RawSourceMap = any + export const SourceMapConsumer: any +} + +declare module 'next/dist/compiled/ws' { + class WebSocket {} + namespace WebSocket { + export class Server {} + } + export = WebSocket +} + +declare module 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' { + export class McpServer { + constructor(...args: any[]) + } +} + +declare module 'next/dist/compiled/edge-runtime' { + export class EdgeRuntime { + constructor(...args: any[]) + context: T + evaluate(code: string): any + } +} + declare module 'react-server-dom-webpack/server' declare module 'react-server-dom-webpack/static' diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6980f4d7568f..74711f84a77a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6383,9 +6383,6 @@ packages: '@types/estree@0.0.39': resolution: {integrity: sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==} - '@types/estree@1.0.6': - resolution: {integrity: sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==} - '@types/estree@1.0.7': resolution: {integrity: sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==} @@ -9620,10 +9617,6 @@ packages: endent@2.1.0: resolution: {integrity: sha512-r8VyPX7XL8U01Xgnb1CjZ3XV+z90cXIJ9JPE/R9SEC9vpw2P6CfsRPJmp20DppC5N7ZAMCmjYkJIa744Iyg96w==} - enhanced-resolve@5.17.1: - resolution: {integrity: sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==} - engines: {node: '>=10.13.0'} - enhanced-resolve@5.18.3: resolution: {integrity: sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==} engines: {node: '>=10.13.0'} @@ -23410,8 +23403,6 @@ snapshots: '@types/estree@0.0.39': {} - '@types/estree@1.0.6': {} - '@types/estree@1.0.7': {} '@types/events@3.0.0': {} @@ -27100,11 +27091,6 @@ snapshots: fast-json-parse: 1.0.3 objectorarray: 1.0.5 - enhanced-resolve@5.17.1: - dependencies: - graceful-fs: 4.2.11 - tapable: 2.2.1 - enhanced-resolve@5.18.3: dependencies: graceful-fs: 4.2.11 @@ -38054,14 +38040,14 @@ snapshots: webpack@5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.15)): dependencies: '@types/eslint-scope': 3.7.7 - '@types/estree': 1.0.6 + '@types/estree': 1.0.7 '@webassemblyjs/ast': 1.14.1 '@webassemblyjs/wasm-edit': 1.14.1 '@webassemblyjs/wasm-parser': 1.14.1 acorn: 8.14.0 browserslist: 4.28.1 chrome-trace-event: 1.0.2 - enhanced-resolve: 5.17.1 + enhanced-resolve: 5.18.3 es-module-lexer: 1.6.0 eslint-scope: 5.1.1 events: 3.3.0 @@ -38084,14 +38070,14 @@ snapshots: webpack@5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.15))(esbuild@0.25.9): dependencies: '@types/eslint-scope': 3.7.7 - '@types/estree': 1.0.6 + '@types/estree': 1.0.7 '@webassemblyjs/ast': 1.14.1 '@webassemblyjs/wasm-edit': 1.14.1 '@webassemblyjs/wasm-parser': 1.14.1 acorn: 8.14.0 browserslist: 4.28.1 chrome-trace-event: 1.0.2 - enhanced-resolve: 5.17.1 + enhanced-resolve: 5.18.3 es-module-lexer: 1.6.0 eslint-scope: 5.1.1 events: 3.3.0 diff --git a/scripts/check-pre-compiled.sh b/scripts/check-pre-compiled.sh index 3de250297ee8..629028ba4c7c 100755 --- a/scripts/check-pre-compiled.sh +++ b/scripts/check-pre-compiled.sh @@ -4,10 +4,10 @@ set -e cd packages/next -cp node_modules/webpack/lib/hmr/HotModuleReplacement.runtime.js src/bundles/webpack/packages/ -cp node_modules/webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js src/bundles/webpack/packages/ -cp node_modules/webpack/hot/lazy-compilation-node.js src/bundles/webpack/packages/ -cp node_modules/webpack/hot/lazy-compilation-web.js src/bundles/webpack/packages/ +cp node_modules/webpack/lib/hmr/HotModuleReplacement.runtime.js src/webpack/bundles/webpack/packages/ +cp node_modules/webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js src/webpack/bundles/webpack/packages/ +cp node_modules/webpack/hot/lazy-compilation-node.js src/webpack/bundles/webpack/packages/ +cp node_modules/webpack/hot/lazy-compilation-web.js src/webpack/bundles/webpack/packages/ pnpm run ncc-compiled diff --git a/scripts/pack-next.ts b/scripts/pack-next.ts index 21c478d26ca8..d61c3a5fab4a 100644 --- a/scripts/pack-next.ts +++ b/scripts/pack-next.ts @@ -180,7 +180,7 @@ async function main(): Promise { ` "@next/env": ${JSON.stringify(`file:${packageFiles.nextEnvFile}`)},` ) console.log( - ` "@next/bundle-analyzer": ${JSON.stringify(`file:${packageFiles.nextBaFile}`)}` + ` "@next/bundle-analyzer": ${JSON.stringify(`file:${packageFiles.nextBaFile}`)},` ) console.log(` }`) console.log(` }`) diff --git a/scripts/trace-next-server.js b/scripts/trace-next-server.js index 74ff122b7267..2c0c2a0c2d48 100644 --- a/scripts/trace-next-server.js +++ b/scripts/trace-next-server.js @@ -82,7 +82,7 @@ async function main() { 'node_modules/next/dist/pages/**/*', 'node_modules/next/dist/server/image-optimizer.js', 'node_modules/next/dist/compiled/@ampproject/toolbox-optimizer/**/*', - 'node_modules/next/dist/compiled/webpack/(bundle4|bundle5).js', + 'node_modules/next/dist/webpack/compiled/webpack/(bundle4|bundle5).js', 'node_modules/react/**/*.development.js', 'node_modules/react-dom/**/*.development.js', 'node_modules/use-subscription/**/*.development.js', diff --git a/test/development/sass-error/index.test.ts b/test/development/sass-error/index.test.ts index a2022ec6b840..5a2a8019e768 100644 --- a/test/development/sass-error/index.test.ts +++ b/test/development/sass-error/index.test.ts @@ -37,7 +37,7 @@ describe('app dir - css', () => { Pseudo-elements like '::before' or '::after' can't be followed by selectors like 'Ident("path")' - Generated code of PostCSS transform of loaders [next/dist/build/webpack/loaders/resolve-url-loader/index, next/dist/compiled/sass-loader] transform of file content of app/global.scss: + Generated code of PostCSS transform of loaders [next/dist/build/resolve-url-loader/index, next/dist/compiled/sass-loader] transform of file content of app/global.scss: ./app/global.scss.css:1:884 > 1 | ...ate(-50%, 0px)}input.defaultCheckbox::before path{fill:currentColor}input:checked.defaul... | ^ diff --git a/test/e2e/app-dir/scss/npm-import-bad/npm-import-bad.test.ts b/test/e2e/app-dir/scss/npm-import-bad/npm-import-bad.test.ts index df02f7c412d0..7605bb73d9d2 100644 --- a/test/e2e/app-dir/scss/npm-import-bad/npm-import-bad.test.ts +++ b/test/e2e/app-dir/scss/npm-import-bad/npm-import-bad.test.ts @@ -52,7 +52,7 @@ describe('CSS Import from node_modules', () => { `) } else if (isRspack) { expect(errorSource).toMatchInlineSnapshot(` - "./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[9].oneOf[14].use[1]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[9].oneOf[14].use[2]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/build/webpack/loaders/resolve-url-loader/index.js??ruleSet[1].rules[9].oneOf[14].use[3]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/compiled/sass-loader/cjs.js??ruleSet[1].rules[9].oneOf[14].use[4]!./styles/global.scss + "./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/webpack/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[9].oneOf[14].use[1]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/webpack/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[9].oneOf[14].use[2]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/build/resolve-url-loader/index.js??ruleSet[1].rules[9].oneOf[14].use[3]!./node_modules/.pnpm/next@file+..+next-repo-8fa5cfcca6029b56fbac0f566cc3851341e4c064ae33fb2a225547c1fab39f23+packa_apujtevk23v6mt6lxsvypt6azu/node_modules/next/dist/compiled/sass-loader/cjs.js??ruleSet[1].rules[9].oneOf[14].use[4]!./styles/global.scss ╰─▶ × Error: RspackResolver(NotFound("nprogress/nprogress.css"))" `) } else { diff --git a/test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts b/test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts index 40c1abccb13c..a0986174f920 100644 --- a/test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts +++ b/test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts @@ -44,7 +44,7 @@ describe('Edge runtime configurable guards', () => { }) // Webpack treats `node_modules` as a "managed path" in its snapshot - // config (see packages/next/src/build/webpack-config.ts), meaning it + // config (see packages/next/src/webpack/build/webpack-config.ts), meaning it // assumes the contents of any file under `node_modules` are immutable // per package version. When a test patches // `node_modules/lib/index.js`, webpack's dev server keeps serving the diff --git a/test/e2e/next-image-legacy/default/default-static.test.ts b/test/e2e/next-image-legacy/default/default-static.test.ts index 43c32e6393c4..d43871f7d76c 100644 --- a/test/e2e/next-image-legacy/default/default-static.test.ts +++ b/test/e2e/next-image-legacy/default/default-static.test.ts @@ -121,7 +121,7 @@ describe('Static Image Component Tests', () => { // In webpack dev, `next/legacy/image` emits a dynamic blur URL via the // image optimizer route instead of an inlined base64 data URL, to avoid // slowing down the dev server (see - // `packages/next/src/build/webpack/loaders/next-image-loader/blur.ts`). + // `packages/next/src/webpack/build/webpack/loaders/next-image-loader/blur.ts`). expect(replaceBlurUrl(style)).toMatchInlineSnapshot( `"position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;background-size:cover;background-position:0% 0%;filter:blur(20px);background-image:url("")"` ) @@ -143,7 +143,7 @@ describe('Static Image Component Tests', () => { // In webpack dev, `next/legacy/image` emits a dynamic blur URL via the // image optimizer route instead of an inlined base64 data URL, to avoid // slowing down the dev server (see - // `packages/next/src/build/webpack/loaders/next-image-loader/blur.ts`). + // `packages/next/src/webpack/build/webpack/loaders/next-image-loader/blur.ts`). expect(replaceBlurUrl(style)).toMatchInlineSnapshot( `"position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;background-size:cover;background-position:0% 0%;filter:blur(20px);background-image:url("")"` ) diff --git a/test/e2e/webpack-require-hook/next.config.js b/test/e2e/webpack-require-hook/next.config.js index 3cf986614d4e..3623064137a8 100644 --- a/test/e2e/webpack-require-hook/next.config.js +++ b/test/e2e/webpack-require-hook/next.config.js @@ -3,7 +3,7 @@ module.exports = { console.log('Initialized config') if ( require('webpack/lib/node/NodeTargetPlugin') !== - require('next/dist/compiled/webpack/NodeTargetPlugin') + require('next/dist/webpack/compiled/webpack/NodeTargetPlugin') ) throw new Error('Webpack require hook not applying') return config diff --git a/test/lib/add-redbox-matchers.ts b/test/lib/add-redbox-matchers.ts index 70de6a793e57..b18f6393c9c9 100644 --- a/test/lib/add-redbox-matchers.ts +++ b/test/lib/add-redbox-matchers.ts @@ -137,7 +137,7 @@ function focusSource( // This is the processed path the nextjs file from node_modules, // likely not being processed properly and it's not deterministic among tests. // e.g. it could be a encoded url of loader path: - // ../packages/next/dist/build/webpack/loaders/next-app-loader/index.js... + // ../packages/next/dist/webpack/build/webpack/loaders/next-app-loader/index.js... const sourceLines = focusedSource.split('\n') if ( sourceLines[0].startsWith('./node_modules/.pnpm/next@file+') || diff --git a/test/lib/next-test-utils.ts b/test/lib/next-test-utils.ts index 6d1112a0f08f..04da484da4da 100644 --- a/test/lib/next-test-utils.ts +++ b/test/lib/next-test-utils.ts @@ -38,7 +38,7 @@ import escapeRegex from 'escape-string-regexp' // Edge Runtime unit tests fail with "EvalError: Code generation from strings disallowed for this context" if these matchers are imported in those tests. import './add-redbox-matchers' import { NextInstance } from 'e2e-utils' -import { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin' +import { ClientReferenceManifest } from 'next/dist/build/manifests' export { shouldUseTurbopack } diff --git a/test/production/app-dir/actions-tree-shaking/_testing/utils.ts b/test/production/app-dir/actions-tree-shaking/_testing/utils.ts index fbb46c75f4b6..b9155d011ba5 100644 --- a/test/production/app-dir/actions-tree-shaking/_testing/utils.ts +++ b/test/production/app-dir/actions-tree-shaking/_testing/utils.ts @@ -1,6 +1,6 @@ import { nextTestSetup, type NextInstance } from 'e2e-utils' -// This is from 'next/dist/build/webpack/plugins/flight-client-entry-plugin', but unfortunately +// This is from 'next/dist/build/manifests', but unfortunately // Typescript breaks when importing it directly. type Actions = { [actionId: string]: { diff --git a/test/production/app-dir/route-handler-manifest-size/route-handler-manifest-size.test.ts b/test/production/app-dir/route-handler-manifest-size/route-handler-manifest-size.test.ts index 59b9abf0198c..6116382d6f79 100644 --- a/test/production/app-dir/route-handler-manifest-size/route-handler-manifest-size.test.ts +++ b/test/production/app-dir/route-handler-manifest-size/route-handler-manifest-size.test.ts @@ -1,6 +1,6 @@ import { nextTestSetup } from 'e2e-utils' import { getClientReferenceManifest } from 'next-test-utils' -import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin' +import type { ClientReferenceManifest } from 'next/dist/build/manifests' describe('route-handler-manifest-size', () => { const { next, isNextStart, skipped } = nextTestSetup({ diff --git a/test/production/pages-dir/production/test/index.test.ts b/test/production/pages-dir/production/test/index.test.ts index 2fc19d39b85b..94681eec7238 100644 --- a/test/production/pages-dir/production/test/index.test.ts +++ b/test/production/pages-dir/production/test/index.test.ts @@ -167,7 +167,7 @@ describe('Production Usage', () => { if (process.platform !== 'win32') { expect( serverTrace.files.some((file) => - file.includes('next/dist/compiled/webpack/bundle5.js') + file.includes('next/dist/webpack/compiled/webpack/bundle5.js') ) ).toBe(false) expect( diff --git a/test/unit/next-image-loader/get-blur-image.test.ts b/test/unit/next-image-loader/get-blur-image.test.ts index f958694a9338..c2248e575a66 100644 --- a/test/unit/next-image-loader/get-blur-image.test.ts +++ b/test/unit/next-image-loader/get-blur-image.test.ts @@ -1,5 +1,5 @@ /* eslint-env jest */ -import { getBlurImage } from 'next/dist/build/webpack/loaders/next-image-loader/blur' +import { getBlurImage } from 'next/dist/webpack/build/webpack/loaders/next-image-loader/blur' import { readFile } from 'fs-extra' import { join } from 'path' diff --git a/test/unit/webpack-config-overrides.test.ts b/test/unit/webpack-config-overrides.test.ts index e7a28f91780d..0f2e29d6c325 100644 --- a/test/unit/webpack-config-overrides.test.ts +++ b/test/unit/webpack-config-overrides.test.ts @@ -1,5 +1,5 @@ /* eslint-env jest */ -import { attachReactRefresh } from 'next/dist/build/webpack-config' +import { attachReactRefresh } from 'next/dist/webpack/next-integration' import * as storybookPlugin from '../../packages/next-plugin-storybook/preset' describe('next-plugin-storybook filterModuleRules', () => {