webpack-config.js 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = getBaseWebpackConfig;
  6. exports.getDefineEnv = getDefineEnv;
  7. exports.attachReactRefresh = attachReactRefresh;
  8. exports.resolveExternal = resolveExternal;
  9. exports.nextImageLoaderRegex = exports.NODE_BASE_ESM_RESOLVE_OPTIONS = exports.NODE_ESM_RESOLVE_OPTIONS = exports.NODE_BASE_RESOLVE_OPTIONS = exports.NODE_RESOLVE_OPTIONS = void 0;
  10. var _reactRefreshWebpackPlugin = _interopRequireDefault(require("next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin"));
  11. var _chalk = _interopRequireDefault(require("next/dist/compiled/chalk"));
  12. var _crypto = _interopRequireDefault(require("crypto"));
  13. var _webpack = require("next/dist/compiled/webpack/webpack");
  14. var _path = _interopRequireWildcard(require("path"));
  15. var _escapeRegexp = require("../shared/lib/escape-regexp");
  16. var _constants = require("../lib/constants");
  17. var _fileExists = require("../lib/file-exists");
  18. var _constants1 = require("../shared/lib/constants");
  19. var _utils = require("../shared/lib/utils");
  20. var _entries = require("./entries");
  21. var Log = _interopRequireWildcard(require("./output/log"));
  22. var _config = require("./webpack/config");
  23. var _middlewarePlugin = _interopRequireWildcard(require("./webpack/plugins/middleware-plugin"));
  24. var _buildManifestPlugin = _interopRequireDefault(require("./webpack/plugins/build-manifest-plugin"));
  25. var _jsconfigPathsPlugin = require("./webpack/plugins/jsconfig-paths-plugin");
  26. var _nextDropClientPagePlugin = require("./webpack/plugins/next-drop-client-page-plugin");
  27. var _pagesManifestPlugin = _interopRequireDefault(require("./webpack/plugins/pages-manifest-plugin"));
  28. var _profilingPlugin = require("./webpack/plugins/profiling-plugin");
  29. var _reactLoadablePlugin = require("./webpack/plugins/react-loadable-plugin");
  30. var _serverlessPlugin = require("./webpack/plugins/serverless-plugin");
  31. var _wellknownErrorsPlugin = require("./webpack/plugins/wellknown-errors-plugin");
  32. var _css = require("./webpack/config/blocks/css");
  33. var _copyFilePlugin = require("./webpack/plugins/copy-file-plugin");
  34. var _flightManifestPlugin = require("./webpack/plugins/flight-manifest-plugin");
  35. var _flightClientEntryPlugin = require("./webpack/plugins/flight-client-entry-plugin");
  36. var _browserslist = _interopRequireDefault(require("next/dist/compiled/browserslist"));
  37. var _loadJsconfig = _interopRequireDefault(require("./load-jsconfig"));
  38. var _swc = require("./swc");
  39. var _appBuildManifestPlugin = require("./webpack/plugins/app-build-manifest-plugin");
  40. var _subresourceIntegrityPlugin = require("./webpack/plugins/subresource-integrity-plugin");
  41. async function getBaseWebpackConfig(dir, { buildId , config , compilerType , dev =false , entrypoints , hasReactRoot , isDevFallback =false , pagesDir , reactProductionProfiling =false , rewrites , runWebpackSpan , target =_constants1.COMPILER_NAMES.server , appDir , middlewareMatchers }) {
  42. var ref44, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, // allows add JsConfigPathsPlugin to allow hot-reloading
  43. // if the config is added/removed
  44. ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref19, ref20, ref21, ref22;
  45. const isClient = compilerType === _constants1.COMPILER_NAMES.client;
  46. const isEdgeServer = compilerType === _constants1.COMPILER_NAMES.edgeServer;
  47. const isNodeServer = compilerType === _constants1.COMPILER_NAMES.server;
  48. const { jsConfig , resolvedBaseUrl } = await (0, _loadJsconfig).default(dir, config);
  49. const supportedBrowsers = await getSupportedBrowsers(dir, dev, config);
  50. const hasRewrites = rewrites.beforeFiles.length > 0 || rewrites.afterFiles.length > 0 || rewrites.fallback.length > 0;
  51. // Only error in first one compiler (client) once
  52. if (isClient) {
  53. if (!hasReactRoot) {
  54. if (config.experimental.runtime) {
  55. throw new Error("`experimental.runtime` requires React 18 to be installed.");
  56. }
  57. if (config.experimental.serverComponents) {
  58. throw new Error("`experimental.serverComponents` requires React 18 to be installed.");
  59. }
  60. }
  61. if (!config.experimental.appDir && config.experimental.serverComponents) {
  62. throw new Error("`experimental.serverComponents` requires experimental.appDir to be enabled.");
  63. }
  64. }
  65. const hasConcurrentFeatures = hasReactRoot;
  66. const hasServerComponents = hasConcurrentFeatures && !!config.experimental.serverComponents;
  67. const disableOptimizedLoading = hasConcurrentFeatures ? true : config.experimental.disableOptimizedLoading;
  68. if (isClient) {
  69. if (config.experimental.runtime === _constants.SERVER_RUNTIME.edge) {
  70. Log.warn("You are using the experimental Edge Runtime with `experimental.runtime`.");
  71. }
  72. if (config.experimental.runtime === "nodejs") {
  73. Log.warn("You are using the experimental Node.js Runtime with `experimental.runtime`.");
  74. }
  75. if (hasServerComponents) {
  76. Log.warn("You have experimental React Server Components enabled. Continue at your own risk.");
  77. }
  78. }
  79. const babelConfigFile = await [
  80. ".babelrc",
  81. ".babelrc.json",
  82. ".babelrc.js",
  83. ".babelrc.mjs",
  84. ".babelrc.cjs",
  85. "babel.config.js",
  86. "babel.config.json",
  87. "babel.config.mjs",
  88. "babel.config.cjs",
  89. ].reduce(async (memo, filename)=>{
  90. const configFilePath = _path.default.join(dir, filename);
  91. return await memo || (await (0, _fileExists).fileExists(configFilePath) ? configFilePath : undefined);
  92. }, Promise.resolve(undefined));
  93. const distDir = _path.default.join(dir, config.distDir);
  94. let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms;
  95. let SWCBinaryTarget = undefined;
  96. if (useSWCLoader) {
  97. var ref23, ref24;
  98. // TODO: we do not collect wasm target yet
  99. const binaryTarget = (ref23 = require("./swc")) == null ? void 0 : ref23.getBinaryMetadata == null ? void 0 : (ref24 = ref23.getBinaryMetadata()) == null ? void 0 : ref24.target;
  100. SWCBinaryTarget = binaryTarget ? [
  101. `swc/target/${binaryTarget}`,
  102. true
  103. ] : undefined;
  104. }
  105. if (!loggedSwcDisabled && !useSWCLoader && babelConfigFile) {
  106. Log.info(`Disabled SWC as replacement for Babel because of custom Babel configuration "${_path.default.relative(dir, babelConfigFile)}" https://nextjs.org/docs/messages/swc-disabled`);
  107. loggedSwcDisabled = true;
  108. }
  109. // eagerly load swc bindings instead of waiting for transform calls
  110. if (!babelConfigFile && isClient) {
  111. await (0, _swc).loadBindings();
  112. }
  113. if (!loggedIgnoredCompilerOptions && !useSWCLoader && config.compiler) {
  114. Log.info("`compiler` options in `next.config.js` will be ignored while using Babel https://nextjs.org/docs/messages/ignored-compiler-options");
  115. loggedIgnoredCompilerOptions = true;
  116. }
  117. const getBabelOrSwcLoader = ()=>{
  118. var ref;
  119. if (useSWCLoader && (config == null ? void 0 : (ref = config.experimental) == null ? void 0 : ref.swcTraceProfiling)) {
  120. var // This will init subscribers once only in a single process lifecycle,
  121. // even though it can be called multiple times.
  122. // Subscriber need to be initialized _before_ any actual swc's call (transform, etcs)
  123. // to collect correct trace spans when they are called.
  124. ref42;
  125. (ref42 = require("./swc")) == null ? void 0 : ref42.initCustomTraceSubscriber == null ? void 0 : ref42.initCustomTraceSubscriber(_path.default.join(distDir, `swc-trace-profile-${Date.now()}.json`));
  126. }
  127. var ref43;
  128. return useSWCLoader ? {
  129. loader: "next-swc-loader",
  130. options: {
  131. isServer: isNodeServer || isEdgeServer,
  132. pagesDir,
  133. hasReactRefresh: dev && isClient,
  134. fileReading: config.experimental.swcFileReading,
  135. nextConfig: config,
  136. jsConfig,
  137. supportedBrowsers: config.experimental.browsersListForSwc ? supportedBrowsers : undefined,
  138. swcCacheDir: _path.default.join(dir, (ref43 = config == null ? void 0 : config.distDir) != null ? ref43 : ".next", "cache", "swc")
  139. }
  140. } : {
  141. loader: require.resolve("./babel/loader/index"),
  142. options: {
  143. configFile: babelConfigFile,
  144. isServer: isNodeServer || isEdgeServer,
  145. distDir,
  146. pagesDir,
  147. cwd: dir,
  148. development: dev,
  149. hasReactRefresh: dev && isClient,
  150. hasJsxRuntime: true
  151. }
  152. };
  153. };
  154. const defaultLoaders = {
  155. babel: getBabelOrSwcLoader()
  156. };
  157. const pageExtensions = config.pageExtensions;
  158. const babelIncludeRegexes = [
  159. /next[\\/]dist[\\/]shared[\\/]lib/,
  160. /next[\\/]dist[\\/]client/,
  161. /next[\\/]dist[\\/]pages/,
  162. /[\\/](strip-ansi|ansi-regex)[\\/]/,
  163. /styled-jsx[\\/]/,
  164. ];
  165. // Support for NODE_PATH
  166. const nodePathList = (process.env.NODE_PATH || "").split(process.platform === "win32" ? ";" : ":").filter((p)=>!!p);
  167. // Intentionally not using isTargetLikeServerless helper
  168. const isLikeServerless = target === "serverless" || target === "experimental-serverless-trace";
  169. const outputPath = isNodeServer || isEdgeServer ? _path.default.join(distDir, isLikeServerless ? _constants1.SERVERLESS_DIRECTORY : _constants1.SERVER_DIRECTORY) : distDir;
  170. const clientEntries = isClient ? {
  171. // Backwards compatibility
  172. "main.js": [],
  173. ...dev ? {
  174. [_constants1.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: require.resolve(`next/dist/compiled/@next/react-refresh-utils/dist/runtime`),
  175. [_constants1.CLIENT_STATIC_FILES_RUNTIME_AMP]: `./` + (0, _path).relative(dir, (0, _path).join(NEXT_PROJECT_ROOT_DIST_CLIENT, "dev", "amp-dev")).replace(/\\/g, "/")
  176. } : {},
  177. [_constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN]: `./` + _path.default.relative(dir, _path.default.join(NEXT_PROJECT_ROOT_DIST_CLIENT, dev ? `next-dev.js` : "next.js")).replace(/\\/g, "/"),
  178. ...config.experimental.appDir ? {
  179. [_constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP]: dev ? [
  180. require.resolve(`next/dist/compiled/@next/react-refresh-utils/dist/runtime`),
  181. `./` + _path.default.relative(dir, _path.default.join(NEXT_PROJECT_ROOT_DIST_CLIENT, "app-next-dev.js")).replace(/\\/g, "/"),
  182. ] : `./` + _path.default.relative(dir, _path.default.join(NEXT_PROJECT_ROOT_DIST_CLIENT, "app-next.js")).replace(/\\/g, "/")
  183. } : {}
  184. } : undefined;
  185. function getReactProfilingInProduction() {
  186. if (reactProductionProfiling) {
  187. return {
  188. "react-dom$": "react-dom/profiling",
  189. "scheduler/tracing": "scheduler/tracing-profiling"
  190. };
  191. }
  192. }
  193. // tell webpack where to look for _app and _document
  194. // using aliases to allow falling back to the default
  195. // version when removed or not present
  196. const clientResolveRewrites = require.resolve("../shared/lib/router/utils/resolve-rewrites");
  197. const customAppAliases = {};
  198. const customErrorAlias = {};
  199. const customDocumentAliases = {};
  200. const customRootAliases = {};
  201. if (dev) {
  202. customAppAliases[`${_constants.PAGES_DIR_ALIAS}/_app`] = [
  203. ...pagesDir ? pageExtensions.reduce((prev, ext)=>{
  204. prev.push(_path.default.join(pagesDir, `_app.${ext}`));
  205. return prev;
  206. }, []) : [],
  207. "next/dist/pages/_app.js",
  208. ];
  209. customAppAliases[`${_constants.PAGES_DIR_ALIAS}/_error`] = [
  210. ...pagesDir ? pageExtensions.reduce((prev, ext)=>{
  211. prev.push(_path.default.join(pagesDir, `_error.${ext}`));
  212. return prev;
  213. }, []) : [],
  214. "next/dist/pages/_error.js",
  215. ];
  216. customDocumentAliases[`${_constants.PAGES_DIR_ALIAS}/_document`] = [
  217. ...pagesDir ? pageExtensions.reduce((prev, ext)=>{
  218. prev.push(_path.default.join(pagesDir, `_document.${ext}`));
  219. return prev;
  220. }, []) : [],
  221. `next/dist/pages/_document.js`,
  222. ];
  223. }
  224. const reactDir = (0, _path).dirname(require.resolve("react/package.json"));
  225. const reactDomDir = (0, _path).dirname(require.resolve("react-dom/package.json"));
  226. const mainFieldsPerCompiler = {
  227. [_constants1.COMPILER_NAMES.server]: [
  228. "main",
  229. "module"
  230. ],
  231. [_constants1.COMPILER_NAMES.client]: [
  232. "browser",
  233. "module",
  234. "main"
  235. ],
  236. [_constants1.COMPILER_NAMES.edgeServer]: [
  237. "browser",
  238. "module",
  239. "main"
  240. ]
  241. };
  242. const resolveConfig = {
  243. // Disable .mjs for node_modules bundling
  244. extensions: isNodeServer ? [
  245. ".js",
  246. ".mjs",
  247. ".tsx",
  248. ".ts",
  249. ".jsx",
  250. ".json",
  251. ".wasm"
  252. ] : [
  253. ".mjs",
  254. ".js",
  255. ".tsx",
  256. ".ts",
  257. ".jsx",
  258. ".json",
  259. ".wasm"
  260. ],
  261. modules: [
  262. "node_modules",
  263. ...nodePathList
  264. ],
  265. alias: {
  266. next: NEXT_PROJECT_ROOT,
  267. react: `${reactDir}`,
  268. "react-dom$": `${reactDomDir}`,
  269. "react-dom/server$": `${reactDomDir}/server`,
  270. "react-dom/server.browser$": `${reactDomDir}/server.browser`,
  271. "react-dom/client$": `${reactDomDir}/client`,
  272. "styled-jsx/style$": require.resolve(`styled-jsx/style`),
  273. "styled-jsx$": require.resolve(`styled-jsx`),
  274. ...customAppAliases,
  275. ...customErrorAlias,
  276. ...customDocumentAliases,
  277. ...customRootAliases,
  278. ...pagesDir ? {
  279. [_constants.PAGES_DIR_ALIAS]: pagesDir
  280. } : {},
  281. ...appDir ? {
  282. [_constants.APP_DIR_ALIAS]: appDir
  283. } : {},
  284. [_constants.ROOT_DIR_ALIAS]: dir,
  285. [_constants.DOT_NEXT_ALIAS]: distDir,
  286. ...isClient || isEdgeServer ? getOptimizedAliases() : {},
  287. ...getReactProfilingInProduction(),
  288. [_constants.RSC_MOD_REF_PROXY_ALIAS]: "next/dist/build/webpack/loaders/next-flight-loader/module-proxy",
  289. ...isClient || isEdgeServer ? {
  290. [clientResolveRewrites]: hasRewrites ? clientResolveRewrites : false
  291. } : {},
  292. "@swc/helpers": _path.default.dirname(require.resolve("@swc/helpers/package.json")),
  293. setimmediate: "next/dist/compiled/setimmediate"
  294. },
  295. ...isClient || isEdgeServer ? {
  296. fallback: {
  297. process: require.resolve("./polyfills/process")
  298. }
  299. } : undefined,
  300. mainFields: mainFieldsPerCompiler[compilerType],
  301. plugins: []
  302. };
  303. const terserOptions = {
  304. parse: {
  305. ecma: 8
  306. },
  307. compress: {
  308. ecma: 5,
  309. warnings: false,
  310. // The following two options are known to break valid JavaScript code
  311. comparisons: false,
  312. inline: 2
  313. },
  314. mangle: {
  315. safari10: true
  316. },
  317. output: {
  318. ecma: 5,
  319. safari10: true,
  320. comments: false,
  321. // Fixes usage of Emoji and certain Regex
  322. ascii_only: true
  323. }
  324. };
  325. const isModuleCSS = (module)=>{
  326. return(// mini-css-extract-plugin
  327. module.type === `css/mini-extract` || // extract-css-chunks-webpack-plugin (old)
  328. module.type === `css/extract-chunks` || // extract-css-chunks-webpack-plugin (new)
  329. module.type === `css/extract-css-chunks`);
  330. };
  331. // Packages which will be split into the 'framework' chunk.
  332. // Only top-level packages are included, e.g. nested copies like
  333. // 'node_modules/meow/node_modules/object-assign' are not included.
  334. const topLevelFrameworkPaths = [];
  335. const visitedFrameworkPackages = new Set();
  336. // Adds package-paths of dependencies recursively
  337. const addPackagePath = (packageName, relativeToPath)=>{
  338. try {
  339. if (visitedFrameworkPackages.has(packageName)) {
  340. return;
  341. }
  342. visitedFrameworkPackages.add(packageName);
  343. const packageJsonPath = require.resolve(`${packageName}/package.json`, {
  344. paths: [
  345. relativeToPath
  346. ]
  347. });
  348. // Include a trailing slash so that a `.startsWith(packagePath)` check avoids false positives
  349. // when one package name starts with the full name of a different package.
  350. // For example:
  351. // "node_modules/react-slider".startsWith("node_modules/react") // true
  352. // "node_modules/react-slider".startsWith("node_modules/react/") // false
  353. const directory = _path.default.join(packageJsonPath, "../");
  354. // Returning from the function in case the directory has already been added and traversed
  355. if (topLevelFrameworkPaths.includes(directory)) return;
  356. topLevelFrameworkPaths.push(directory);
  357. const dependencies = require(packageJsonPath).dependencies || {};
  358. for (const name of Object.keys(dependencies)){
  359. addPackagePath(name, directory);
  360. }
  361. } catch (_) {
  362. // don't error on failing to resolve framework packages
  363. }
  364. };
  365. for (const packageName1 of [
  366. "react",
  367. "react-dom"
  368. ]){
  369. addPackagePath(packageName1, dir);
  370. }
  371. const crossOrigin = config.crossOrigin;
  372. const looseEsmExternals = ((ref44 = config.experimental) == null ? void 0 : ref44.esmExternals) === "loose";
  373. async function handleExternals(context, request, dependencyType, getResolve) {
  374. // We need to externalize internal requests for files intended to
  375. // not be bundled.
  376. const isLocal = request.startsWith(".") || // Always check for unix-style path, as webpack sometimes
  377. // normalizes as posix.
  378. _path.default.posix.isAbsolute(request) || // When on Windows, we also want to check for Windows-specific
  379. // absolute paths.
  380. (process.platform === "win32" && _path.default.win32.isAbsolute(request));
  381. // make sure import "next" shows a warning when imported
  382. // in pages/components
  383. if (request === "next") {
  384. return `commonjs next/dist/lib/import-next-warning`;
  385. }
  386. // Relative requires don't need custom resolution, because they
  387. // are relative to requests we've already resolved here.
  388. // Absolute requires (require('/foo')) are extremely uncommon, but
  389. // also have no need for customization as they're already resolved.
  390. if (!isLocal) {
  391. // styled-jsx is also marked as externals here to avoid being
  392. // bundled in client components for RSC.
  393. if (/^(?:next$|styled-jsx$|react(?:$|\/))/.test(request)) {
  394. return `commonjs ${request}`;
  395. }
  396. const notExternalModules = /^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|future\/image|constants|dynamic|script)$)|string-hash|private-next-rsc-mod-ref-proxy$)/;
  397. if (notExternalModules.test(request)) {
  398. return;
  399. }
  400. }
  401. // @swc/helpers should not be external as it would
  402. // require hoisting the package which we can't rely on
  403. if (request.includes("@swc/helpers")) {
  404. return;
  405. }
  406. // When in esm externals mode, and using import, we resolve with
  407. // ESM resolving options.
  408. const isEsmRequested = dependencyType === "esm";
  409. const isLocalCallback = (localRes)=>{
  410. // Makes sure dist/shared and dist/server are not bundled
  411. // we need to process shared `router/router` and `dynamic`,
  412. // so that the DefinePlugin can inject process.env values
  413. const isNextExternal = /next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(localRes);
  414. if (isNextExternal) {
  415. // Generate Next.js external import
  416. const externalRequest = _path.default.posix.join("next", "dist", _path.default.relative(// Root of Next.js package:
  417. _path.default.join(__dirname, ".."), localRes)// Windows path normalization
  418. .replace(/\\/g, "/"));
  419. return `commonjs ${externalRequest}`;
  420. } else {
  421. // We don't want to retry local requests
  422. // with other preferEsm options
  423. return;
  424. }
  425. };
  426. const resolveResult = await resolveExternal(dir, config.experimental.esmExternals, context, request, isEsmRequested, getResolve, isLocal ? isLocalCallback : undefined);
  427. if ("localRes" in resolveResult) {
  428. return resolveResult.localRes;
  429. }
  430. // Forcedly resolve the styled-jsx installed by next.js,
  431. // since `resolveExternal` cannot find the styled-jsx dep with pnpm
  432. if (request === "styled-jsx/style") {
  433. resolveResult.res = require.resolve(request);
  434. }
  435. const { res , isEsm } = resolveResult;
  436. // If the request cannot be resolved we need to have
  437. // webpack "bundle" it so it surfaces the not found error.
  438. if (!res) {
  439. return;
  440. }
  441. // ESM externals can only be imported (and not required).
  442. // Make an exception in loose mode.
  443. if (!isEsmRequested && isEsm && !looseEsmExternals) {
  444. throw new Error(`ESM packages (${request}) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals`);
  445. }
  446. const externalType = isEsm ? "module" : "commonjs";
  447. if (res.match(/next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/) || res.match(/next[/\\]dist[/\\]compiled[/\\].*\.[mc]?js$/)) {
  448. return `${externalType} ${request}`;
  449. }
  450. // Default pages have to be transpiled
  451. if (res.match(/[/\\]next[/\\]dist[/\\]/) || // This is the @babel/plugin-transform-runtime "helpers: true" option
  452. res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/)) {
  453. return;
  454. }
  455. // Webpack itself has to be compiled because it doesn't always use module relative paths
  456. if (res.match(/node_modules[/\\]webpack/) || res.match(/node_modules[/\\]css-loader/)) {
  457. return;
  458. }
  459. // Anything else that is standard JavaScript within `node_modules`
  460. // can be externalized.
  461. if (/node_modules[/\\].*\.[mc]?js$/.test(res)) {
  462. return `${externalType} ${request}`;
  463. }
  464. // Default behavior: bundle the code!
  465. }
  466. const codeCondition = {
  467. test: /\.(tsx|ts|js|cjs|mjs|jsx)$/,
  468. ...config.experimental.externalDir ? {} : {
  469. include: [
  470. dir,
  471. ...babelIncludeRegexes
  472. ]
  473. },
  474. exclude: (excludePath)=>{
  475. if (babelIncludeRegexes.some((r)=>r.test(excludePath))) {
  476. return false;
  477. }
  478. return /node_modules/.test(excludePath);
  479. }
  480. };
  481. const rscSharedRegex = /(node_modules\/react\/|\/shared\/lib\/(head-manager-context|router-context|flush-effects)\.js|node_modules\/styled-jsx\/)/;
  482. let webpackConfig = {
  483. parallelism: Number(process.env.NEXT_WEBPACK_PARALLELISM) || undefined,
  484. // @ts-ignore
  485. externals: isClient || isEdgeServer ? // bundles in case a user imported types and it wasn't removed
  486. // TODO: should we warn/error for this instead?
  487. [
  488. "next",
  489. ...isEdgeServer ? [
  490. {
  491. "@builder.io/partytown": "{}",
  492. "next/dist/compiled/etag": "{}",
  493. "next/dist/compiled/chalk": "{}",
  494. "react-dom": "{}"
  495. },
  496. _middlewarePlugin.handleWebpackExtenalForEdgeRuntime,
  497. ] : [],
  498. ] : target !== "serverless" ? [
  499. ({ context , request , dependencyType , getResolve })=>{
  500. return handleExternals(context, request, dependencyType, (options)=>{
  501. const resolveFunction = getResolve(options);
  502. return (resolveContext, requestToResolve)=>{
  503. return new Promise((resolve, reject)=>{
  504. resolveFunction(resolveContext, requestToResolve, (err, result, resolveData)=>{
  505. var ref;
  506. if (err) return reject(err);
  507. if (!result) return resolve([
  508. null,
  509. false
  510. ]);
  511. const isEsm = /\.js$/i.test(result) ? (resolveData == null ? void 0 : (ref = resolveData.descriptionFileData) == null ? void 0 : ref.type) === "module" : /\.mjs$/i.test(result);
  512. resolve([
  513. result,
  514. isEsm
  515. ]);
  516. });
  517. });
  518. };
  519. });
  520. },
  521. ] : [
  522. // When the 'serverless' target is used all node_modules will be compiled into the output bundles
  523. // So that the 'serverless' bundles have 0 runtime dependencies
  524. "next/dist/compiled/@ampproject/toolbox-optimizer",
  525. // Mark this as external if not enabled so it doesn't cause a
  526. // webpack error from being missing
  527. ...config.experimental.optimizeCss ? [] : [
  528. "critters"
  529. ],
  530. ],
  531. optimization: {
  532. // @ts-ignore: TODO remove ts-ignore when webpack 4 is removed
  533. emitOnErrors: !dev,
  534. checkWasmTypes: false,
  535. nodeEnv: false,
  536. ...hasServerComponents ? {
  537. // We have to use the names here instead of hashes to ensure the consistency between compilers.
  538. moduleIds: isClient ? "deterministic" : "named"
  539. } : {},
  540. splitChunks: (()=>{
  541. // For the edge runtime, we have to bundle all dependencies inside without dynamic `require`s.
  542. // To make some dependencies like `react` to be shared between entrypoints, we use a special
  543. // cache group here even under dev mode.
  544. const edgeRSCCacheGroups = hasServerComponents ? {
  545. rscDeps: {
  546. enforce: true,
  547. name: "rsc-runtime-deps",
  548. filename: "rsc-runtime-deps.js",
  549. test: rscSharedRegex
  550. }
  551. } : undefined;
  552. if (isEdgeServer && edgeRSCCacheGroups) {
  553. return {
  554. cacheGroups: edgeRSCCacheGroups
  555. };
  556. }
  557. if (dev) {
  558. return false;
  559. }
  560. if (isNodeServer) {
  561. return {
  562. // @ts-ignore
  563. filename: "[name].js",
  564. chunks: "all",
  565. minSize: 1000
  566. };
  567. }
  568. if (isEdgeServer) {
  569. return {
  570. // @ts-ignore
  571. filename: "edge-chunks/[name].js",
  572. chunks: "all",
  573. minChunks: 2,
  574. cacheGroups: edgeRSCCacheGroups
  575. };
  576. }
  577. return {
  578. // Keep main and _app chunks unsplitted in webpack 5
  579. // as we don't need a separate vendor chunk from that
  580. // and all other chunk depend on them so there is no
  581. // duplication that need to be pulled out.
  582. chunks: (chunk)=>!/^(polyfills|main|pages\/_app)$/.test(chunk.name),
  583. cacheGroups: {
  584. framework: {
  585. chunks: "all",
  586. name: "framework",
  587. test (module) {
  588. const resource = module.nameForCondition == null ? void 0 : module.nameForCondition();
  589. return resource ? topLevelFrameworkPaths.some((pkgPath)=>resource.startsWith(pkgPath)) : false;
  590. },
  591. priority: 40,
  592. // Don't let webpack eliminate this chunk (prevents this chunk from
  593. // becoming a part of the commons chunk)
  594. enforce: true
  595. },
  596. lib: {
  597. test (module) {
  598. return module.size() > 160000 && /node_modules[/\\]/.test(module.nameForCondition() || "");
  599. },
  600. name (module) {
  601. const hash = _crypto.default.createHash("sha1");
  602. if (isModuleCSS(module)) {
  603. module.updateHash(hash);
  604. } else {
  605. if (!module.libIdent) {
  606. throw new Error(`Encountered unknown module type: ${module.type}. Please open an issue.`);
  607. }
  608. hash.update(module.libIdent({
  609. context: dir
  610. }));
  611. }
  612. return hash.digest("hex").substring(0, 8);
  613. },
  614. priority: 30,
  615. minChunks: 1,
  616. reuseExistingChunk: true
  617. }
  618. },
  619. maxInitialRequests: 25,
  620. minSize: 20000
  621. };
  622. })(),
  623. runtimeChunk: isClient ? {
  624. name: _constants1.CLIENT_STATIC_FILES_RUNTIME_WEBPACK
  625. } : undefined,
  626. minimize: !dev && isClient,
  627. minimizer: [
  628. // Minify JavaScript
  629. (compiler)=>{
  630. var ref, ref45;
  631. // @ts-ignore No typings yet
  632. const { TerserPlugin , } = require("./webpack/plugins/terser-webpack-plugin/src/index.js");
  633. var ref46, ref47;
  634. new TerserPlugin({
  635. cacheDir: _path.default.join(distDir, "cache", "next-minifier"),
  636. parallel: config.experimental.cpus,
  637. swcMinify: config.swcMinify,
  638. terserOptions: {
  639. ...terserOptions,
  640. compress: {
  641. ...terserOptions.compress,
  642. ...(ref46 = (ref = config.experimental.swcMinifyDebugOptions) == null ? void 0 : ref.compress) != null ? ref46 : {}
  643. },
  644. mangle: {
  645. ...terserOptions.mangle,
  646. ...(ref47 = (ref45 = config.experimental.swcMinifyDebugOptions) == null ? void 0 : ref45.mangle) != null ? ref47 : {}
  647. }
  648. }
  649. }).apply(compiler);
  650. },
  651. // Minify CSS
  652. (compiler)=>{
  653. const { CssMinimizerPlugin , } = require("./webpack/plugins/css-minimizer-plugin");
  654. new CssMinimizerPlugin({
  655. postcssOptions: {
  656. map: {
  657. // `inline: false` generates the source map in a separate file.
  658. // Otherwise, the CSS file is needlessly large.
  659. inline: false,
  660. // `annotation: false` skips appending the `sourceMappingURL`
  661. // to the end of the CSS file. Webpack already handles this.
  662. annotation: false
  663. }
  664. }
  665. }).apply(compiler);
  666. },
  667. ]
  668. },
  669. context: dir,
  670. // Kept as function to be backwards compatible
  671. // @ts-ignore TODO webpack 5 typings needed
  672. entry: async ()=>{
  673. return {
  674. ...clientEntries ? clientEntries : {},
  675. ...entrypoints
  676. };
  677. },
  678. watchOptions,
  679. output: {
  680. // we must set publicPath to an empty value to override the default of
  681. // auto which doesn't work in IE11
  682. publicPath: `${config.assetPrefix || ""}/_next/`,
  683. path: !dev && isNodeServer ? _path.default.join(outputPath, "chunks") : outputPath,
  684. // On the server we don't use hashes
  685. filename: isNodeServer || isEdgeServer ? dev || isEdgeServer ? `[name].js` : `../[name].js` : `static/chunks/${isDevFallback ? "fallback/" : ""}[name]${dev ? "" : appDir ? "-[chunkhash]" : "-[contenthash]"}.js`,
  686. library: isClient || isEdgeServer ? "_N_E" : undefined,
  687. libraryTarget: isClient || isEdgeServer ? "assign" : "commonjs2",
  688. hotUpdateChunkFilename: "static/webpack/[id].[fullhash].hot-update.js",
  689. hotUpdateMainFilename: "static/webpack/[fullhash].[runtime].hot-update.json",
  690. // This saves chunks with the name given via `import()`
  691. chunkFilename: isNodeServer || isEdgeServer ? "[name].js" : `static/chunks/${isDevFallback ? "fallback/" : ""}${dev ? "[name]" : "[name].[contenthash]"}.js`,
  692. strictModuleExceptionHandling: true,
  693. crossOriginLoading: crossOrigin,
  694. webassemblyModuleFilename: "static/wasm/[modulehash].wasm",
  695. hashFunction: "xxhash64",
  696. hashDigestLength: 16
  697. },
  698. performance: false,
  699. resolve: resolveConfig,
  700. resolveLoader: {
  701. // The loaders Next.js provides
  702. alias: [
  703. "error-loader",
  704. "next-swc-loader",
  705. "next-client-pages-loader",
  706. "next-image-loader",
  707. "next-serverless-loader",
  708. "next-style-loader",
  709. "next-flight-loader",
  710. "next-flight-client-entry-loader",
  711. "noop-loader",
  712. "next-middleware-loader",
  713. "next-edge-function-loader",
  714. "next-edge-ssr-loader",
  715. "next-middleware-asset-loader",
  716. "next-middleware-wasm-loader",
  717. "next-app-loader",
  718. ].reduce((alias, loader)=>{
  719. // using multiple aliases to replace `resolveLoader.modules`
  720. alias[loader] = _path.default.join(__dirname, "webpack", "loaders", loader);
  721. return alias;
  722. }, {}),
  723. modules: [
  724. "node_modules",
  725. ...nodePathList
  726. ],
  727. plugins: []
  728. },
  729. module: {
  730. rules: [
  731. // TODO: FIXME: do NOT webpack 5 support with this
  732. // x-ref: https://github.com/webpack/webpack/issues/11467
  733. ...!config.experimental.fullySpecified ? [
  734. {
  735. test: /\.m?js/,
  736. resolve: {
  737. fullySpecified: false
  738. }
  739. },
  740. ] : [],
  741. ...hasServerComponents && (isNodeServer || isEdgeServer) ? [
  742. // RSC server compilation loaders
  743. {
  744. test: codeCondition.test,
  745. include: [
  746. dir,
  747. // To let the internal client components passing through flight loader
  748. /next[\\/]dist/,
  749. ],
  750. issuerLayer: _constants.WEBPACK_LAYERS.server,
  751. use: {
  752. loader: "next-flight-loader"
  753. }
  754. },
  755. ] : [],
  756. ...hasServerComponents && isEdgeServer ? [
  757. // Move shared dependencies from sc_server and sc_client into the
  758. // same layer.
  759. {
  760. test: rscSharedRegex,
  761. layer: _constants.WEBPACK_LAYERS.rscShared
  762. },
  763. ] : [],
  764. {
  765. test: /\.(js|cjs|mjs)$/,
  766. issuerLayer: _constants.WEBPACK_LAYERS.api,
  767. parser: {
  768. // Switch back to normal URL handling
  769. url: true
  770. }
  771. },
  772. {
  773. oneOf: [
  774. {
  775. ...codeCondition,
  776. issuerLayer: _constants.WEBPACK_LAYERS.api,
  777. parser: {
  778. // Switch back to normal URL handling
  779. url: true
  780. },
  781. use: defaultLoaders.babel
  782. },
  783. {
  784. ...codeCondition,
  785. issuerLayer: _constants.WEBPACK_LAYERS.middleware,
  786. use: getBabelOrSwcLoader()
  787. },
  788. ...hasServerComponents ? [
  789. {
  790. test: codeCondition.test,
  791. issuerLayer: _constants.WEBPACK_LAYERS.server,
  792. use: {
  793. ...defaultLoaders.babel,
  794. options: {
  795. ...defaultLoaders.babel.options,
  796. isServerLayer: true
  797. }
  798. }
  799. },
  800. ] : [],
  801. {
  802. ...codeCondition,
  803. use: dev && isClient ? [
  804. require.resolve("next/dist/compiled/@next/react-refresh-utils/dist/loader"),
  805. defaultLoaders.babel,
  806. ] : defaultLoaders.babel
  807. },
  808. ]
  809. },
  810. ...!config.images.disableStaticImages ? [
  811. {
  812. test: nextImageLoaderRegex,
  813. loader: "next-image-loader",
  814. issuer: {
  815. not: _css.regexLikeCss
  816. },
  817. dependency: {
  818. not: [
  819. "url"
  820. ]
  821. },
  822. options: {
  823. isServer: isNodeServer || isEdgeServer,
  824. isDev: dev,
  825. basePath: config.basePath,
  826. assetPrefix: config.assetPrefix
  827. }
  828. },
  829. ] : [],
  830. ...isEdgeServer || isClient ? [
  831. {
  832. oneOf: [
  833. {
  834. issuerLayer: _constants.WEBPACK_LAYERS.middleware,
  835. resolve: {
  836. fallback: {
  837. process: require.resolve("./polyfills/process")
  838. }
  839. }
  840. },
  841. {
  842. resolve: {
  843. fallback: config.experimental.fallbackNodePolyfills === false ? {
  844. assert: false,
  845. buffer: false,
  846. constants: false,
  847. crypto: false,
  848. domain: false,
  849. http: false,
  850. https: false,
  851. os: false,
  852. path: false,
  853. punycode: false,
  854. process: false,
  855. querystring: false,
  856. stream: false,
  857. string_decoder: false,
  858. sys: false,
  859. timers: false,
  860. tty: false,
  861. util: false,
  862. vm: false,
  863. zlib: false,
  864. events: false,
  865. setImmediate: false
  866. } : {
  867. assert: require.resolve("next/dist/compiled/assert"),
  868. buffer: require.resolve("next/dist/compiled/buffer/"),
  869. constants: require.resolve("next/dist/compiled/constants-browserify"),
  870. crypto: require.resolve("next/dist/compiled/crypto-browserify"),
  871. domain: require.resolve("next/dist/compiled/domain-browser"),
  872. http: require.resolve("next/dist/compiled/stream-http"),
  873. https: require.resolve("next/dist/compiled/https-browserify"),
  874. os: require.resolve("next/dist/compiled/os-browserify"),
  875. path: require.resolve("next/dist/compiled/path-browserify"),
  876. punycode: require.resolve("next/dist/compiled/punycode"),
  877. process: require.resolve("./polyfills/process"),
  878. // Handled in separate alias
  879. querystring: require.resolve("next/dist/compiled/querystring-es3"),
  880. stream: require.resolve("next/dist/compiled/stream-browserify"),
  881. string_decoder: require.resolve("next/dist/compiled/string_decoder"),
  882. sys: require.resolve("next/dist/compiled/util/"),
  883. timers: require.resolve("next/dist/compiled/timers-browserify"),
  884. tty: require.resolve("next/dist/compiled/tty-browserify"),
  885. // Handled in separate alias
  886. // url: require.resolve('url/'),
  887. util: require.resolve("next/dist/compiled/util/"),
  888. vm: require.resolve("next/dist/compiled/vm-browserify"),
  889. zlib: require.resolve("next/dist/compiled/browserify-zlib"),
  890. events: require.resolve("next/dist/compiled/events/"),
  891. setImmediate: require.resolve("next/dist/compiled/setimmediate")
  892. }
  893. }
  894. },
  895. ]
  896. },
  897. ] : [],
  898. ].filter(Boolean)
  899. },
  900. plugins: [
  901. dev && isClient && new _reactRefreshWebpackPlugin.default(_webpack.webpack),
  902. // Makes sure `Buffer` and `process` are polyfilled in client and flight bundles (same behavior as webpack 4)
  903. (isClient || isEdgeServer) && new _webpack.webpack.ProvidePlugin({
  904. // Buffer is used by getInlineScriptSource
  905. Buffer: [
  906. require.resolve("buffer"),
  907. "Buffer"
  908. ],
  909. // Avoid process being overridden when in web run time
  910. ...isClient && {
  911. process: [
  912. require.resolve("process")
  913. ]
  914. }
  915. }),
  916. new _webpack.webpack.DefinePlugin(getDefineEnv({
  917. dev,
  918. config,
  919. distDir,
  920. isClient,
  921. hasRewrites,
  922. hasReactRoot,
  923. isNodeServer,
  924. isEdgeServer,
  925. middlewareMatchers
  926. })),
  927. isClient && new _reactLoadablePlugin.ReactLoadablePlugin({
  928. filename: _constants1.REACT_LOADABLE_MANIFEST,
  929. pagesDir,
  930. runtimeAsset: hasConcurrentFeatures ? `server/${_constants1.MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js` : undefined,
  931. dev
  932. }),
  933. (isClient || isEdgeServer) && new _nextDropClientPagePlugin.DropClientPage(),
  934. config.outputFileTracing && !isLikeServerless && (isNodeServer || isEdgeServer) && !dev && new (require("./webpack/plugins/next-trace-entrypoints-plugin")).TraceEntryPointsPlugin({
  935. appDir: dir,
  936. esmExternals: config.experimental.esmExternals,
  937. staticImageImports: !config.images.disableStaticImages,
  938. outputFileTracingRoot: config.experimental.outputFileTracingRoot
  939. }),
  940. // Moment.js is an extremely popular library that bundles large locale files
  941. // by default due to how Webpack interprets its code. This is a practical
  942. // solution that requires the user to opt into importing specific locales.
  943. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  944. config.excludeDefaultMomentLocales && new _webpack.webpack.IgnorePlugin({
  945. resourceRegExp: /^\.\/locale$/,
  946. contextRegExp: /moment$/
  947. }),
  948. ...dev ? (()=>{
  949. // Even though require.cache is server only we have to clear assets from both compilations
  950. // This is because the client compilation generates the build manifest that's used on the server side
  951. const { NextJsRequireCacheHotReloader , } = require("./webpack/plugins/nextjs-require-cache-hot-reloader");
  952. const devPlugins = [
  953. new NextJsRequireCacheHotReloader({
  954. hasServerComponents: config.experimental.serverComponents
  955. }),
  956. ];
  957. if (isClient || isEdgeServer) {
  958. devPlugins.push(new _webpack.webpack.HotModuleReplacementPlugin());
  959. }
  960. return devPlugins;
  961. })() : [],
  962. !dev && new _webpack.webpack.IgnorePlugin({
  963. resourceRegExp: /react-is/,
  964. contextRegExp: /next[\\/]dist[\\/]/
  965. }),
  966. target === "serverless" && (isNodeServer || isEdgeServer) && new _serverlessPlugin.ServerlessPlugin(),
  967. (isNodeServer || isEdgeServer) && new _pagesManifestPlugin.default({
  968. serverless: isLikeServerless,
  969. dev,
  970. isEdgeRuntime: isEdgeServer,
  971. appDirEnabled: !!config.experimental.appDir
  972. }),
  973. // MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
  974. // replacement is done before its process.env.* handling
  975. isEdgeServer && new _middlewarePlugin.default({
  976. dev,
  977. sriEnabled: !dev && !!((ref1 = config.experimental.sri) == null ? void 0 : ref1.algorithm),
  978. allowMiddlewareResponseBody: !!config.experimental.allowMiddlewareResponseBody
  979. }),
  980. isClient && new _buildManifestPlugin.default({
  981. buildId,
  982. rewrites,
  983. isDevFallback,
  984. exportRuntime: hasConcurrentFeatures,
  985. appDirEnabled: !!config.experimental.appDir
  986. }),
  987. new _profilingPlugin.ProfilingPlugin({
  988. runWebpackSpan
  989. }),
  990. config.optimizeFonts && !dev && isNodeServer && function() {
  991. const { FontStylesheetGatheringPlugin } = require("./webpack/plugins/font-stylesheet-gathering-plugin");
  992. return new FontStylesheetGatheringPlugin({
  993. isLikeServerless,
  994. adjustFontFallbacks: config.experimental.adjustFontFallbacks
  995. });
  996. }(),
  997. new _wellknownErrorsPlugin.WellKnownErrorsPlugin(),
  998. isClient && new _copyFilePlugin.CopyFilePlugin({
  999. filePath: require.resolve("./polyfills/polyfill-nomodule"),
  1000. cacheKey: "12.3.4",
  1001. name: `static/chunks/polyfills${dev ? "" : "-[hash]"}.js`,
  1002. minimize: false,
  1003. info: {
  1004. [_constants1.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL]: 1,
  1005. // This file is already minified
  1006. minimized: true
  1007. }
  1008. }),
  1009. !!config.experimental.appDir && hasServerComponents && isClient && new _appBuildManifestPlugin.AppBuildManifestPlugin({
  1010. dev
  1011. }),
  1012. hasServerComponents && !!config.experimental.appDir && (isClient ? new _flightManifestPlugin.FlightManifestPlugin({
  1013. dev
  1014. }) : new _flightClientEntryPlugin.FlightClientEntryPlugin({
  1015. dev,
  1016. isEdgeServer
  1017. })),
  1018. !dev && isClient && !!((ref2 = config.experimental.sri) == null ? void 0 : ref2.algorithm) && new _subresourceIntegrityPlugin.SubresourceIntegrityPlugin(config.experimental.sri.algorithm),
  1019. !dev && isClient && new (require("./webpack/plugins/telemetry-plugin")).TelemetryPlugin(new Map([
  1020. [
  1021. "swcLoader",
  1022. useSWCLoader
  1023. ],
  1024. [
  1025. "swcMinify",
  1026. config.swcMinify
  1027. ],
  1028. [
  1029. "swcRelay",
  1030. !!((ref3 = config.compiler) == null ? void 0 : ref3.relay)
  1031. ],
  1032. [
  1033. "swcStyledComponents",
  1034. !!((ref4 = config.compiler) == null ? void 0 : ref4.styledComponents)
  1035. ],
  1036. [
  1037. "swcReactRemoveProperties",
  1038. !!((ref5 = config.compiler) == null ? void 0 : ref5.reactRemoveProperties),
  1039. ],
  1040. [
  1041. "swcExperimentalDecorators",
  1042. !!(jsConfig == null ? void 0 : (ref6 = jsConfig.compilerOptions) == null ? void 0 : ref6.experimentalDecorators),
  1043. ],
  1044. [
  1045. "swcRemoveConsole",
  1046. !!((ref7 = config.compiler) == null ? void 0 : ref7.removeConsole)
  1047. ],
  1048. [
  1049. "swcImportSource",
  1050. !!(jsConfig == null ? void 0 : (ref8 = jsConfig.compilerOptions) == null ? void 0 : ref8.jsxImportSource)
  1051. ],
  1052. [
  1053. "swcEmotion",
  1054. !!((ref9 = config.compiler) == null ? void 0 : ref9.emotion)
  1055. ],
  1056. SWCBinaryTarget,
  1057. ].filter(Boolean))),
  1058. ].filter(Boolean)
  1059. };
  1060. // Support tsconfig and jsconfig baseUrl
  1061. if (resolvedBaseUrl) {
  1062. var ref25, ref26;
  1063. (ref25 = webpackConfig.resolve) == null ? void 0 : (ref26 = ref25.modules) == null ? void 0 : ref26.push(resolvedBaseUrl);
  1064. }
  1065. (ref10 = webpackConfig.resolve) == null ? void 0 : (ref11 = ref10.plugins) == null ? void 0 : ref11.unshift(new _jsconfigPathsPlugin.JsConfigPathsPlugin((jsConfig == null ? void 0 : (ref12 = jsConfig.compilerOptions) == null ? void 0 : ref12.paths) || {}, resolvedBaseUrl || dir));
  1066. const webpack5Config = webpackConfig;
  1067. if (isEdgeServer) {
  1068. var ref27, ref28, ref29, ref30, ref31, ref32;
  1069. (ref27 = webpack5Config.module) == null ? void 0 : (ref28 = ref27.rules) == null ? void 0 : ref28.unshift({
  1070. test: /\.wasm$/,
  1071. loader: "next-middleware-wasm-loader",
  1072. type: "javascript/auto",
  1073. resourceQuery: /module/i
  1074. });
  1075. (ref29 = webpack5Config.module) == null ? void 0 : (ref30 = ref29.rules) == null ? void 0 : ref30.unshift({
  1076. dependency: "url",
  1077. loader: "next-middleware-asset-loader",
  1078. type: "javascript/auto",
  1079. layer: _constants.WEBPACK_LAYERS.edgeAsset
  1080. });
  1081. (ref31 = webpack5Config.module) == null ? void 0 : (ref32 = ref31.rules) == null ? void 0 : ref32.unshift({
  1082. issuerLayer: _constants.WEBPACK_LAYERS.edgeAsset,
  1083. type: "asset/source"
  1084. });
  1085. }
  1086. webpack5Config.experiments = {
  1087. layers: true,
  1088. cacheUnaffected: true,
  1089. buildHttp: Array.isArray(config.experimental.urlImports) ? {
  1090. allowedUris: config.experimental.urlImports,
  1091. cacheLocation: _path.default.join(dir, "next.lock/data"),
  1092. lockfileLocation: _path.default.join(dir, "next.lock/lock.json")
  1093. } : config.experimental.urlImports ? {
  1094. cacheLocation: _path.default.join(dir, "next.lock/data"),
  1095. lockfileLocation: _path.default.join(dir, "next.lock/lock.json"),
  1096. ...config.experimental.urlImports
  1097. } : undefined
  1098. };
  1099. webpack5Config.module.parser = {
  1100. javascript: {
  1101. url: "relative"
  1102. }
  1103. };
  1104. webpack5Config.module.generator = {
  1105. asset: {
  1106. filename: "static/media/[name].[hash:8][ext]"
  1107. }
  1108. };
  1109. if (!webpack5Config.output) {
  1110. webpack5Config.output = {};
  1111. }
  1112. if (isClient) {
  1113. webpack5Config.output.trustedTypes = "nextjs#bundler";
  1114. }
  1115. if (isClient || isEdgeServer) {
  1116. webpack5Config.output.enabledLibraryTypes = [
  1117. "assign"
  1118. ];
  1119. }
  1120. if (dev) {
  1121. // @ts-ignore unsafeCache exists
  1122. webpack5Config.module.unsafeCache = (module)=>!/[\\/]pages[\\/][^\\/]+(?:$|\?|#)/.test(module.resource);
  1123. }
  1124. // This enables managedPaths for all node_modules
  1125. // and also for the unplugged folder when using yarn pnp
  1126. // It also add the yarn cache to the immutable paths
  1127. webpack5Config.snapshot = {};
  1128. if (process.versions.pnp === "3") {
  1129. webpack5Config.snapshot.managedPaths = [
  1130. /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/,
  1131. ];
  1132. } else {
  1133. webpack5Config.snapshot.managedPaths = [
  1134. /^(.+?[\\/]node_modules[\\/])/
  1135. ];
  1136. }
  1137. if (process.versions.pnp === "3") {
  1138. webpack5Config.snapshot.immutablePaths = [
  1139. /^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/,
  1140. ];
  1141. }
  1142. if (dev) {
  1143. if (!webpack5Config.optimization) {
  1144. webpack5Config.optimization = {};
  1145. }
  1146. // For Server Components, it's necessary to have provided exports collected
  1147. // to generate the correct flight manifest.
  1148. if (!hasServerComponents) {
  1149. webpack5Config.optimization.providedExports = false;
  1150. }
  1151. webpack5Config.optimization.usedExports = false;
  1152. }
  1153. const configVars = JSON.stringify({
  1154. crossOrigin: config.crossOrigin,
  1155. pageExtensions: pageExtensions,
  1156. trailingSlash: config.trailingSlash,
  1157. buildActivity: config.devIndicators.buildActivity,
  1158. buildActivityPosition: config.devIndicators.buildActivityPosition,
  1159. productionBrowserSourceMaps: !!config.productionBrowserSourceMaps,
  1160. reactStrictMode: config.reactStrictMode,
  1161. optimizeFonts: config.optimizeFonts,
  1162. optimizeCss: config.experimental.optimizeCss,
  1163. nextScriptWorkers: config.experimental.nextScriptWorkers,
  1164. scrollRestoration: config.experimental.scrollRestoration,
  1165. basePath: config.basePath,
  1166. pageEnv: config.experimental.pageEnv,
  1167. excludeDefaultMomentLocales: config.excludeDefaultMomentLocales,
  1168. assetPrefix: config.assetPrefix,
  1169. disableOptimizedLoading,
  1170. target,
  1171. isEdgeRuntime: isEdgeServer,
  1172. reactProductionProfiling,
  1173. webpack: !!config.webpack,
  1174. hasRewrites,
  1175. runtime: config.experimental.runtime,
  1176. swcMinify: config.swcMinify,
  1177. swcLoader: useSWCLoader,
  1178. removeConsole: (ref13 = config.compiler) == null ? void 0 : ref13.removeConsole,
  1179. reactRemoveProperties: (ref14 = config.compiler) == null ? void 0 : ref14.reactRemoveProperties,
  1180. styledComponents: (ref15 = config.compiler) == null ? void 0 : ref15.styledComponents,
  1181. relay: (ref16 = config.compiler) == null ? void 0 : ref16.relay,
  1182. emotion: (ref17 = config.compiler) == null ? void 0 : ref17.emotion,
  1183. modularizeImports: (ref18 = config.experimental) == null ? void 0 : ref18.modularizeImports,
  1184. legacyBrowsers: (ref19 = config.experimental) == null ? void 0 : ref19.legacyBrowsers
  1185. });
  1186. const cache = {
  1187. type: "filesystem",
  1188. // Includes:
  1189. // - Next.js version
  1190. // - next.config.js keys that affect compilation
  1191. version: `${"12.3.4"}|${configVars}`,
  1192. cacheDirectory: _path.default.join(distDir, "cache", "webpack")
  1193. };
  1194. // Adds `next.config.js` as a buildDependency when custom webpack config is provided
  1195. if (config.webpack && config.configFile) {
  1196. cache.buildDependencies = {
  1197. config: [
  1198. config.configFile
  1199. ]
  1200. };
  1201. }
  1202. webpack5Config.cache = cache;
  1203. if (process.env.NEXT_WEBPACK_LOGGING) {
  1204. const infra = process.env.NEXT_WEBPACK_LOGGING.includes("infrastructure");
  1205. const profileClient = process.env.NEXT_WEBPACK_LOGGING.includes("profile-client");
  1206. const profileServer = process.env.NEXT_WEBPACK_LOGGING.includes("profile-server");
  1207. const summaryClient = process.env.NEXT_WEBPACK_LOGGING.includes("summary-client");
  1208. const summaryServer = process.env.NEXT_WEBPACK_LOGGING.includes("summary-server");
  1209. const profile = profileClient && isClient || profileServer && (isNodeServer || isEdgeServer);
  1210. const summary = summaryClient && isClient || summaryServer && (isNodeServer || isEdgeServer);
  1211. const logDefault = !infra && !profile && !summary;
  1212. if (logDefault || infra) {
  1213. webpack5Config.infrastructureLogging = {
  1214. level: "verbose",
  1215. debug: /FileSystemInfo/
  1216. };
  1217. }
  1218. if (logDefault || profile) {
  1219. webpack5Config.plugins.push((compiler)=>{
  1220. compiler.hooks.done.tap("next-webpack-logging", (stats)=>{
  1221. console.log(stats.toString({
  1222. colors: true,
  1223. logging: logDefault ? "log" : "verbose"
  1224. }));
  1225. });
  1226. });
  1227. } else if (summary) {
  1228. webpack5Config.plugins.push((compiler)=>{
  1229. compiler.hooks.done.tap("next-webpack-logging", (stats)=>{
  1230. console.log(stats.toString({
  1231. preset: "summary",
  1232. colors: true,
  1233. timings: true
  1234. }));
  1235. });
  1236. });
  1237. }
  1238. if (profile) {
  1239. const ProgressPlugin = _webpack.webpack.ProgressPlugin;
  1240. webpack5Config.plugins.push(new ProgressPlugin({
  1241. profile: true
  1242. }));
  1243. webpack5Config.profile = true;
  1244. }
  1245. }
  1246. webpackConfig = await (0, _config).build(webpackConfig, {
  1247. supportedBrowsers,
  1248. rootDirectory: dir,
  1249. customAppFile: pagesDir ? new RegExp((0, _escapeRegexp).escapeStringRegexp(_path.default.join(pagesDir, `_app`))) : undefined,
  1250. isDevelopment: dev,
  1251. isServer: isNodeServer || isEdgeServer,
  1252. isEdgeRuntime: isEdgeServer,
  1253. targetWeb: isClient || isEdgeServer,
  1254. assetPrefix: config.assetPrefix || "",
  1255. sassOptions: config.sassOptions,
  1256. productionBrowserSourceMaps: config.productionBrowserSourceMaps,
  1257. future: config.future,
  1258. experimental: config.experimental,
  1259. disableStaticImages: config.images.disableStaticImages
  1260. });
  1261. // @ts-ignore Cache exists
  1262. webpackConfig.cache.name = `${webpackConfig.name}-${webpackConfig.mode}${isDevFallback ? "-fallback" : ""}`;
  1263. let originalDevtool = webpackConfig.devtool;
  1264. if (typeof config.webpack === "function") {
  1265. var ref33, ref34;
  1266. webpackConfig = config.webpack(webpackConfig, {
  1267. dir,
  1268. dev,
  1269. isServer: isNodeServer || isEdgeServer,
  1270. buildId,
  1271. config,
  1272. defaultLoaders,
  1273. totalPages: Object.keys(entrypoints).length,
  1274. webpack: _webpack.webpack,
  1275. ...isNodeServer || isEdgeServer ? {
  1276. nextRuntime: isEdgeServer ? "edge" : "nodejs"
  1277. } : {}
  1278. });
  1279. if (!webpackConfig) {
  1280. throw new Error(`Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your ${config.configFileName}.\n` + "See more info here https://nextjs.org/docs/messages/undefined-webpack-config");
  1281. }
  1282. if (dev && originalDevtool !== webpackConfig.devtool) {
  1283. webpackConfig.devtool = originalDevtool;
  1284. devtoolRevertWarning(originalDevtool);
  1285. }
  1286. // eslint-disable-next-line no-shadow
  1287. const webpack5Config = webpackConfig;
  1288. // disable lazy compilation of entries as next.js has it's own method here
  1289. if (((ref33 = webpack5Config.experiments) == null ? void 0 : ref33.lazyCompilation) === true) {
  1290. webpack5Config.experiments.lazyCompilation = {
  1291. entries: false
  1292. };
  1293. } else if (typeof ((ref34 = webpack5Config.experiments) == null ? void 0 : ref34.lazyCompilation) === "object" && webpack5Config.experiments.lazyCompilation.entries !== false) {
  1294. webpack5Config.experiments.lazyCompilation.entries = false;
  1295. }
  1296. if (typeof webpackConfig.then === "function") {
  1297. console.warn("> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config");
  1298. }
  1299. }
  1300. if (!config.images.disableStaticImages) {
  1301. var ref35;
  1302. const rules = ((ref35 = webpackConfig.module) == null ? void 0 : ref35.rules) || [];
  1303. const hasCustomSvg = rules.some((rule)=>rule && typeof rule === "object" && rule.loader !== "next-image-loader" && "test" in rule && rule.test instanceof RegExp && rule.test.test(".svg"));
  1304. const nextImageRule = rules.find((rule)=>rule && typeof rule === "object" && rule.loader === "next-image-loader");
  1305. if (hasCustomSvg && nextImageRule && nextImageRule && typeof nextImageRule === "object") {
  1306. // Exclude svg if the user already defined it in custom
  1307. // webpack config such as `@svgr/webpack` plugin or
  1308. // the `babel-plugin-inline-react-svg` plugin.
  1309. nextImageRule.test = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i;
  1310. }
  1311. }
  1312. if (config.experimental.craCompat && ((ref20 = webpackConfig.module) == null ? void 0 : ref20.rules) && webpackConfig.plugins) {
  1313. // CRA allows importing non-webpack handled files with file-loader
  1314. // these need to be the last rule to prevent catching other items
  1315. // https://github.com/facebook/create-react-app/blob/fddce8a9e21bf68f37054586deb0c8636a45f50b/packages/react-scripts/config/webpack.config.js#L594
  1316. const fileLoaderExclude = [
  1317. /\.(js|mjs|jsx|ts|tsx|json)$/
  1318. ];
  1319. const fileLoader = {
  1320. exclude: fileLoaderExclude,
  1321. issuer: fileLoaderExclude,
  1322. type: "asset/resource"
  1323. };
  1324. const topRules = [];
  1325. const innerRules = [];
  1326. for (const rule of webpackConfig.module.rules){
  1327. if (!rule || typeof rule !== "object") continue;
  1328. if (rule.resolve) {
  1329. topRules.push(rule);
  1330. } else {
  1331. if (rule.oneOf && !(rule.test || rule.exclude || rule.resource || rule.issuer)) {
  1332. rule.oneOf.forEach((r)=>innerRules.push(r));
  1333. } else {
  1334. innerRules.push(rule);
  1335. }
  1336. }
  1337. }
  1338. webpackConfig.module.rules = [
  1339. ...topRules,
  1340. {
  1341. oneOf: [
  1342. ...innerRules,
  1343. fileLoader
  1344. ]
  1345. },
  1346. ];
  1347. }
  1348. // Backwards compat with webpack-dev-middleware options object
  1349. if (typeof config.webpackDevMiddleware === "function") {
  1350. const options = config.webpackDevMiddleware({
  1351. watchOptions: webpackConfig.watchOptions
  1352. });
  1353. if (options.watchOptions) {
  1354. webpackConfig.watchOptions = options.watchOptions;
  1355. }
  1356. }
  1357. function canMatchCss(rule) {
  1358. if (!rule) {
  1359. return false;
  1360. }
  1361. const fileNames = [
  1362. "/tmp/NEXTJS_CSS_DETECTION_FILE.css",
  1363. "/tmp/NEXTJS_CSS_DETECTION_FILE.scss",
  1364. "/tmp/NEXTJS_CSS_DETECTION_FILE.sass",
  1365. "/tmp/NEXTJS_CSS_DETECTION_FILE.less",
  1366. "/tmp/NEXTJS_CSS_DETECTION_FILE.styl",
  1367. ];
  1368. if (rule instanceof RegExp && fileNames.some((input)=>rule.test(input))) {
  1369. return true;
  1370. }
  1371. if (typeof rule === "function") {
  1372. if (fileNames.some((input)=>{
  1373. try {
  1374. if (rule(input)) {
  1375. return true;
  1376. }
  1377. } catch (_) {}
  1378. return false;
  1379. })) {
  1380. return true;
  1381. }
  1382. }
  1383. if (Array.isArray(rule) && rule.some(canMatchCss)) {
  1384. return true;
  1385. }
  1386. return false;
  1387. }
  1388. var ref36;
  1389. const hasUserCssConfig = (ref36 = (ref21 = webpackConfig.module) == null ? void 0 : (ref22 = ref21.rules) == null ? void 0 : ref22.some((rule)=>canMatchCss(rule.test) || canMatchCss(rule.include))) != null ? ref36 : false;
  1390. if (hasUserCssConfig) {
  1391. var ref37, ref38, ref39, ref40, ref41;
  1392. // only show warning for one build
  1393. if (isNodeServer || isEdgeServer) {
  1394. console.warn(_chalk.default.yellow.bold("Warning: ") + _chalk.default.bold("Built-in CSS support is being disabled due to custom CSS configuration being detected.\n") + "See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n");
  1395. }
  1396. if ((ref37 = webpackConfig.module) == null ? void 0 : (ref38 = ref37.rules) == null ? void 0 : ref38.length) {
  1397. // Remove default CSS Loaders
  1398. webpackConfig.module.rules.forEach((r)=>{
  1399. if (!r || typeof r !== "object") return;
  1400. if (Array.isArray(r.oneOf)) {
  1401. r.oneOf = r.oneOf.filter((o)=>o[Symbol.for("__next_css_remove")] !== true);
  1402. }
  1403. });
  1404. }
  1405. if ((ref39 = webpackConfig.plugins) == null ? void 0 : ref39.length) {
  1406. // Disable CSS Extraction Plugin
  1407. webpackConfig.plugins = webpackConfig.plugins.filter((p)=>p.__next_css_remove !== true);
  1408. }
  1409. if ((ref40 = webpackConfig.optimization) == null ? void 0 : (ref41 = ref40.minimizer) == null ? void 0 : ref41.length) {
  1410. // Disable CSS Minifier
  1411. webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter((e)=>e.__next_css_remove !== true);
  1412. }
  1413. }
  1414. // Inject missing React Refresh loaders so that development mode is fast:
  1415. if (dev && isClient) {
  1416. attachReactRefresh(webpackConfig, defaultLoaders.babel);
  1417. }
  1418. // check if using @zeit/next-typescript and show warning
  1419. if ((isNodeServer || isEdgeServer) && webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
  1420. let foundTsRule = false;
  1421. webpackConfig.module.rules = webpackConfig.module.rules.filter((rule)=>{
  1422. if (!rule || typeof rule !== "object") return true;
  1423. if (!(rule.test instanceof RegExp)) return true;
  1424. if ("noop.ts".match(rule.test) && !"noop.js".match(rule.test)) {
  1425. // remove if it matches @zeit/next-typescript
  1426. foundTsRule = rule.use === defaultLoaders.babel;
  1427. return !foundTsRule;
  1428. }
  1429. return true;
  1430. });
  1431. if (foundTsRule) {
  1432. console.warn(`\n@zeit/next-typescript is no longer needed since Next.js has built-in support for TypeScript now. Please remove it from your ${config.configFileName} and your .babelrc\n`);
  1433. }
  1434. }
  1435. // Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
  1436. if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
  1437. [].forEach.call(webpackConfig.module.rules, function(rule) {
  1438. if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
  1439. return;
  1440. }
  1441. const isSass = rule.test.source === "\\.scss$" || rule.test.source === "\\.sass$";
  1442. const isLess = rule.test.source === "\\.less$";
  1443. const isCss = rule.test.source === "\\.css$";
  1444. const isStylus = rule.test.source === "\\.styl$";
  1445. // Check if the rule we're iterating over applies to Sass, Less, or CSS
  1446. if (!(isSass || isLess || isCss || isStylus)) {
  1447. return;
  1448. }
  1449. [].forEach.call(rule.use, function(use) {
  1450. if (!(use && typeof use === "object" && // Identify use statements only pertaining to `css-loader`
  1451. (use.loader === "css-loader" || use.loader === "css-loader/locals") && use.options && typeof use.options === "object" && // The `minimize` property is a good heuristic that we need to
  1452. // perform this hack. The `minimize` property was only valid on
  1453. // old `css-loader` versions. Custom setups (that aren't next-sass,
  1454. // next-less or next-stylus) likely have the newer version.
  1455. // We still handle this gracefully below.
  1456. (Object.prototype.hasOwnProperty.call(use.options, "minimize") || Object.prototype.hasOwnProperty.call(use.options, "exportOnlyLocals")))) {
  1457. return;
  1458. }
  1459. // Try to monkey patch within a try-catch. We shouldn't fail the build
  1460. // if we cannot pull this off.
  1461. // The user may not even be using the `next-sass` or `next-less` or
  1462. // `next-stylus` plugins.
  1463. // If it does work, great!
  1464. try {
  1465. // Resolve the version of `@zeit/next-css` as depended on by the Sass,
  1466. // Less or Stylus plugin.
  1467. const correctNextCss = require.resolve("@zeit/next-css", {
  1468. paths: [
  1469. isCss ? dir : require.resolve(isSass ? "@zeit/next-sass" : isLess ? "@zeit/next-less" : isStylus ? "@zeit/next-stylus" : "next"),
  1470. ]
  1471. });
  1472. // If we found `@zeit/next-css` ...
  1473. if (correctNextCss) {
  1474. // ... resolve the version of `css-loader` shipped with that
  1475. // package instead of whichever was hoisted highest in your
  1476. // `node_modules` tree.
  1477. const correctCssLoader = require.resolve(use.loader, {
  1478. paths: [
  1479. correctNextCss
  1480. ]
  1481. });
  1482. if (correctCssLoader) {
  1483. // We saved the user from a failed build!
  1484. use.loader = correctCssLoader;
  1485. }
  1486. }
  1487. } catch (_) {
  1488. // The error is not required to be handled.
  1489. }
  1490. });
  1491. });
  1492. }
  1493. // Backwards compat for `main.js` entry key
  1494. // and setup of dependencies between entries
  1495. // we can't do that in the initial entry for
  1496. // backward-compat reasons
  1497. const originalEntry = webpackConfig.entry;
  1498. if (typeof originalEntry !== "undefined") {
  1499. const updatedEntry = async ()=>{
  1500. const entry = typeof originalEntry === "function" ? await originalEntry() : originalEntry;
  1501. // Server compilation doesn't have main.js
  1502. if (clientEntries && Array.isArray(entry["main.js"]) && entry["main.js"].length > 0) {
  1503. const originalFile = clientEntries[_constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN];
  1504. entry[_constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
  1505. ...entry["main.js"],
  1506. originalFile,
  1507. ];
  1508. }
  1509. delete entry["main.js"];
  1510. for (const name of Object.keys(entry)){
  1511. entry[name] = (0, _entries).finalizeEntrypoint({
  1512. value: entry[name],
  1513. compilerType,
  1514. name,
  1515. appDir: config.experimental.appDir
  1516. });
  1517. }
  1518. return entry;
  1519. };
  1520. // @ts-ignore webpack 5 typings needed
  1521. webpackConfig.entry = updatedEntry;
  1522. }
  1523. if (!dev && typeof webpackConfig.entry === "function") {
  1524. // entry is always a function
  1525. webpackConfig.entry = await webpackConfig.entry();
  1526. }
  1527. return webpackConfig;
  1528. }
  1529. function _interopRequireDefault(obj) {
  1530. return obj && obj.__esModule ? obj : {
  1531. default: obj
  1532. };
  1533. }
  1534. function _getRequireWildcardCache() {
  1535. if (typeof WeakMap !== "function") return null;
  1536. var cache = new WeakMap();
  1537. _getRequireWildcardCache = function() {
  1538. return cache;
  1539. };
  1540. return cache;
  1541. }
  1542. function _interopRequireWildcard(obj) {
  1543. if (obj && obj.__esModule) {
  1544. return obj;
  1545. }
  1546. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  1547. return {
  1548. default: obj
  1549. };
  1550. }
  1551. var cache = _getRequireWildcardCache();
  1552. if (cache && cache.has(obj)) {
  1553. return cache.get(obj);
  1554. }
  1555. var newObj = {};
  1556. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  1557. for(var key in obj){
  1558. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1559. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  1560. if (desc && (desc.get || desc.set)) {
  1561. Object.defineProperty(newObj, key, desc);
  1562. } else {
  1563. newObj[key] = obj[key];
  1564. }
  1565. }
  1566. }
  1567. newObj.default = obj;
  1568. if (cache) {
  1569. cache.set(obj, newObj);
  1570. }
  1571. return newObj;
  1572. }
  1573. const NEXT_PROJECT_ROOT = (0, _path).join(__dirname, "..", "..");
  1574. const NEXT_PROJECT_ROOT_DIST = (0, _path).join(NEXT_PROJECT_ROOT, "dist");
  1575. const NEXT_PROJECT_ROOT_DIST_CLIENT = (0, _path).join(NEXT_PROJECT_ROOT_DIST, "client");
  1576. function errorIfEnvConflicted(config, key) {
  1577. const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key);
  1578. const hasNextRuntimeKey = key === "NEXT_RUNTIME";
  1579. if (isPrivateKey || hasNextRuntimeKey) {
  1580. throw new Error(`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`);
  1581. }
  1582. }
  1583. const watchOptions = Object.freeze({
  1584. aggregateTimeout: 5,
  1585. ignored: [
  1586. "**/.git/**",
  1587. "**/.next/**"
  1588. ]
  1589. });
  1590. function getDefineEnv({ dev , config , distDir , isClient , hasRewrites , hasReactRoot , isNodeServer , isEdgeServer , middlewareMatchers }) {
  1591. var ref, ref48, ref49, ref50;
  1592. return {
  1593. // internal field to identify the plugin config
  1594. __NEXT_DEFINE_ENV: "true",
  1595. ...Object.keys(process.env).reduce((prev, key)=>{
  1596. if (key.startsWith("NEXT_PUBLIC_")) {
  1597. prev[`process.env.${key}`] = JSON.stringify(process.env[key]);
  1598. }
  1599. return prev;
  1600. }, {}),
  1601. ...Object.keys(config.env).reduce((acc, key)=>{
  1602. errorIfEnvConflicted(config, key);
  1603. return {
  1604. ...acc,
  1605. [`process.env.${key}`]: JSON.stringify(config.env[key])
  1606. };
  1607. }, {}),
  1608. ...!isEdgeServer ? {} : {
  1609. EdgeRuntime: JSON.stringify(/**
  1610. * Cloud providers can set this environment variable to allow users
  1611. * and library authors to have different implementations based on
  1612. * the runtime they are running with, if it's not using `edge-runtime`
  1613. */ process.env.NEXT_EDGE_RUNTIME_PROVIDER || "edge-runtime")
  1614. },
  1615. // TODO: enforce `NODE_ENV` on `process.env`, and add a test:
  1616. "process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
  1617. ...(isNodeServer || isEdgeServer) && {
  1618. "process.env.NEXT_RUNTIME": JSON.stringify(isEdgeServer ? "edge" : "nodejs")
  1619. },
  1620. "process.env.__NEXT_MIDDLEWARE_MATCHERS": JSON.stringify(middlewareMatchers || []),
  1621. "process.env.__NEXT_MANUAL_CLIENT_BASE_PATH": JSON.stringify(config.experimental.manualClientBasePath),
  1622. "process.env.__NEXT_NEW_LINK_BEHAVIOR": JSON.stringify(config.experimental.newNextLinkBehavior),
  1623. "process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE": JSON.stringify(config.experimental.optimisticClientCache),
  1624. "process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE": JSON.stringify(config.experimental.skipMiddlewareUrlNormalize),
  1625. "process.env.__NEXT_ALLOW_MIDDLEWARE_RESPONSE_BODY": JSON.stringify(config.experimental.allowMiddlewareResponseBody),
  1626. "process.env.__NEXT_MANUAL_TRAILING_SLASH": JSON.stringify((ref = config.experimental) == null ? void 0 : ref.skipTrailingSlashRedirect),
  1627. "process.env.__NEXT_CROSS_ORIGIN": JSON.stringify(config.crossOrigin),
  1628. "process.browser": JSON.stringify(isClient),
  1629. "process.env.__NEXT_TEST_MODE": JSON.stringify(process.env.__NEXT_TEST_MODE),
  1630. // This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
  1631. ...dev && (isClient || isEdgeServer) ? {
  1632. "process.env.__NEXT_DIST_DIR": JSON.stringify(distDir)
  1633. } : {},
  1634. "process.env.__NEXT_TRAILING_SLASH": JSON.stringify(config.trailingSlash),
  1635. "process.env.__NEXT_BUILD_INDICATOR": JSON.stringify(config.devIndicators.buildActivity),
  1636. "process.env.__NEXT_BUILD_INDICATOR_POSITION": JSON.stringify(config.devIndicators.buildActivityPosition),
  1637. "process.env.__NEXT_STRICT_MODE": JSON.stringify(config.reactStrictMode),
  1638. "process.env.__NEXT_REACT_ROOT": JSON.stringify(hasReactRoot),
  1639. "process.env.__NEXT_OPTIMIZE_FONTS": JSON.stringify(!dev && config.optimizeFonts),
  1640. "process.env.__NEXT_OPTIMIZE_CSS": JSON.stringify(config.experimental.optimizeCss && !dev),
  1641. "process.env.__NEXT_SCRIPT_WORKERS": JSON.stringify(config.experimental.nextScriptWorkers && !dev),
  1642. "process.env.__NEXT_SCROLL_RESTORATION": JSON.stringify(config.experimental.scrollRestoration),
  1643. "process.env.__NEXT_IMAGE_OPTS": JSON.stringify({
  1644. deviceSizes: config.images.deviceSizes,
  1645. imageSizes: config.images.imageSizes,
  1646. path: config.images.path,
  1647. loader: config.images.loader,
  1648. dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
  1649. unoptimized: config == null ? void 0 : (ref48 = config.images) == null ? void 0 : ref48.unoptimized,
  1650. ...dev ? {
  1651. // pass domains in development to allow validating on the client
  1652. domains: config.images.domains,
  1653. remotePatterns: (ref49 = config.images) == null ? void 0 : ref49.remotePatterns
  1654. } : {}
  1655. }),
  1656. "process.env.__NEXT_ROUTER_BASEPATH": JSON.stringify(config.basePath),
  1657. "process.env.__NEXT_HAS_REWRITES": JSON.stringify(hasRewrites),
  1658. "process.env.__NEXT_I18N_SUPPORT": JSON.stringify(!!config.i18n),
  1659. "process.env.__NEXT_I18N_DOMAINS": JSON.stringify((ref50 = config.i18n) == null ? void 0 : ref50.domains),
  1660. "process.env.__NEXT_ANALYTICS_ID": JSON.stringify(config.analyticsId),
  1661. ...isNodeServer || isEdgeServer ? {
  1662. // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
  1663. // This is typically found in unmaintained modules from the
  1664. // pre-webpack era (common in server-side code)
  1665. "global.GENTLY": JSON.stringify(false)
  1666. } : undefined,
  1667. // stub process.env with proxy to warn a missing value is
  1668. // being accessed in development mode
  1669. ...config.experimental.pageEnv && dev ? {
  1670. "process.env": `
  1671. new Proxy(${isNodeServer ? "process.env" : "{}"}, {
  1672. get(target, prop) {
  1673. if (typeof target[prop] === 'undefined') {
  1674. console.warn(\`An environment variable (\${prop}) that was not provided in the environment was accessed.\nSee more info here: https://nextjs.org/docs/messages/missing-env-value\`)
  1675. }
  1676. return target[prop]
  1677. }
  1678. })
  1679. `
  1680. } : {}
  1681. };
  1682. }
  1683. function getSupportedBrowsers(dir, isDevelopment, config) {
  1684. let browsers;
  1685. try {
  1686. const browsersListConfig = _browserslist.default.loadConfig({
  1687. path: dir,
  1688. env: isDevelopment ? "development" : "production"
  1689. });
  1690. // Running `browserslist` resolves `extends` and other config features into a list of browsers
  1691. if (browsersListConfig && browsersListConfig.length > 0) {
  1692. browsers = (0, _browserslist).default(browsersListConfig);
  1693. }
  1694. } catch {}
  1695. // When user has browserslist use that target
  1696. if (browsers && browsers.length > 0) {
  1697. return browsers;
  1698. }
  1699. // When user does not have browserslist use the default target
  1700. // When `experimental.legacyBrowsers: false` the modern default is used
  1701. return config.experimental.legacyBrowsers ? undefined : _constants1.MODERN_BROWSERSLIST_TARGET;
  1702. }
  1703. const devtoolRevertWarning = (0, _utils).execOnce((devtool)=>{
  1704. console.warn(_chalk.default.yellow.bold("Warning: ") + _chalk.default.bold(`Reverting webpack devtool to '${devtool}'.\n`) + "Changing the webpack devtool in development mode will cause severe performance regressions.\n" + "Read more: https://nextjs.org/docs/messages/improper-devtool");
  1705. });
  1706. let loggedSwcDisabled = false;
  1707. let loggedIgnoredCompilerOptions = false;
  1708. function getOptimizedAliases() {
  1709. const stubWindowFetch = _path.default.join(__dirname, "polyfills", "fetch", "index.js");
  1710. const stubObjectAssign = _path.default.join(__dirname, "polyfills", "object-assign.js");
  1711. const shimAssign = _path.default.join(__dirname, "polyfills", "object.assign");
  1712. return Object.assign({}, {
  1713. unfetch$: stubWindowFetch,
  1714. "isomorphic-unfetch$": stubWindowFetch,
  1715. "whatwg-fetch$": _path.default.join(__dirname, "polyfills", "fetch", "whatwg-fetch.js")
  1716. }, {
  1717. "object-assign$": stubObjectAssign,
  1718. // Stub Package: object.assign
  1719. "object.assign/auto": _path.default.join(shimAssign, "auto.js"),
  1720. "object.assign/implementation": _path.default.join(shimAssign, "implementation.js"),
  1721. "object.assign$": _path.default.join(shimAssign, "index.js"),
  1722. "object.assign/polyfill": _path.default.join(shimAssign, "polyfill.js"),
  1723. "object.assign/shim": _path.default.join(shimAssign, "shim.js"),
  1724. // Replace: full URL polyfill with platform-based polyfill
  1725. url: require.resolve("next/dist/compiled/native-url")
  1726. });
  1727. }
  1728. function attachReactRefresh(webpackConfig, targetLoader) {
  1729. var ref, ref51;
  1730. let injections = 0;
  1731. const reactRefreshLoaderName = "next/dist/compiled/@next/react-refresh-utils/dist/loader";
  1732. const reactRefreshLoader = require.resolve(reactRefreshLoaderName);
  1733. (ref = webpackConfig.module) == null ? void 0 : (ref51 = ref.rules) == null ? void 0 : ref51.forEach((rule)=>{
  1734. if (rule && typeof rule === "object" && "use" in rule) {
  1735. const curr = rule.use;
  1736. // When the user has configured `defaultLoaders.babel` for a input file:
  1737. if (curr === targetLoader) {
  1738. ++injections;
  1739. rule.use = [
  1740. reactRefreshLoader,
  1741. curr
  1742. ];
  1743. } else if (Array.isArray(curr) && curr.some((r)=>r === targetLoader) && // Check if loader already exists:
  1744. !curr.some((r)=>r === reactRefreshLoader || r === reactRefreshLoaderName)) {
  1745. ++injections;
  1746. const idx = curr.findIndex((r)=>r === targetLoader);
  1747. // Clone to not mutate user input
  1748. rule.use = [
  1749. ...curr
  1750. ];
  1751. // inject / input: [other, babel] output: [other, refresh, babel]:
  1752. rule.use.splice(idx, 0, reactRefreshLoader);
  1753. }
  1754. }
  1755. });
  1756. if (injections) {
  1757. Log.info(`automatically enabled Fast Refresh for ${injections} custom loader${injections > 1 ? "s" : ""}`);
  1758. }
  1759. }
  1760. const NODE_RESOLVE_OPTIONS = {
  1761. dependencyType: "commonjs",
  1762. modules: [
  1763. "node_modules"
  1764. ],
  1765. fallback: false,
  1766. exportsFields: [
  1767. "exports"
  1768. ],
  1769. importsFields: [
  1770. "imports"
  1771. ],
  1772. conditionNames: [
  1773. "node",
  1774. "require"
  1775. ],
  1776. descriptionFiles: [
  1777. "package.json"
  1778. ],
  1779. extensions: [
  1780. ".js",
  1781. ".json",
  1782. ".node"
  1783. ],
  1784. enforceExtensions: false,
  1785. symlinks: true,
  1786. mainFields: [
  1787. "main"
  1788. ],
  1789. mainFiles: [
  1790. "index"
  1791. ],
  1792. roots: [],
  1793. fullySpecified: false,
  1794. preferRelative: false,
  1795. preferAbsolute: false,
  1796. restrictions: []
  1797. };
  1798. exports.NODE_RESOLVE_OPTIONS = NODE_RESOLVE_OPTIONS;
  1799. const NODE_BASE_RESOLVE_OPTIONS = {
  1800. ...NODE_RESOLVE_OPTIONS,
  1801. alias: false
  1802. };
  1803. exports.NODE_BASE_RESOLVE_OPTIONS = NODE_BASE_RESOLVE_OPTIONS;
  1804. const NODE_ESM_RESOLVE_OPTIONS = {
  1805. ...NODE_RESOLVE_OPTIONS,
  1806. alias: false,
  1807. dependencyType: "esm",
  1808. conditionNames: [
  1809. "node",
  1810. "import"
  1811. ],
  1812. fullySpecified: true
  1813. };
  1814. exports.NODE_ESM_RESOLVE_OPTIONS = NODE_ESM_RESOLVE_OPTIONS;
  1815. const NODE_BASE_ESM_RESOLVE_OPTIONS = {
  1816. ...NODE_ESM_RESOLVE_OPTIONS,
  1817. alias: false
  1818. };
  1819. exports.NODE_BASE_ESM_RESOLVE_OPTIONS = NODE_BASE_ESM_RESOLVE_OPTIONS;
  1820. const nextImageLoaderRegex = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i;
  1821. exports.nextImageLoaderRegex = nextImageLoaderRegex;
  1822. async function resolveExternal(appDir, esmExternalsConfig, context, request, isEsmRequested, getResolve, isLocalCallback, baseResolveCheck = true, esmResolveOptions = NODE_ESM_RESOLVE_OPTIONS, nodeResolveOptions = NODE_RESOLVE_OPTIONS, baseEsmResolveOptions = NODE_BASE_ESM_RESOLVE_OPTIONS, baseResolveOptions = NODE_BASE_RESOLVE_OPTIONS) {
  1823. const esmExternals = !!esmExternalsConfig;
  1824. const looseEsmExternals = esmExternalsConfig === "loose";
  1825. let res = null;
  1826. let isEsm = false;
  1827. let preferEsmOptions = esmExternals && isEsmRequested ? [
  1828. true,
  1829. false
  1830. ] : [
  1831. false
  1832. ];
  1833. for (const preferEsm of preferEsmOptions){
  1834. const resolve = getResolve(preferEsm ? esmResolveOptions : nodeResolveOptions);
  1835. // Resolve the import with the webpack provided context, this
  1836. // ensures we're resolving the correct version when multiple
  1837. // exist.
  1838. try {
  1839. [res, isEsm] = await resolve(context, request);
  1840. } catch (err) {
  1841. res = null;
  1842. }
  1843. if (!res) {
  1844. continue;
  1845. }
  1846. // ESM externals can only be imported (and not required).
  1847. // Make an exception in loose mode.
  1848. if (!isEsmRequested && isEsm && !looseEsmExternals) {
  1849. continue;
  1850. }
  1851. if (isLocalCallback) {
  1852. return {
  1853. localRes: isLocalCallback(res)
  1854. };
  1855. }
  1856. // Bundled Node.js code is relocated without its node_modules tree.
  1857. // This means we need to make sure its request resolves to the same
  1858. // package that'll be available at runtime. If it's not identical,
  1859. // we need to bundle the code (even if it _should_ be external).
  1860. if (baseResolveCheck) {
  1861. let baseRes;
  1862. let baseIsEsm;
  1863. try {
  1864. const baseResolve = getResolve(isEsm ? baseEsmResolveOptions : baseResolveOptions);
  1865. [baseRes, baseIsEsm] = await baseResolve(appDir, request);
  1866. } catch (err) {
  1867. baseRes = null;
  1868. baseIsEsm = false;
  1869. }
  1870. // Same as above: if the package, when required from the root,
  1871. // would be different from what the real resolution would use, we
  1872. // cannot externalize it.
  1873. // if request is pointing to a symlink it could point to the the same file,
  1874. // the resolver will resolve symlinks so this is handled
  1875. if (baseRes !== res || isEsm !== baseIsEsm) {
  1876. res = null;
  1877. continue;
  1878. }
  1879. }
  1880. break;
  1881. }
  1882. return {
  1883. res,
  1884. isEsm
  1885. };
  1886. }
  1887. //# sourceMappingURL=webpack-config.js.map