index.js 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = build;
  6. var _env = require("@next/env");
  7. var _chalk = _interopRequireDefault(require("next/dist/compiled/chalk"));
  8. var _crypto = _interopRequireDefault(require("crypto"));
  9. var _micromatch = require("next/dist/compiled/micromatch");
  10. var _fs = require("fs");
  11. var _jestWorker = require("next/dist/compiled/jest-worker");
  12. var _worker = require("../lib/worker");
  13. var _devalue = _interopRequireDefault(require("next/dist/compiled/devalue"));
  14. var _escapeRegexp = require("../shared/lib/escape-regexp");
  15. var _findUp = _interopRequireDefault(require("next/dist/compiled/find-up"));
  16. var _indexCjs = require("next/dist/compiled/nanoid/index.cjs");
  17. var _pathToRegexp = require("next/dist/compiled/path-to-regexp");
  18. var _path = _interopRequireWildcard(require("path"));
  19. var _formatWebpackMessages = _interopRequireDefault(require("../client/dev/error-overlay/format-webpack-messages"));
  20. var _constants = require("../lib/constants");
  21. var _fileExists = require("../lib/file-exists");
  22. var _findPagesDir = require("../lib/find-pages-dir");
  23. var _loadCustomRoutes = _interopRequireWildcard(require("../lib/load-custom-routes"));
  24. var _redirectStatus = require("../lib/redirect-status");
  25. var _nonNullable = require("../lib/non-nullable");
  26. var _recursiveDelete = require("../lib/recursive-delete");
  27. var _verifyAndLint = require("../lib/verifyAndLint");
  28. var _verifyPartytownSetup = require("../lib/verify-partytown-setup");
  29. var _constants1 = require("../shared/lib/constants");
  30. var _utils = require("../shared/lib/router/utils");
  31. var _config = _interopRequireDefault(require("../server/config"));
  32. var _utils1 = require("../server/utils");
  33. var _normalizePagePath = require("../shared/lib/page-path/normalize-page-path");
  34. var _require = require("../server/require");
  35. var ciEnvironment = _interopRequireWildcard(require("../telemetry/ci-info"));
  36. var _events = require("../telemetry/events");
  37. var _storage = require("../telemetry/storage");
  38. var _compiler = require("./compiler");
  39. var _getPageStaticInfo = require("./analysis/get-page-static-info");
  40. var _entries = require("./entries");
  41. var _generateBuildId = require("./generate-build-id");
  42. var _isWriteable = require("./is-writeable");
  43. var Log = _interopRequireWildcard(require("./output/log"));
  44. var _spinner = _interopRequireDefault(require("./spinner"));
  45. var _trace = require("../trace");
  46. var _utils2 = require("./utils");
  47. var _webpackConfig = _interopRequireDefault(require("./webpack-config"));
  48. var _writeBuildId = require("./write-build-id");
  49. var _normalizeLocalePath = require("../shared/lib/i18n/normalize-locale-path");
  50. var _isError = _interopRequireDefault(require("../lib/is-error"));
  51. var _telemetryPlugin = require("./webpack/plugins/telemetry-plugin");
  52. var _recursiveCopy = require("../lib/recursive-copy");
  53. var _recursiveReaddir = require("../lib/recursive-readdir");
  54. var _swc = require("./swc");
  55. var _flightClientEntryPlugin = require("./webpack/plugins/flight-client-entry-plugin");
  56. var _routeRegex = require("../shared/lib/router/utils/route-regex");
  57. var _flatReaddir = require("../lib/flat-readdir");
  58. var _swcPlugins = require("../telemetry/events/swc-plugins");
  59. var _appPaths = require("../shared/lib/router/utils/app-paths");
  60. async function build(dir, conf = null, reactProductionProfiling = false, debugOutput = false, runLint = true) {
  61. try {
  62. const nextBuildSpan = (0, _trace).trace("next-build", undefined, {
  63. version: "12.3.4"
  64. });
  65. const buildResult = await nextBuildSpan.traceAsyncFn(async ()=>{
  66. var ref7, ref1;
  67. // attempt to load global env values so they are available in next.config.js
  68. const { loadedEnvFiles } = nextBuildSpan.traceChild("load-dotenv").traceFn(()=>(0, _env).loadEnvConfig(dir, false, Log));
  69. const config = await nextBuildSpan.traceChild("load-next-config").traceAsyncFn(()=>(0, _config).default(_constants1.PHASE_PRODUCTION_BUILD, dir, conf));
  70. const distDir = _path.default.join(dir, config.distDir);
  71. (0, _trace).setGlobal("phase", _constants1.PHASE_PRODUCTION_BUILD);
  72. (0, _trace).setGlobal("distDir", distDir);
  73. // We enable concurrent features (Fizz-related rendering architecture) when
  74. // using React 18 or experimental.
  75. const hasReactRoot = !!process.env.__NEXT_REACT_ROOT;
  76. const hasServerComponents = hasReactRoot && !!config.experimental.serverComponents;
  77. const { target } = config;
  78. const buildId = await nextBuildSpan.traceChild("generate-buildid").traceAsyncFn(()=>(0, _generateBuildId).generateBuildId(config.generateBuildId, _indexCjs.nanoid));
  79. const customRoutes = await nextBuildSpan.traceChild("load-custom-routes").traceAsyncFn(()=>(0, _loadCustomRoutes).default(config));
  80. const { headers , rewrites , redirects } = customRoutes;
  81. const cacheDir = _path.default.join(distDir, "cache");
  82. if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
  83. const hasCache = await (0, _fileExists).fileExists(cacheDir);
  84. if (!hasCache) {
  85. // Intentionally not piping to stderr in case people fail in CI when
  86. // stderr is detected.
  87. console.log(`${Log.prefixes.warn} No build cache found. Please configure build caching for faster rebuilds. Read more: https://nextjs.org/docs/messages/no-cache`);
  88. }
  89. }
  90. const telemetry = new _storage.Telemetry({
  91. distDir
  92. });
  93. (0, _trace).setGlobal("telemetry", telemetry);
  94. const publicDir = _path.default.join(dir, "public");
  95. const { pages: pagesDir , appDir } = (0, _findPagesDir).findPagesDir(dir, config.experimental.appDir);
  96. const hasPublicDir = await (0, _fileExists).fileExists(publicDir);
  97. telemetry.record((0, _events).eventCliSession(dir, config, {
  98. webpackVersion: 5,
  99. cliCommand: "build",
  100. isSrcDir: !!pagesDir && _path.default.relative(dir, pagesDir).startsWith("src") || !!appDir && _path.default.relative(dir, appDir).startsWith("src"),
  101. hasNowJson: !!await (0, _findUp).default("now.json", {
  102. cwd: dir
  103. }),
  104. isCustomServer: null
  105. }));
  106. (0, _events).eventNextPlugins(_path.default.resolve(dir)).then((events)=>telemetry.record(events));
  107. (0, _swcPlugins).eventSwcPlugins(_path.default.resolve(dir), config).then((events)=>telemetry.record(events));
  108. const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors);
  109. const ignoreESLint = Boolean(config.eslint.ignoreDuringBuilds);
  110. const eslintCacheDir = _path.default.join(cacheDir, "eslint/");
  111. const shouldLint = !ignoreESLint && runLint;
  112. if (ignoreTypeScriptErrors) {
  113. Log.info("Skipping validation of types");
  114. }
  115. if (runLint && ignoreESLint) {
  116. // only print log when build requre lint while ignoreESLint is enabled
  117. Log.info("Skipping linting");
  118. }
  119. let typeCheckingAndLintingSpinnerPrefixText;
  120. let typeCheckingAndLintingSpinner;
  121. if (!ignoreTypeScriptErrors && shouldLint) {
  122. typeCheckingAndLintingSpinnerPrefixText = "Linting and checking validity of types";
  123. } else if (!ignoreTypeScriptErrors) {
  124. typeCheckingAndLintingSpinnerPrefixText = "Checking validity of types";
  125. } else if (shouldLint) {
  126. typeCheckingAndLintingSpinnerPrefixText = "Linting";
  127. }
  128. // we will not create a spinner if both ignoreTypeScriptErrors and ignoreESLint are
  129. // enabled, but we will still verifying project's tsconfig and dependencies.
  130. if (typeCheckingAndLintingSpinnerPrefixText) {
  131. typeCheckingAndLintingSpinner = (0, _spinner).default({
  132. prefixText: `${Log.prefixes.info} ${typeCheckingAndLintingSpinnerPrefixText}`
  133. });
  134. }
  135. const typeCheckStart = process.hrtime();
  136. try {
  137. const [[verifyResult, typeCheckEnd]] = await Promise.all([
  138. nextBuildSpan.traceChild("verify-typescript-setup").traceAsyncFn(()=>verifyTypeScriptSetup(dir, [
  139. pagesDir,
  140. appDir
  141. ].filter(Boolean), !ignoreTypeScriptErrors, config.typescript.tsconfigPath, config.images.disableStaticImages, cacheDir, config.experimental.cpus, config.experimental.workerThreads).then((resolved)=>{
  142. const checkEnd = process.hrtime(typeCheckStart);
  143. return [
  144. resolved,
  145. checkEnd
  146. ];
  147. })),
  148. shouldLint && nextBuildSpan.traceChild("verify-and-lint").traceAsyncFn(async ()=>{
  149. var ref;
  150. await (0, _verifyAndLint).verifyAndLint(dir, eslintCacheDir, (ref = config.eslint) == null ? void 0 : ref.dirs, config.experimental.cpus, config.experimental.workerThreads, telemetry, !!config.experimental.appDir);
  151. }),
  152. ]);
  153. typeCheckingAndLintingSpinner == null ? void 0 : typeCheckingAndLintingSpinner.stopAndPersist();
  154. if (!ignoreTypeScriptErrors && verifyResult) {
  155. var ref2, ref3, ref4;
  156. telemetry.record((0, _events).eventTypeCheckCompleted({
  157. durationInSeconds: typeCheckEnd[0],
  158. typescriptVersion: verifyResult.version,
  159. inputFilesCount: (ref2 = verifyResult.result) == null ? void 0 : ref2.inputFilesCount,
  160. totalFilesCount: (ref3 = verifyResult.result) == null ? void 0 : ref3.totalFilesCount,
  161. incremental: (ref4 = verifyResult.result) == null ? void 0 : ref4.incremental
  162. }));
  163. }
  164. } catch (err1) {
  165. // prevent showing jest-worker internal error as it
  166. // isn't helpful for users and clutters output
  167. if ((0, _isError).default(err1) && err1.message === "Call retries were exceeded") {
  168. process.exit(1);
  169. }
  170. throw err1;
  171. }
  172. const buildLintEvent = {
  173. featureName: "build-lint",
  174. invocationCount: shouldLint ? 1 : 0
  175. };
  176. telemetry.record({
  177. eventName: _events.EVENT_BUILD_FEATURE_USAGE,
  178. payload: buildLintEvent
  179. });
  180. const buildSpinner = (0, _spinner).default({
  181. prefixText: `${Log.prefixes.info} Creating an optimized production build`
  182. });
  183. const isLikeServerless = (0, _utils1).isTargetLikeServerless(target);
  184. const pagesPaths = pagesDir ? await nextBuildSpan.traceChild("collect-pages").traceAsyncFn(()=>(0, _recursiveReaddir).recursiveReadDir(pagesDir, new RegExp(`\\.(?:${config.pageExtensions.join("|")})$`))) : [];
  185. let appPaths;
  186. if (appDir) {
  187. appPaths = await nextBuildSpan.traceChild("collect-app-paths").traceAsyncFn(()=>(0, _recursiveReaddir).recursiveReadDir(appDir, new RegExp(`page\\.(?:${config.pageExtensions.join("|")})$`)));
  188. }
  189. const middlewareDetectionRegExp = new RegExp(`^${_constants.MIDDLEWARE_FILENAME}\\.(?:${config.pageExtensions.join("|")})$`);
  190. const rootPaths = pagesDir ? (await (0, _flatReaddir).flatReaddir((0, _path).join(pagesDir, ".."), middlewareDetectionRegExp)).map((absoluteFile)=>absoluteFile.replace(dir, "")) : [];
  191. // needed for static exporting since we want to replace with HTML
  192. // files
  193. const allStaticPages = new Set();
  194. let allPageInfos = new Map();
  195. const previewProps = {
  196. previewModeId: _crypto.default.randomBytes(16).toString("hex"),
  197. previewModeSigningKey: _crypto.default.randomBytes(32).toString("hex"),
  198. previewModeEncryptionKey: _crypto.default.randomBytes(32).toString("hex")
  199. };
  200. const mappedPages = nextBuildSpan.traceChild("create-pages-mapping").traceFn(()=>(0, _entries).createPagesMapping({
  201. isDev: false,
  202. pageExtensions: config.pageExtensions,
  203. pagesType: "pages",
  204. pagePaths: pagesPaths,
  205. pagesDir
  206. }));
  207. let mappedAppPages;
  208. if (appPaths && appDir) {
  209. mappedAppPages = nextBuildSpan.traceChild("create-app-mapping").traceFn(()=>(0, _entries).createPagesMapping({
  210. pagePaths: appPaths,
  211. isDev: false,
  212. pagesType: "app",
  213. pageExtensions: config.pageExtensions,
  214. pagesDir: pagesDir
  215. }));
  216. }
  217. let mappedRootPaths = {};
  218. if (rootPaths.length > 0) {
  219. mappedRootPaths = (0, _entries).createPagesMapping({
  220. isDev: false,
  221. pageExtensions: config.pageExtensions,
  222. pagePaths: rootPaths,
  223. pagesType: "root",
  224. pagesDir: pagesDir
  225. });
  226. }
  227. const entrypoints = await nextBuildSpan.traceChild("create-entrypoints").traceAsyncFn(()=>(0, _entries).createEntrypoints({
  228. buildId,
  229. config,
  230. envFiles: loadedEnvFiles,
  231. isDev: false,
  232. pages: mappedPages,
  233. pagesDir,
  234. previewMode: previewProps,
  235. target,
  236. rootDir: dir,
  237. rootPaths: mappedRootPaths,
  238. appDir,
  239. appPaths: mappedAppPages,
  240. pageExtensions: config.pageExtensions
  241. }));
  242. const pageKeys = {
  243. pages: Object.keys(mappedPages),
  244. app: mappedAppPages ? Object.keys(mappedAppPages).map((key)=>(0, _appPaths).normalizeAppPath(key) || "/") : undefined
  245. };
  246. const conflictingPublicFiles = [];
  247. const hasPages404 = (ref7 = mappedPages["/404"]) == null ? void 0 : ref7.startsWith(_constants.PAGES_DIR_ALIAS);
  248. const hasCustomErrorPage = mappedPages["/_error"].startsWith(_constants.PAGES_DIR_ALIAS);
  249. if (hasPublicDir) {
  250. const hasPublicUnderScoreNextDir = await (0, _fileExists).fileExists(_path.default.join(publicDir, "_next"));
  251. if (hasPublicUnderScoreNextDir) {
  252. throw new Error(_constants.PUBLIC_DIR_MIDDLEWARE_CONFLICT);
  253. }
  254. }
  255. await nextBuildSpan.traceChild("public-dir-conflict-check").traceAsyncFn(async ()=>{
  256. // Check if pages conflict with files in `public`
  257. // Only a page of public file can be served, not both.
  258. for(const page in mappedPages){
  259. const hasPublicPageFile = await (0, _fileExists).fileExists(_path.default.join(publicDir, page === "/" ? "/index" : page), "file");
  260. if (hasPublicPageFile) {
  261. conflictingPublicFiles.push(page);
  262. }
  263. }
  264. const numConflicting = conflictingPublicFiles.length;
  265. if (numConflicting) {
  266. throw new Error(`Conflicting public and page file${numConflicting === 1 ? " was" : "s were"} found. https://nextjs.org/docs/messages/conflicting-public-file-page\n${conflictingPublicFiles.join("\n")}`);
  267. }
  268. });
  269. const nestedReservedPages = pageKeys.pages.filter((page)=>{
  270. return page.match(/\/(_app|_document|_error)$/) && _path.default.dirname(page) !== "/";
  271. });
  272. if (nestedReservedPages.length) {
  273. Log.warn(`The following reserved Next.js pages were detected not directly under the pages directory:\n` + nestedReservedPages.join("\n") + `\nSee more info here: https://nextjs.org/docs/messages/nested-reserved-page\n`);
  274. }
  275. const restrictedRedirectPaths = [
  276. "/_next"
  277. ].map((p)=>config.basePath ? `${config.basePath}${p}` : p);
  278. const buildCustomRoute = (r, type)=>{
  279. const keys = [];
  280. const routeRegex = (0, _pathToRegexp).pathToRegexp(r.source, keys, {
  281. strict: true,
  282. sensitive: false,
  283. delimiter: "/"
  284. });
  285. let regexSource = routeRegex.source;
  286. if (!r.internal) {
  287. regexSource = (0, _redirectStatus).modifyRouteRegex(routeRegex.source, type === "redirect" ? restrictedRedirectPaths : undefined);
  288. }
  289. return {
  290. ...r,
  291. ...type === "redirect" ? {
  292. statusCode: (0, _redirectStatus).getRedirectStatus(r),
  293. permanent: undefined
  294. } : {},
  295. regex: (0, _loadCustomRoutes).normalizeRouteRegex(regexSource)
  296. };
  297. };
  298. const routesManifestPath = _path.default.join(distDir, _constants1.ROUTES_MANIFEST);
  299. const routesManifest = nextBuildSpan.traceChild("generate-routes-manifest").traceFn(()=>{
  300. var _app;
  301. const sortedRoutes = (0, _utils).getSortedRoutes([
  302. ...pageKeys.pages,
  303. ...(_app = pageKeys.app) != null ? _app : [],
  304. ]);
  305. const dynamicRoutes = [];
  306. const staticRoutes = [];
  307. for (const route of sortedRoutes){
  308. if ((0, _utils).isDynamicRoute(route)) {
  309. dynamicRoutes.push(pageToRoute(route));
  310. } else if (!(0, _utils2).isReservedPage(route)) {
  311. staticRoutes.push(pageToRoute(route));
  312. }
  313. }
  314. return {
  315. version: 3,
  316. pages404: true,
  317. basePath: config.basePath,
  318. redirects: redirects.map((r)=>buildCustomRoute(r, "redirect")),
  319. headers: headers.map((r)=>buildCustomRoute(r, "header")),
  320. dynamicRoutes,
  321. staticRoutes,
  322. dataRoutes: [],
  323. i18n: config.i18n || undefined,
  324. skipMiddlewareUrlNormalize: config.experimental.skipMiddlewareUrlNormalize
  325. };
  326. });
  327. if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
  328. routesManifest.rewrites = rewrites.afterFiles.map((r)=>buildCustomRoute(r, "rewrite"));
  329. } else {
  330. routesManifest.rewrites = {
  331. beforeFiles: rewrites.beforeFiles.map((r)=>buildCustomRoute(r, "rewrite")),
  332. afterFiles: rewrites.afterFiles.map((r)=>buildCustomRoute(r, "rewrite")),
  333. fallback: rewrites.fallback.map((r)=>buildCustomRoute(r, "rewrite"))
  334. };
  335. }
  336. const combinedRewrites = [
  337. ...rewrites.beforeFiles,
  338. ...rewrites.afterFiles,
  339. ...rewrites.fallback,
  340. ];
  341. const distDirCreated = await nextBuildSpan.traceChild("create-dist-dir").traceAsyncFn(async ()=>{
  342. try {
  343. await _fs.promises.mkdir(distDir, {
  344. recursive: true
  345. });
  346. return true;
  347. } catch (err) {
  348. if ((0, _isError).default(err) && err.code === "EPERM") {
  349. return false;
  350. }
  351. throw err;
  352. }
  353. });
  354. if (!distDirCreated || !await (0, _isWriteable).isWriteable(distDir)) {
  355. throw new Error("> Build directory is not writeable. https://nextjs.org/docs/messages/build-dir-not-writeable");
  356. }
  357. if (config.cleanDistDir) {
  358. await (0, _recursiveDelete).recursiveDelete(distDir, /^cache/);
  359. }
  360. // Ensure commonjs handling is used for files in the distDir (generally .next)
  361. // Files outside of the distDir can be "type": "module"
  362. await _fs.promises.writeFile(_path.default.join(distDir, "package.json"), '{"type": "commonjs"}');
  363. // We need to write the manifest with rewrites before build
  364. // so serverless can import the manifest
  365. await nextBuildSpan.traceChild("write-routes-manifest").traceAsyncFn(()=>_fs.promises.writeFile(routesManifestPath, JSON.stringify(routesManifest), "utf8"));
  366. const serverDir = isLikeServerless ? _constants1.SERVERLESS_DIRECTORY : _constants1.SERVER_DIRECTORY;
  367. const manifestPath = _path.default.join(distDir, serverDir, _constants1.PAGES_MANIFEST);
  368. const requiredServerFiles = nextBuildSpan.traceChild("generate-required-server-files").traceFn(()=>({
  369. version: 1,
  370. config: {
  371. ...config,
  372. configFile: undefined,
  373. experimental: {
  374. ...config.experimental,
  375. trustHostHeader: ciEnvironment.hasNextSupport
  376. }
  377. },
  378. appDir: dir,
  379. files: [
  380. _constants1.ROUTES_MANIFEST,
  381. _path.default.relative(distDir, manifestPath),
  382. _constants1.BUILD_MANIFEST,
  383. _constants1.PRERENDER_MANIFEST,
  384. _path.default.join(_constants1.SERVER_DIRECTORY, _constants1.MIDDLEWARE_MANIFEST),
  385. ...hasServerComponents ? [
  386. _path.default.join(_constants1.SERVER_DIRECTORY, _constants1.FLIGHT_MANIFEST + ".js"),
  387. _path.default.join(_constants1.SERVER_DIRECTORY, _constants1.FLIGHT_MANIFEST + ".json"),
  388. _path.default.join(_constants1.SERVER_DIRECTORY, _constants1.FLIGHT_SERVER_CSS_MANIFEST + ".js"),
  389. _path.default.join(_constants1.SERVER_DIRECTORY, _constants1.FLIGHT_SERVER_CSS_MANIFEST + ".json"),
  390. ] : [],
  391. _constants1.REACT_LOADABLE_MANIFEST,
  392. config.optimizeFonts ? _path.default.join(serverDir, _constants1.FONT_MANIFEST) : null,
  393. _constants1.BUILD_ID_FILE,
  394. appDir ? _path.default.join(serverDir, _constants1.APP_PATHS_MANIFEST) : null,
  395. ].filter(_nonNullable.nonNullable).map((file)=>_path.default.join(config.distDir, file)),
  396. ignore: []
  397. }));
  398. let result = {
  399. warnings: [],
  400. errors: [],
  401. stats: []
  402. };
  403. let webpackBuildStart;
  404. let telemetryPlugin;
  405. await (async ()=>{
  406. var ref;
  407. // IIFE to isolate locals and avoid retaining memory too long
  408. const runWebpackSpan = nextBuildSpan.traceChild("run-webpack-compiler");
  409. const commonWebpackOptions = {
  410. buildId,
  411. config,
  412. hasReactRoot,
  413. pagesDir,
  414. reactProductionProfiling,
  415. rewrites,
  416. runWebpackSpan,
  417. target,
  418. appDir,
  419. middlewareMatchers: entrypoints.middlewareMatchers
  420. };
  421. const configs = await runWebpackSpan.traceChild("generate-webpack-config").traceAsyncFn(()=>Promise.all([
  422. (0, _webpackConfig).default(dir, {
  423. ...commonWebpackOptions,
  424. compilerType: _constants1.COMPILER_NAMES.client,
  425. entrypoints: entrypoints.client
  426. }),
  427. (0, _webpackConfig).default(dir, {
  428. ...commonWebpackOptions,
  429. compilerType: _constants1.COMPILER_NAMES.server,
  430. entrypoints: entrypoints.server
  431. }),
  432. (0, _webpackConfig).default(dir, {
  433. ...commonWebpackOptions,
  434. compilerType: _constants1.COMPILER_NAMES.edgeServer,
  435. entrypoints: entrypoints.edgeServer
  436. }),
  437. ]));
  438. const clientConfig = configs[0];
  439. if (clientConfig.optimization && (clientConfig.optimization.minimize !== true || clientConfig.optimization.minimizer && clientConfig.optimization.minimizer.length === 0)) {
  440. Log.warn(`Production code optimization has been disabled in your project. Read more: https://nextjs.org/docs/messages/minification-disabled`);
  441. }
  442. webpackBuildStart = process.hrtime();
  443. // We run client and server compilation separately to optimize for memory usage
  444. await runWebpackSpan.traceAsyncFn(async ()=>{
  445. // If we are under the serverless build, we will have to run the client
  446. // compiler first because the server compiler depends on the manifest
  447. // files that are created by the client compiler.
  448. // Otherwise, we run the server compilers first and then the client
  449. // compiler to track the boundary of server/client components.
  450. let clientResult = null;
  451. let serverResult = null;
  452. let edgeServerResult = null;
  453. if (isLikeServerless) {
  454. if (config.experimental.serverComponents) {
  455. throw new Error("Server Components are not supported in serverless mode.");
  456. }
  457. // Build client first
  458. clientResult = await (0, _compiler).runCompiler(clientConfig, {
  459. runWebpackSpan
  460. });
  461. // Only continue if there were no errors
  462. if (!clientResult.errors.length) {
  463. serverResult = await (0, _compiler).runCompiler(configs[1], {
  464. runWebpackSpan
  465. });
  466. edgeServerResult = configs[2] ? await (0, _compiler).runCompiler(configs[2], {
  467. runWebpackSpan
  468. }) : null;
  469. }
  470. } else {
  471. // During the server compilations, entries of client components will be
  472. // injected to this set and then will be consumed by the client compiler.
  473. _flightClientEntryPlugin.injectedClientEntries.clear();
  474. serverResult = await (0, _compiler).runCompiler(configs[1], {
  475. runWebpackSpan
  476. });
  477. edgeServerResult = configs[2] ? await (0, _compiler).runCompiler(configs[2], {
  478. runWebpackSpan
  479. }) : null;
  480. // Only continue if there were no errors
  481. if (!serverResult.errors.length && !(edgeServerResult == null ? void 0 : edgeServerResult.errors.length)) {
  482. _flightClientEntryPlugin.injectedClientEntries.forEach((value, key)=>{
  483. clientConfig.entry[key] = value;
  484. });
  485. clientResult = await (0, _compiler).runCompiler(clientConfig, {
  486. runWebpackSpan
  487. });
  488. }
  489. }
  490. result = {
  491. warnings: [].concat(clientResult == null ? void 0 : clientResult.warnings, serverResult == null ? void 0 : serverResult.warnings, edgeServerResult == null ? void 0 : edgeServerResult.warnings).filter(_nonNullable.nonNullable),
  492. errors: [].concat(clientResult == null ? void 0 : clientResult.errors, serverResult == null ? void 0 : serverResult.errors, edgeServerResult == null ? void 0 : edgeServerResult.errors).filter(_nonNullable.nonNullable),
  493. stats: [
  494. clientResult == null ? void 0 : clientResult.stats,
  495. serverResult == null ? void 0 : serverResult.stats,
  496. edgeServerResult == null ? void 0 : edgeServerResult.stats,
  497. ]
  498. };
  499. });
  500. result = nextBuildSpan.traceChild("format-webpack-messages").traceFn(()=>(0, _formatWebpackMessages).default(result, true));
  501. telemetryPlugin = (ref = clientConfig.plugins) == null ? void 0 : ref.find(isTelemetryPlugin);
  502. })();
  503. const webpackBuildEnd = process.hrtime(webpackBuildStart);
  504. if (buildSpinner) {
  505. buildSpinner.stopAndPersist();
  506. }
  507. if (result.errors.length > 0) {
  508. // Only keep the first few errors. Others are often indicative
  509. // of the same problem, but confuse the reader with noise.
  510. if (result.errors.length > 5) {
  511. result.errors.length = 5;
  512. }
  513. let error = result.errors.filter(Boolean).join("\n\n");
  514. console.error(_chalk.default.red("Failed to compile.\n"));
  515. if (error.indexOf("private-next-pages") > -1 && error.indexOf("does not contain a default export") > -1) {
  516. const page_name_regex = /'private-next-pages\/(?<page_name>[^']*)'/;
  517. const parsed = page_name_regex.exec(error);
  518. const page_name = parsed && parsed.groups && parsed.groups.page_name;
  519. throw new Error(`webpack build failed: found page without a React Component as default export in pages/${page_name}\n\nSee https://nextjs.org/docs/messages/page-without-valid-component for more info.`);
  520. }
  521. console.error(error);
  522. console.error();
  523. if (error.indexOf("private-next-pages") > -1 || error.indexOf("__next_polyfill__") > -1) {
  524. const err = new Error("webpack config.resolve.alias was incorrectly overridden. https://nextjs.org/docs/messages/invalid-resolve-alias");
  525. err.code = "INVALID_RESOLVE_ALIAS";
  526. throw err;
  527. }
  528. const err = new Error("Build failed because of webpack errors");
  529. err.code = "WEBPACK_ERRORS";
  530. throw err;
  531. } else {
  532. telemetry.record((0, _events).eventBuildCompleted(pagesPaths, {
  533. durationInSeconds: webpackBuildEnd[0]
  534. }));
  535. if (result.warnings.length > 0) {
  536. Log.warn("Compiled with warnings\n");
  537. console.warn(result.warnings.filter(Boolean).join("\n\n"));
  538. console.warn();
  539. } else {
  540. Log.info("Compiled successfully");
  541. }
  542. }
  543. const postCompileSpinner = (0, _spinner).default({
  544. prefixText: `${Log.prefixes.info} Collecting page data`
  545. });
  546. const buildManifestPath = _path.default.join(distDir, _constants1.BUILD_MANIFEST);
  547. const appBuildManifestPath = _path.default.join(distDir, _constants1.APP_BUILD_MANIFEST);
  548. const ssgPages = new Set();
  549. const ssgStaticFallbackPages = new Set();
  550. const ssgBlockingFallbackPages = new Set();
  551. const staticPages = new Set();
  552. const invalidPages = new Set();
  553. const hybridAmpPages = new Set();
  554. const serverPropsPages = new Set();
  555. const additionalSsgPaths = new Map();
  556. const additionalSsgPathsEncoded = new Map();
  557. const appStaticPaths = new Map();
  558. const appStaticPathsEncoded = new Map();
  559. const appNormalizedPaths = new Map();
  560. const appDynamicParamPaths = new Set();
  561. const appDefaultConfigs = new Map();
  562. const pageTraceIncludes = new Map();
  563. const pageTraceExcludes = new Map();
  564. const pageInfos = new Map();
  565. const pagesManifest = JSON.parse(await _fs.promises.readFile(manifestPath, "utf8"));
  566. const buildManifest = JSON.parse(await _fs.promises.readFile(buildManifestPath, "utf8"));
  567. const appBuildManifest = appDir ? JSON.parse(await _fs.promises.readFile(appBuildManifestPath, "utf8")) : undefined;
  568. const timeout = config.staticPageGenerationTimeout || 0;
  569. const sharedPool = config.experimental.sharedPool || false;
  570. const staticWorker = sharedPool ? require.resolve("./worker") : require.resolve("./utils");
  571. let infoPrinted = false;
  572. let appPathsManifest = {};
  573. const appPathRoutes = {};
  574. if (appDir) {
  575. appPathsManifest = JSON.parse(await _fs.promises.readFile(_path.default.join(distDir, serverDir, _constants1.APP_PATHS_MANIFEST), "utf8"));
  576. Object.keys(appPathsManifest).forEach((entry)=>{
  577. appPathRoutes[entry] = (0, _appPaths).normalizeAppPath(entry) || "/";
  578. });
  579. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.APP_PATH_ROUTES_MANIFEST), JSON.stringify(appPathRoutes, null, 2));
  580. }
  581. process.env.NEXT_PHASE = _constants1.PHASE_PRODUCTION_BUILD;
  582. const staticWorkers = new _worker.Worker(staticWorker, {
  583. timeout: timeout * 1000,
  584. onRestart: (method, [arg], attempts)=>{
  585. if (method === "exportPage") {
  586. const { path: pagePath } = arg;
  587. if (attempts >= 3) {
  588. throw new Error(`Static page generation for ${pagePath} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`);
  589. }
  590. Log.warn(`Restarted static page generation for ${pagePath} because it took more than ${timeout} seconds`);
  591. } else {
  592. const pagePath = arg;
  593. if (attempts >= 2) {
  594. throw new Error(`Collecting page data for ${pagePath} is still timing out after 2 attempts. See more info here https://nextjs.org/docs/messages/page-data-collection-timeout`);
  595. }
  596. Log.warn(`Restarted collecting page data for ${pagePath} because it took more than ${timeout} seconds`);
  597. }
  598. if (!infoPrinted) {
  599. Log.warn("See more info here https://nextjs.org/docs/messages/static-page-generation-timeout");
  600. infoPrinted = true;
  601. }
  602. },
  603. numWorkers: config.experimental.cpus,
  604. enableWorkerThreads: config.experimental.workerThreads,
  605. exposedMethods: sharedPool ? [
  606. "hasCustomGetInitialProps",
  607. "isPageStatic",
  608. "getNamedExports",
  609. "exportPage",
  610. ] : [
  611. "hasCustomGetInitialProps",
  612. "isPageStatic",
  613. "getNamedExports"
  614. ]
  615. });
  616. const analysisBegin = process.hrtime();
  617. const staticCheckSpan = nextBuildSpan.traceChild("static-check");
  618. const { customAppGetInitialProps , namedExports , isNextImageImported: isNextImageImported1 , hasSsrAmpPages: hasSsrAmpPages1 , hasNonStaticErrorPage , } = await staticCheckSpan.traceAsyncFn(async ()=>{
  619. const { configFileName , publicRuntimeConfig , serverRuntimeConfig } = config;
  620. const runtimeEnvConfig = {
  621. publicRuntimeConfig,
  622. serverRuntimeConfig
  623. };
  624. const nonStaticErrorPageSpan = staticCheckSpan.traceChild("check-static-error-page");
  625. const errorPageHasCustomGetInitialProps = nonStaticErrorPageSpan.traceAsyncFn(async ()=>hasCustomErrorPage && await staticWorkers.hasCustomGetInitialProps("/_error", distDir, isLikeServerless, runtimeEnvConfig, false));
  626. const errorPageStaticResult = nonStaticErrorPageSpan.traceAsyncFn(async ()=>{
  627. var ref, ref8;
  628. return hasCustomErrorPage && staticWorkers.isPageStatic({
  629. page: "/_error",
  630. distDir,
  631. serverless: isLikeServerless,
  632. configFileName,
  633. runtimeEnvConfig,
  634. httpAgentOptions: config.httpAgentOptions,
  635. locales: (ref = config.i18n) == null ? void 0 : ref.locales,
  636. defaultLocale: (ref8 = config.i18n) == null ? void 0 : ref8.defaultLocale,
  637. pageRuntime: config.experimental.runtime
  638. });
  639. });
  640. // we don't output _app in serverless mode so use _app export
  641. // from _error instead
  642. const appPageToCheck = isLikeServerless ? "/_error" : "/_app";
  643. const customAppGetInitialPropsPromise = staticWorkers.hasCustomGetInitialProps(appPageToCheck, distDir, isLikeServerless, runtimeEnvConfig, true);
  644. const namedExportsPromise = staticWorkers.getNamedExports(appPageToCheck, distDir, isLikeServerless, runtimeEnvConfig);
  645. // eslint-disable-next-line no-shadow
  646. let isNextImageImported;
  647. // eslint-disable-next-line no-shadow
  648. let hasSsrAmpPages = false;
  649. const computedManifestData = await (0, _utils2).computeFromManifest({
  650. build: buildManifest,
  651. app: appBuildManifest
  652. }, distDir, config.experimental.gzipSize);
  653. await Promise.all(Object.entries(pageKeys).reduce((acc, [key, files])=>{
  654. if (!files) {
  655. return acc;
  656. }
  657. const pageType = key;
  658. for (const page of files){
  659. acc.push({
  660. pageType,
  661. page
  662. });
  663. }
  664. return acc;
  665. }, []).map(({ pageType , page })=>{
  666. const checkPageSpan = staticCheckSpan.traceChild("check-page", {
  667. page
  668. });
  669. return checkPageSpan.traceAsyncFn(async ()=>{
  670. const actualPage = (0, _normalizePagePath).normalizePagePath(page);
  671. const [selfSize, allSize] = await (0, _utils2).getJsPageSizeInKb(pageType, actualPage, distDir, buildManifest, appBuildManifest, config.experimental.gzipSize, computedManifestData);
  672. let isSsg = false;
  673. let isStatic = false;
  674. let isServerComponent = false;
  675. let isHybridAmp = false;
  676. let ssgPageRoutes = null;
  677. let pagePath = "";
  678. if (pageType === "pages") {
  679. pagePath = pagesPaths.find((p)=>p.startsWith(actualPage + ".") || p.startsWith(actualPage + "/index.")) || "";
  680. }
  681. let originalAppPath;
  682. if (pageType === "app" && mappedAppPages) {
  683. for (const [originalPath, normalizedPath] of Object.entries(appPathRoutes)){
  684. if (normalizedPath === page) {
  685. pagePath = mappedAppPages[originalPath].replace(/^private-next-app-dir/, "");
  686. originalAppPath = originalPath;
  687. break;
  688. }
  689. }
  690. }
  691. const staticInfo = pagePath ? await (0, _getPageStaticInfo).getPageStaticInfo({
  692. pageFilePath: (0, _path).join((pageType === "pages" ? pagesDir : appDir) || "", pagePath),
  693. nextConfig: config
  694. }) : undefined;
  695. const pageRuntime = staticInfo == null ? void 0 : staticInfo.runtime;
  696. isServerComponent = pageType === "app" && (staticInfo == null ? void 0 : staticInfo.rsc) !== _constants1.RSC_MODULE_TYPES.client;
  697. if (!(0, _utils2).isReservedPage(page)) {
  698. try {
  699. let edgeInfo;
  700. if (pageRuntime === _constants.SERVER_RUNTIME.edge) {
  701. const manifest = require((0, _path).join(distDir, serverDir, _constants1.MIDDLEWARE_MANIFEST));
  702. const manifestKey = pageType === "pages" ? page : (0, _path).join(page, "page");
  703. edgeInfo = manifest.functions[manifestKey];
  704. }
  705. let isPageStaticSpan = checkPageSpan.traceChild("is-page-static");
  706. let workerResult = await isPageStaticSpan.traceAsyncFn(()=>{
  707. var ref, ref9;
  708. return staticWorkers.isPageStatic({
  709. page,
  710. originalAppPath,
  711. distDir,
  712. serverless: isLikeServerless,
  713. configFileName,
  714. runtimeEnvConfig,
  715. httpAgentOptions: config.httpAgentOptions,
  716. locales: (ref = config.i18n) == null ? void 0 : ref.locales,
  717. defaultLocale: (ref9 = config.i18n) == null ? void 0 : ref9.defaultLocale,
  718. parentId: isPageStaticSpan.id,
  719. pageRuntime,
  720. edgeInfo,
  721. pageType,
  722. hasServerComponents
  723. });
  724. });
  725. if (pageType === "app" && originalAppPath) {
  726. appNormalizedPaths.set(originalAppPath, page);
  727. // TODO-APP: handle prerendering with edge
  728. // runtime
  729. if (pageRuntime === "experimental-edge") {
  730. return;
  731. }
  732. if (workerResult.encodedPrerenderRoutes && workerResult.prerenderRoutes) {
  733. appStaticPaths.set(originalAppPath, workerResult.prerenderRoutes);
  734. appStaticPathsEncoded.set(originalAppPath, workerResult.encodedPrerenderRoutes);
  735. }
  736. if (!(0, _utils).isDynamicRoute(page)) {
  737. appStaticPaths.set(originalAppPath, [
  738. page
  739. ]);
  740. appStaticPathsEncoded.set(originalAppPath, [
  741. page
  742. ]);
  743. }
  744. if (workerResult.prerenderFallback) {
  745. // whether or not to allow requests for paths not
  746. // returned from generateStaticParams
  747. appDynamicParamPaths.add(originalAppPath);
  748. }
  749. appDefaultConfigs.set(originalAppPath, workerResult.appConfig || {});
  750. return;
  751. }
  752. if (pageRuntime === _constants.SERVER_RUNTIME.edge) {
  753. if (workerResult.hasStaticProps) {
  754. console.warn(`"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}`);
  755. }
  756. // TODO: add handling for statically rendering edge
  757. // pages and allow edge with Prerender outputs
  758. workerResult.isStatic = false;
  759. workerResult.hasStaticProps = false;
  760. }
  761. if (config.outputFileTracing) {
  762. pageTraceIncludes.set(page, workerResult.traceIncludes || []);
  763. pageTraceExcludes.set(page, workerResult.traceExcludes || []);
  764. }
  765. if (workerResult.isStatic === false && (workerResult.isHybridAmp || workerResult.isAmpOnly)) {
  766. hasSsrAmpPages = true;
  767. }
  768. if (workerResult.isHybridAmp) {
  769. isHybridAmp = true;
  770. hybridAmpPages.add(page);
  771. }
  772. if (workerResult.isNextImageImported) {
  773. isNextImageImported = true;
  774. }
  775. if (workerResult.hasStaticProps) {
  776. ssgPages.add(page);
  777. isSsg = true;
  778. if (workerResult.prerenderRoutes && workerResult.encodedPrerenderRoutes) {
  779. additionalSsgPaths.set(page, workerResult.prerenderRoutes);
  780. additionalSsgPathsEncoded.set(page, workerResult.encodedPrerenderRoutes);
  781. ssgPageRoutes = workerResult.prerenderRoutes;
  782. }
  783. if (workerResult.prerenderFallback === "blocking") {
  784. ssgBlockingFallbackPages.add(page);
  785. } else if (workerResult.prerenderFallback === true) {
  786. ssgStaticFallbackPages.add(page);
  787. }
  788. } else if (workerResult.hasServerProps) {
  789. serverPropsPages.add(page);
  790. } else if (workerResult.isStatic && !isServerComponent && await customAppGetInitialPropsPromise === false) {
  791. staticPages.add(page);
  792. isStatic = true;
  793. } else if (isServerComponent) {
  794. // This is a static server component page that doesn't have
  795. // gSP or gSSP. We still treat it as a SSG page.
  796. ssgPages.add(page);
  797. isSsg = true;
  798. }
  799. if (hasPages404 && page === "/404") {
  800. if (!workerResult.isStatic && !workerResult.hasStaticProps) {
  801. throw new Error(`\`pages/404\` ${_constants.STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`);
  802. }
  803. // we need to ensure the 404 lambda is present since we use
  804. // it when _app has getInitialProps
  805. if (await customAppGetInitialPropsPromise && !workerResult.hasStaticProps) {
  806. staticPages.delete(page);
  807. }
  808. }
  809. if (_constants1.STATIC_STATUS_PAGES.includes(page) && !workerResult.isStatic && !workerResult.hasStaticProps) {
  810. throw new Error(`\`pages${page}\` ${_constants.STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`);
  811. }
  812. } catch (err) {
  813. if (!(0, _isError).default(err) || err.message !== "INVALID_DEFAULT_EXPORT") throw err;
  814. invalidPages.add(page);
  815. }
  816. }
  817. pageInfos.set(page, {
  818. size: selfSize,
  819. totalSize: allSize,
  820. static: isStatic,
  821. isSsg,
  822. isHybridAmp,
  823. ssgPageRoutes,
  824. initialRevalidateSeconds: false,
  825. runtime: pageRuntime,
  826. pageDuration: undefined,
  827. ssgPageDurations: undefined
  828. });
  829. });
  830. }));
  831. const errorPageResult = await errorPageStaticResult;
  832. const nonStaticErrorPage = await errorPageHasCustomGetInitialProps || errorPageResult && errorPageResult.hasServerProps;
  833. const returnValue = {
  834. customAppGetInitialProps: await customAppGetInitialPropsPromise,
  835. namedExports: await namedExportsPromise,
  836. isNextImageImported,
  837. hasSsrAmpPages,
  838. hasNonStaticErrorPage: nonStaticErrorPage
  839. };
  840. if (!sharedPool) staticWorkers.end();
  841. return returnValue;
  842. });
  843. if (customAppGetInitialProps) {
  844. console.warn(_chalk.default.bold.yellow(`Warning: `) + _chalk.default.yellow(`You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`. This does not opt-out pages with \`getStaticProps\``));
  845. console.warn("Read more: https://nextjs.org/docs/messages/opt-out-auto-static-optimization\n");
  846. }
  847. if (!hasSsrAmpPages1) {
  848. requiredServerFiles.ignore.push(_path.default.relative(dir, _path.default.join(_path.default.dirname(require.resolve("next/dist/compiled/@ampproject/toolbox-optimizer")), "**/*")));
  849. }
  850. if (config.outputFileTracing) {
  851. const { nodeFileTrace } = require("next/dist/compiled/@vercel/nft");
  852. const includeExcludeSpan = nextBuildSpan.traceChild("apply-include-excludes");
  853. await includeExcludeSpan.traceAsyncFn(async ()=>{
  854. const globOrig = require("next/dist/compiled/glob");
  855. const glob = (pattern)=>{
  856. return new Promise((resolve, reject)=>{
  857. globOrig(pattern, {
  858. cwd: dir
  859. }, (err, files)=>{
  860. if (err) {
  861. return reject(err);
  862. }
  863. resolve(files);
  864. });
  865. });
  866. };
  867. for (let page of pageKeys.pages){
  868. await includeExcludeSpan.traceChild("include-exclude", {
  869. page
  870. }).traceAsyncFn(async ()=>{
  871. const includeGlobs = pageTraceIncludes.get(page);
  872. const excludeGlobs = pageTraceExcludes.get(page);
  873. page = (0, _normalizePagePath).normalizePagePath(page);
  874. if (!(includeGlobs == null ? void 0 : includeGlobs.length) && !(excludeGlobs == null ? void 0 : excludeGlobs.length)) {
  875. return;
  876. }
  877. const traceFile = _path.default.join(distDir, "server/pages", `${page}.js.nft.json`);
  878. const pageDir = _path.default.dirname(traceFile);
  879. const traceContent = JSON.parse(await _fs.promises.readFile(traceFile, "utf8"));
  880. let includes = [];
  881. if (includeGlobs == null ? void 0 : includeGlobs.length) {
  882. for (const includeGlob of includeGlobs){
  883. const results = await glob(includeGlob);
  884. includes.push(...results.map((file)=>{
  885. return _path.default.relative(pageDir, _path.default.join(dir, file));
  886. }));
  887. }
  888. }
  889. const combined = new Set([
  890. ...traceContent.files,
  891. ...includes
  892. ]);
  893. if (excludeGlobs == null ? void 0 : excludeGlobs.length) {
  894. const resolvedGlobs = excludeGlobs.map((exclude)=>_path.default.join(dir, exclude));
  895. combined.forEach((file)=>{
  896. if ((0, _micromatch).isMatch(_path.default.join(pageDir, file), resolvedGlobs)) {
  897. combined.delete(file);
  898. }
  899. });
  900. }
  901. await _fs.promises.writeFile(traceFile, JSON.stringify({
  902. version: traceContent.version,
  903. files: [
  904. ...combined
  905. ]
  906. }));
  907. });
  908. }
  909. });
  910. // TODO: move this inside of webpack so it can be cached
  911. // between builds. Should only need to be re-run on lockfile change
  912. await nextBuildSpan.traceChild("trace-next-server").traceAsyncFn(async ()=>{
  913. let cacheKey;
  914. // consider all lockFiles in tree in case user accidentally
  915. // has both package-lock.json and yarn.lock
  916. const lockFiles = (await Promise.all([
  917. "package-lock.json",
  918. "yarn.lock",
  919. "pnpm-lock.yaml"
  920. ].map((file)=>(0, _findUp).default(file, {
  921. cwd: dir
  922. })))).filter(Boolean)// TypeScript doesn't like this filter
  923. ;
  924. const nextServerTraceOutput = _path.default.join(distDir, "next-server.js.nft.json");
  925. const cachedTracePath = _path.default.join(distDir, "cache/next-server.js.nft.json");
  926. if (lockFiles.length > 0) {
  927. const cacheHash = require("crypto").createHash("sha256");
  928. cacheHash.update(require("next/package").version);
  929. cacheHash.update(hasSsrAmpPages1 + "");
  930. cacheHash.update(ciEnvironment.hasNextSupport + "");
  931. await Promise.all(lockFiles.map(async (lockFile)=>{
  932. cacheHash.update(await _fs.promises.readFile(lockFile));
  933. }));
  934. cacheKey = cacheHash.digest("hex");
  935. try {
  936. const existingTrace = JSON.parse(await _fs.promises.readFile(cachedTracePath, "utf8"));
  937. if (existingTrace.cacheKey === cacheKey) {
  938. await _fs.promises.copyFile(cachedTracePath, nextServerTraceOutput);
  939. return;
  940. }
  941. } catch (_) {}
  942. }
  943. const root = config.experimental.outputFileTracingRoot || dir;
  944. const toTrace = [
  945. require.resolve("next/dist/server/next-server")
  946. ];
  947. // ensure we trace any dependencies needed for custom
  948. // incremental cache handler
  949. if (config.experimental.incrementalCacheHandlerPath) {
  950. toTrace.push(require.resolve(config.experimental.incrementalCacheHandlerPath));
  951. }
  952. const serverResult = await nodeFileTrace(toTrace, {
  953. base: root,
  954. processCwd: dir,
  955. ignore: [
  956. "**/next/dist/pages/**/*",
  957. "**/next/dist/compiled/webpack/(bundle4|bundle5).js",
  958. "**/node_modules/webpack5/**/*",
  959. "**/next/dist/server/lib/squoosh/**/*.wasm",
  960. ...ciEnvironment.hasNextSupport ? [
  961. // only ignore image-optimizer code when
  962. // this is being handled outside of next-server
  963. "**/next/dist/server/image-optimizer.js",
  964. "**/node_modules/sharp/**/*",
  965. ] : [],
  966. ...!hasSsrAmpPages1 ? [
  967. "**/next/dist/compiled/@ampproject/toolbox-optimizer/**/*"
  968. ] : [],
  969. ]
  970. });
  971. const tracedFiles = new Set();
  972. serverResult.fileList.forEach((file)=>{
  973. tracedFiles.add(_path.default.relative(distDir, _path.default.join(root, file)).replace(/\\/g, "/"));
  974. });
  975. await _fs.promises.writeFile(nextServerTraceOutput, JSON.stringify({
  976. version: 1,
  977. cacheKey,
  978. files: [
  979. ...tracedFiles
  980. ]
  981. }));
  982. await _fs.promises.unlink(cachedTracePath).catch(()=>{});
  983. await _fs.promises.copyFile(nextServerTraceOutput, cachedTracePath).catch(()=>{});
  984. });
  985. }
  986. if (serverPropsPages.size > 0 || ssgPages.size > 0) {
  987. // We update the routes manifest after the build with the
  988. // data routes since we can't determine these until after build
  989. routesManifest.dataRoutes = (0, _utils).getSortedRoutes([
  990. ...serverPropsPages,
  991. ...ssgPages,
  992. ]).map((page)=>{
  993. const pagePath = (0, _normalizePagePath).normalizePagePath(page);
  994. const dataRoute = _path.default.posix.join("/_next/data", buildId, `${pagePath}.json`);
  995. let dataRouteRegex;
  996. let namedDataRouteRegex;
  997. let routeKeys;
  998. if ((0, _utils).isDynamicRoute(page)) {
  999. const routeRegex = (0, _routeRegex).getNamedRouteRegex(dataRoute.replace(/\.json$/, ""));
  1000. dataRouteRegex = (0, _loadCustomRoutes).normalizeRouteRegex(routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`));
  1001. namedDataRouteRegex = routeRegex.namedRegex.replace(/\(\?:\/\)\?\$$/, `\\.json$`);
  1002. routeKeys = routeRegex.routeKeys;
  1003. } else {
  1004. dataRouteRegex = (0, _loadCustomRoutes).normalizeRouteRegex(new RegExp(`^${_path.default.posix.join("/_next/data", (0, _escapeRegexp).escapeStringRegexp(buildId), `${pagePath}.json`)}$`).source);
  1005. }
  1006. return {
  1007. page,
  1008. routeKeys,
  1009. dataRouteRegex,
  1010. namedDataRouteRegex
  1011. };
  1012. });
  1013. await _fs.promises.writeFile(routesManifestPath, JSON.stringify(routesManifest), "utf8");
  1014. }
  1015. // Since custom _app.js can wrap the 404 page we have to opt-out of static optimization if it has getInitialProps
  1016. // Only export the static 404 when there is no /_error present
  1017. const useStatic404 = !customAppGetInitialProps && (!hasNonStaticErrorPage || hasPages404);
  1018. if (invalidPages.size > 0) {
  1019. const err = new Error(`Build optimization failed: found page${invalidPages.size === 1 ? "" : "s"} without a React Component as default export in \n${[
  1020. ...invalidPages
  1021. ].map((pg)=>`pages${pg}`).join("\n")}\n\nSee https://nextjs.org/docs/messages/page-without-valid-component for more info.\n`);
  1022. err.code = "BUILD_OPTIMIZATION_FAILED";
  1023. throw err;
  1024. }
  1025. await (0, _writeBuildId).writeBuildId(distDir, buildId);
  1026. if (config.experimental.optimizeCss) {
  1027. const globOrig = require("next/dist/compiled/glob");
  1028. const cssFilePaths = await new Promise((resolve, reject)=>{
  1029. globOrig("**/*.css", {
  1030. cwd: (0, _path).join(distDir, "static")
  1031. }, (err, files)=>{
  1032. if (err) {
  1033. return reject(err);
  1034. }
  1035. resolve(files);
  1036. });
  1037. });
  1038. requiredServerFiles.files.push(...cssFilePaths.map((filePath)=>_path.default.join(config.distDir, "static", filePath)));
  1039. }
  1040. const features = [
  1041. {
  1042. featureName: "experimental/optimizeCss",
  1043. invocationCount: config.experimental.optimizeCss ? 1 : 0
  1044. },
  1045. {
  1046. featureName: "experimental/nextScriptWorkers",
  1047. invocationCount: config.experimental.nextScriptWorkers ? 1 : 0
  1048. },
  1049. {
  1050. featureName: "optimizeFonts",
  1051. invocationCount: config.optimizeFonts ? 1 : 0
  1052. },
  1053. ];
  1054. telemetry.record(features.map((feature)=>{
  1055. return {
  1056. eventName: _events.EVENT_BUILD_FEATURE_USAGE,
  1057. payload: feature
  1058. };
  1059. }));
  1060. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.SERVER_FILES_MANIFEST), JSON.stringify(requiredServerFiles), "utf8");
  1061. const middlewareManifest = JSON.parse(await _fs.promises.readFile(_path.default.join(distDir, serverDir, _constants1.MIDDLEWARE_MANIFEST), "utf8"));
  1062. const outputFileTracingRoot = config.experimental.outputFileTracingRoot || dir;
  1063. if (config.output === "standalone") {
  1064. await nextBuildSpan.traceChild("copy-traced-files").traceAsyncFn(async ()=>{
  1065. await (0, _utils2).copyTracedFiles(dir, distDir, pageKeys.pages, outputFileTracingRoot, requiredServerFiles.config, middlewareManifest);
  1066. });
  1067. }
  1068. const finalPrerenderRoutes = {};
  1069. const finalDynamicRoutes = {};
  1070. const tbdPrerenderRoutes = [];
  1071. let ssgNotFoundPaths = [];
  1072. if (postCompileSpinner) postCompileSpinner.stopAndPersist();
  1073. const { i18n } = config;
  1074. const usedStaticStatusPages = _constants1.STATIC_STATUS_PAGES.filter((page)=>mappedPages[page] && mappedPages[page].startsWith("private-next-pages"));
  1075. usedStaticStatusPages.forEach((page)=>{
  1076. if (!ssgPages.has(page) && !customAppGetInitialProps) {
  1077. staticPages.add(page);
  1078. }
  1079. });
  1080. const hasPages500 = usedStaticStatusPages.includes("/500");
  1081. const useDefaultStatic500 = !hasPages500 && !hasNonStaticErrorPage && !customAppGetInitialProps;
  1082. const combinedPages = [
  1083. ...staticPages,
  1084. ...ssgPages
  1085. ];
  1086. // we need to trigger automatic exporting when we have
  1087. // - static 404/500
  1088. // - getStaticProps paths
  1089. // - experimental app is enabled
  1090. if (combinedPages.length > 0 || useStatic404 || useDefaultStatic500 || config.experimental.appDir) {
  1091. const staticGenerationSpan = nextBuildSpan.traceChild("static-generation");
  1092. await staticGenerationSpan.traceAsyncFn(async ()=>{
  1093. (0, _utils2).detectConflictingPaths([
  1094. ...combinedPages,
  1095. ...pageKeys.pages.filter((page)=>!combinedPages.includes(page)),
  1096. ], ssgPages, additionalSsgPaths);
  1097. const exportApp = require("../export").default;
  1098. const exportOptions = {
  1099. silent: false,
  1100. buildExport: true,
  1101. threads: config.experimental.cpus,
  1102. pages: combinedPages,
  1103. outdir: _path.default.join(distDir, "export"),
  1104. statusMessage: "Generating static pages",
  1105. exportPageWorker: sharedPool ? staticWorkers.exportPage.bind(staticWorkers) : undefined,
  1106. endWorker: sharedPool ? async ()=>{
  1107. await staticWorkers.end();
  1108. } : undefined,
  1109. appPaths
  1110. };
  1111. const exportConfig = {
  1112. ...config,
  1113. initialPageRevalidationMap: {},
  1114. pageDurationMap: {},
  1115. ssgNotFoundPaths: [],
  1116. // Default map will be the collection of automatic statically exported
  1117. // pages and incremental pages.
  1118. // n.b. we cannot handle this above in combinedPages because the dynamic
  1119. // page must be in the `pages` array, but not in the mapping.
  1120. exportPathMap: (defaultMap)=>{
  1121. // Dynamically routed pages should be prerendered to be used as
  1122. // a client-side skeleton (fallback) while data is being fetched.
  1123. // This ensures the end-user never sees a 500 or slow response from the
  1124. // server.
  1125. //
  1126. // Note: prerendering disables automatic static optimization.
  1127. ssgPages.forEach((page)=>{
  1128. if ((0, _utils).isDynamicRoute(page)) {
  1129. tbdPrerenderRoutes.push(page);
  1130. if (ssgStaticFallbackPages.has(page)) {
  1131. // Override the rendering for the dynamic page to be treated as a
  1132. // fallback render.
  1133. if (i18n) {
  1134. defaultMap[`/${i18n.defaultLocale}${page}`] = {
  1135. page,
  1136. query: {
  1137. __nextFallback: true
  1138. }
  1139. };
  1140. } else {
  1141. defaultMap[page] = {
  1142. page,
  1143. query: {
  1144. __nextFallback: true
  1145. }
  1146. };
  1147. }
  1148. } else {
  1149. // Remove dynamically routed pages from the default path map when
  1150. // fallback behavior is disabled.
  1151. delete defaultMap[page];
  1152. }
  1153. }
  1154. });
  1155. // Append the "well-known" routes we should prerender for, e.g. blog
  1156. // post slugs.
  1157. additionalSsgPaths.forEach((routes, page)=>{
  1158. const encodedRoutes = additionalSsgPathsEncoded.get(page);
  1159. routes.forEach((route, routeIdx)=>{
  1160. defaultMap[route] = {
  1161. page,
  1162. query: {
  1163. __nextSsgPath: encodedRoutes == null ? void 0 : encodedRoutes[routeIdx]
  1164. }
  1165. };
  1166. });
  1167. });
  1168. if (useStatic404) {
  1169. defaultMap["/404"] = {
  1170. page: hasPages404 ? "/404" : "/_error"
  1171. };
  1172. }
  1173. if (useDefaultStatic500) {
  1174. defaultMap["/500"] = {
  1175. page: "/_error"
  1176. };
  1177. }
  1178. // TODO: output manifest specific to app paths and their
  1179. // revalidate periods and dynamicParams settings
  1180. appStaticPaths.forEach((routes, originalAppPath)=>{
  1181. const encodedRoutes = appStaticPathsEncoded.get(originalAppPath);
  1182. routes.forEach((route, routeIdx)=>{
  1183. defaultMap[route] = {
  1184. page: originalAppPath,
  1185. query: {
  1186. __nextSsgPath: encodedRoutes == null ? void 0 : encodedRoutes[routeIdx]
  1187. },
  1188. _isAppDir: true
  1189. };
  1190. });
  1191. });
  1192. if (i18n) {
  1193. for (const page of [
  1194. ...staticPages,
  1195. ...ssgPages,
  1196. ...useStatic404 ? [
  1197. "/404"
  1198. ] : [],
  1199. ...useDefaultStatic500 ? [
  1200. "/500"
  1201. ] : [],
  1202. ]){
  1203. const isSsg = ssgPages.has(page);
  1204. const isDynamic = (0, _utils).isDynamicRoute(page);
  1205. const isFallback = isSsg && ssgStaticFallbackPages.has(page);
  1206. for (const locale of i18n.locales){
  1207. var ref;
  1208. // skip fallback generation for SSG pages without fallback mode
  1209. if (isSsg && isDynamic && !isFallback) continue;
  1210. const outputPath = `/${locale}${page === "/" ? "" : page}`;
  1211. defaultMap[outputPath] = {
  1212. page: ((ref = defaultMap[page]) == null ? void 0 : ref.page) || page,
  1213. query: {
  1214. __nextLocale: locale
  1215. }
  1216. };
  1217. if (isFallback) {
  1218. defaultMap[outputPath].query.__nextFallback = true;
  1219. }
  1220. }
  1221. if (isSsg) {
  1222. // remove non-locale prefixed variant from defaultMap
  1223. delete defaultMap[page];
  1224. }
  1225. }
  1226. }
  1227. return defaultMap;
  1228. }
  1229. };
  1230. await exportApp(dir, exportOptions, nextBuildSpan, exportConfig);
  1231. const postBuildSpinner = (0, _spinner).default({
  1232. prefixText: `${Log.prefixes.info} Finalizing page optimization`
  1233. });
  1234. ssgNotFoundPaths = exportConfig.ssgNotFoundPaths;
  1235. // remove server bundles that were exported
  1236. for (const page2 of staticPages){
  1237. const serverBundle = (0, _require).getPagePath(page2, distDir, isLikeServerless);
  1238. await _fs.promises.unlink(serverBundle);
  1239. }
  1240. for (const [originalAppPath1, routes1] of appStaticPaths){
  1241. const page = appNormalizedPaths.get(originalAppPath1) || "";
  1242. const appConfig = appDefaultConfigs.get(originalAppPath1) || {};
  1243. let hasDynamicData = appConfig.revalidate === 0;
  1244. routes1.forEach((route)=>{
  1245. let revalidate = exportConfig.initialPageRevalidationMap[route];
  1246. if (typeof revalidate === "undefined") {
  1247. revalidate = typeof appConfig.revalidate !== "undefined" ? appConfig.revalidate : false;
  1248. }
  1249. if (revalidate !== 0) {
  1250. const normalizedRoute = (0, _normalizePagePath).normalizePagePath(route);
  1251. const dataRoute = _path.default.posix.join(`${normalizedRoute}.rsc`);
  1252. finalPrerenderRoutes[route] = {
  1253. initialRevalidateSeconds: revalidate,
  1254. srcRoute: page,
  1255. dataRoute
  1256. };
  1257. } else {
  1258. hasDynamicData = true;
  1259. }
  1260. });
  1261. if (!hasDynamicData && (0, _utils).isDynamicRoute(originalAppPath1)) {
  1262. const normalizedRoute = (0, _normalizePagePath).normalizePagePath(page);
  1263. const dataRoute = _path.default.posix.join(`${normalizedRoute}.rsc`);
  1264. // TODO: create a separate manifest to allow enforcing
  1265. // dynamicParams for non-static paths?
  1266. finalDynamicRoutes[page] = {
  1267. routeRegex: (0, _loadCustomRoutes).normalizeRouteRegex((0, _routeRegex).getNamedRouteRegex(page).re.source),
  1268. dataRoute,
  1269. // if dynamicParams are enabled treat as fallback:
  1270. // 'blocking' if not it's fallback: false
  1271. fallback: appDynamicParamPaths.has(originalAppPath1) ? null : false,
  1272. dataRouteRegex: (0, _loadCustomRoutes).normalizeRouteRegex((0, _routeRegex).getNamedRouteRegex(dataRoute.replace(/\.rsc$/, "")).re.source.replace(/\(\?:\\\/\)\?\$$/, "\\.rsc$"))
  1273. };
  1274. }
  1275. }
  1276. const moveExportedPage = async (originPage, page, file, isSsg, ext, additionalSsgFile = false)=>{
  1277. return staticGenerationSpan.traceChild("move-exported-page").traceAsyncFn(async ()=>{
  1278. file = `${file}.${ext}`;
  1279. const orig = _path.default.join(exportOptions.outdir, file);
  1280. const pagePath = (0, _require).getPagePath(originPage, distDir, isLikeServerless);
  1281. const relativeDest = _path.default.relative(_path.default.join(distDir, serverDir), _path.default.join(_path.default.join(pagePath, // strip leading / and then recurse number of nested dirs
  1282. // to place from base folder
  1283. originPage.slice(1).split("/").map(()=>"..").join("/")), file)).replace(/\\/g, "/");
  1284. if (!isSsg && !// don't add static status page to manifest if it's
  1285. // the default generated version e.g. no pages/500
  1286. (_constants1.STATIC_STATUS_PAGES.includes(page) && !usedStaticStatusPages.includes(page))) {
  1287. pagesManifest[page] = relativeDest;
  1288. }
  1289. const dest = _path.default.join(distDir, serverDir, relativeDest);
  1290. const isNotFound = ssgNotFoundPaths.includes(page);
  1291. // for SSG files with i18n the non-prerendered variants are
  1292. // output with the locale prefixed so don't attempt moving
  1293. // without the prefix
  1294. if ((!i18n || additionalSsgFile) && !isNotFound) {
  1295. await _fs.promises.mkdir(_path.default.dirname(dest), {
  1296. recursive: true
  1297. });
  1298. await _fs.promises.rename(orig, dest);
  1299. } else if (i18n && !isSsg) {
  1300. // this will be updated with the locale prefixed variant
  1301. // since all files are output with the locale prefix
  1302. delete pagesManifest[page];
  1303. }
  1304. if (i18n) {
  1305. if (additionalSsgFile) return;
  1306. for (const locale of i18n.locales){
  1307. const curPath = `/${locale}${page === "/" ? "" : page}`;
  1308. const localeExt = page === "/" ? _path.default.extname(file) : "";
  1309. const relativeDestNoPages = relativeDest.slice("pages/".length);
  1310. if (isSsg && ssgNotFoundPaths.includes(curPath)) {
  1311. continue;
  1312. }
  1313. const updatedRelativeDest = _path.default.join("pages", locale + localeExt, // if it's the top-most index page we want it to be locale.EXT
  1314. // instead of locale/index.html
  1315. page === "/" ? "" : relativeDestNoPages).replace(/\\/g, "/");
  1316. const updatedOrig = _path.default.join(exportOptions.outdir, locale + localeExt, page === "/" ? "" : file);
  1317. const updatedDest = _path.default.join(distDir, serverDir, updatedRelativeDest);
  1318. if (!isSsg) {
  1319. pagesManifest[curPath] = updatedRelativeDest;
  1320. }
  1321. await _fs.promises.mkdir(_path.default.dirname(updatedDest), {
  1322. recursive: true
  1323. });
  1324. await _fs.promises.rename(updatedOrig, updatedDest);
  1325. }
  1326. }
  1327. });
  1328. };
  1329. // Only move /404 to /404 when there is no custom 404 as in that case we don't know about the 404 page
  1330. if (!hasPages404 && useStatic404) {
  1331. await moveExportedPage("/_error", "/404", "/404", false, "html");
  1332. }
  1333. if (useDefaultStatic500) {
  1334. await moveExportedPage("/_error", "/500", "/500", false, "html");
  1335. }
  1336. for (const page1 of combinedPages){
  1337. const isSsg = ssgPages.has(page1);
  1338. const isStaticSsgFallback = ssgStaticFallbackPages.has(page1);
  1339. const isDynamic = (0, _utils).isDynamicRoute(page1);
  1340. const hasAmp = hybridAmpPages.has(page1);
  1341. const file = (0, _normalizePagePath).normalizePagePath(page1);
  1342. const pageInfo = pageInfos.get(page1);
  1343. const durationInfo = exportConfig.pageDurationMap[page1];
  1344. if (pageInfo && durationInfo) {
  1345. // Set Build Duration
  1346. if (pageInfo.ssgPageRoutes) {
  1347. pageInfo.ssgPageDurations = pageInfo.ssgPageRoutes.map((pagePath)=>durationInfo[pagePath]);
  1348. }
  1349. pageInfo.pageDuration = durationInfo[page1];
  1350. }
  1351. // The dynamic version of SSG pages are only prerendered if the
  1352. // fallback is enabled. Below, we handle the specific prerenders
  1353. // of these.
  1354. const hasHtmlOutput = !(isSsg && isDynamic && !isStaticSsgFallback);
  1355. if (hasHtmlOutput) {
  1356. await moveExportedPage(page1, page1, file, isSsg, "html");
  1357. }
  1358. if (hasAmp && (!isSsg || isSsg && !isDynamic)) {
  1359. const ampPage = `${file}.amp`;
  1360. await moveExportedPage(page1, ampPage, ampPage, isSsg, "html");
  1361. if (isSsg) {
  1362. await moveExportedPage(page1, ampPage, ampPage, isSsg, "json");
  1363. }
  1364. }
  1365. if (isSsg) {
  1366. // For a non-dynamic SSG page, we must copy its data file
  1367. // from export, we already moved the HTML file above
  1368. if (!isDynamic) {
  1369. await moveExportedPage(page1, page1, file, isSsg, "json");
  1370. if (i18n) {
  1371. // TODO: do we want to show all locale variants in build output
  1372. for (const locale of i18n.locales){
  1373. const localePage = `/${locale}${page1 === "/" ? "" : page1}`;
  1374. finalPrerenderRoutes[localePage] = {
  1375. initialRevalidateSeconds: exportConfig.initialPageRevalidationMap[localePage],
  1376. srcRoute: null,
  1377. dataRoute: _path.default.posix.join("/_next/data", buildId, `${file}.json`)
  1378. };
  1379. }
  1380. } else {
  1381. finalPrerenderRoutes[page1] = {
  1382. initialRevalidateSeconds: exportConfig.initialPageRevalidationMap[page1],
  1383. srcRoute: null,
  1384. dataRoute: _path.default.posix.join("/_next/data", buildId, `${file}.json`)
  1385. };
  1386. }
  1387. // Set Page Revalidation Interval
  1388. if (pageInfo) {
  1389. pageInfo.initialRevalidateSeconds = exportConfig.initialPageRevalidationMap[page1];
  1390. }
  1391. } else {
  1392. // For a dynamic SSG page, we did not copy its data exports and only
  1393. // copy the fallback HTML file (if present).
  1394. // We must also copy specific versions of this page as defined by
  1395. // `getStaticPaths` (additionalSsgPaths).
  1396. const extraRoutes = additionalSsgPaths.get(page1) || [];
  1397. for (const route of extraRoutes){
  1398. const pageFile = (0, _normalizePagePath).normalizePagePath(route);
  1399. await moveExportedPage(page1, route, pageFile, isSsg, "html", true);
  1400. await moveExportedPage(page1, route, pageFile, isSsg, "json", true);
  1401. if (hasAmp) {
  1402. const ampPage = `${pageFile}.amp`;
  1403. await moveExportedPage(page1, ampPage, ampPage, isSsg, "html", true);
  1404. await moveExportedPage(page1, ampPage, ampPage, isSsg, "json", true);
  1405. }
  1406. finalPrerenderRoutes[route] = {
  1407. initialRevalidateSeconds: exportConfig.initialPageRevalidationMap[route],
  1408. srcRoute: page1,
  1409. dataRoute: _path.default.posix.join("/_next/data", buildId, `${(0, _normalizePagePath).normalizePagePath(route)}.json`)
  1410. };
  1411. // Set route Revalidation Interval
  1412. if (pageInfo) {
  1413. pageInfo.initialRevalidateSeconds = exportConfig.initialPageRevalidationMap[route];
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. // remove temporary export folder
  1420. await (0, _recursiveDelete).recursiveDelete(exportOptions.outdir);
  1421. await _fs.promises.rmdir(exportOptions.outdir);
  1422. await _fs.promises.writeFile(manifestPath, JSON.stringify(pagesManifest, null, 2), "utf8");
  1423. if (postBuildSpinner) postBuildSpinner.stopAndPersist();
  1424. console.log();
  1425. });
  1426. }
  1427. // ensure the worker is not left hanging
  1428. staticWorkers.close();
  1429. const analysisEnd = process.hrtime(analysisBegin);
  1430. var ref5;
  1431. telemetry.record((0, _events).eventBuildOptimize(pagesPaths, {
  1432. durationInSeconds: analysisEnd[0],
  1433. staticPageCount: staticPages.size,
  1434. staticPropsPageCount: ssgPages.size,
  1435. serverPropsPageCount: serverPropsPages.size,
  1436. ssrPageCount: pagesPaths.length - (staticPages.size + ssgPages.size + serverPropsPages.size),
  1437. hasStatic404: useStatic404,
  1438. hasReportWebVitals: (ref5 = namedExports == null ? void 0 : namedExports.includes("reportWebVitals")) != null ? ref5 : false,
  1439. rewritesCount: combinedRewrites.length,
  1440. headersCount: headers.length,
  1441. redirectsCount: redirects.length - 1,
  1442. headersWithHasCount: headers.filter((r)=>!!r.has).length,
  1443. rewritesWithHasCount: combinedRewrites.filter((r)=>!!r.has).length,
  1444. redirectsWithHasCount: redirects.filter((r)=>!!r.has).length,
  1445. middlewareCount: Object.keys(rootPaths).length > 0 ? 1 : 0
  1446. }));
  1447. if (telemetryPlugin) {
  1448. const events = (0, _events).eventBuildFeatureUsage(telemetryPlugin);
  1449. telemetry.record(events);
  1450. telemetry.record((0, _events).eventPackageUsedInGetServerSideProps(telemetryPlugin));
  1451. }
  1452. if (ssgPages.size > 0 || appDir) {
  1453. var ref6;
  1454. tbdPrerenderRoutes.forEach((tbdRoute)=>{
  1455. const normalizedRoute = (0, _normalizePagePath).normalizePagePath(tbdRoute);
  1456. const dataRoute = _path.default.posix.join("/_next/data", buildId, `${normalizedRoute}.json`);
  1457. finalDynamicRoutes[tbdRoute] = {
  1458. routeRegex: (0, _loadCustomRoutes).normalizeRouteRegex((0, _routeRegex).getNamedRouteRegex(tbdRoute).re.source),
  1459. dataRoute,
  1460. fallback: ssgBlockingFallbackPages.has(tbdRoute) ? null : ssgStaticFallbackPages.has(tbdRoute) ? `${normalizedRoute}.html` : false,
  1461. dataRouteRegex: (0, _loadCustomRoutes).normalizeRouteRegex((0, _routeRegex).getNamedRouteRegex(dataRoute.replace(/\.json$/, "")).re.source.replace(/\(\?:\\\/\)\?\$$/, "\\.json$"))
  1462. };
  1463. });
  1464. const prerenderManifest = {
  1465. version: 3,
  1466. routes: finalPrerenderRoutes,
  1467. dynamicRoutes: finalDynamicRoutes,
  1468. notFoundRoutes: ssgNotFoundPaths,
  1469. preview: previewProps
  1470. };
  1471. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.PRERENDER_MANIFEST), JSON.stringify(prerenderManifest), "utf8");
  1472. await generateClientSsgManifest(prerenderManifest, {
  1473. distDir,
  1474. buildId,
  1475. locales: ((ref6 = config.i18n) == null ? void 0 : ref6.locales) || []
  1476. });
  1477. } else {
  1478. const prerenderManifest = {
  1479. version: 3,
  1480. routes: {},
  1481. dynamicRoutes: {},
  1482. preview: previewProps,
  1483. notFoundRoutes: []
  1484. };
  1485. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.PRERENDER_MANIFEST), JSON.stringify(prerenderManifest), "utf8");
  1486. }
  1487. const images = {
  1488. ...config.images
  1489. };
  1490. const { deviceSizes , imageSizes } = images;
  1491. images.sizes = [
  1492. ...deviceSizes,
  1493. ...imageSizes
  1494. ];
  1495. var _pathname;
  1496. images.remotePatterns = ((config == null ? void 0 : (ref1 = config.images) == null ? void 0 : ref1.remotePatterns) || []).map((p)=>({
  1497. // Should be the same as matchRemotePattern()
  1498. protocol: p.protocol,
  1499. hostname: (0, _micromatch).makeRe(p.hostname).source,
  1500. port: p.port,
  1501. pathname: (0, _micromatch).makeRe((_pathname = p.pathname) != null ? _pathname : "**").source
  1502. }));
  1503. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.IMAGES_MANIFEST), JSON.stringify({
  1504. version: 1,
  1505. images
  1506. }), "utf8");
  1507. await _fs.promises.writeFile(_path.default.join(distDir, _constants1.EXPORT_MARKER), JSON.stringify({
  1508. version: 1,
  1509. hasExportPathMap: typeof config.exportPathMap === "function",
  1510. exportTrailingSlash: config.trailingSlash === true,
  1511. isNextImageImported: isNextImageImported1 === true
  1512. }), "utf8");
  1513. await _fs.promises.unlink(_path.default.join(distDir, _constants1.EXPORT_DETAIL)).catch((err)=>{
  1514. if (err.code === "ENOENT") {
  1515. return Promise.resolve();
  1516. }
  1517. return Promise.reject(err);
  1518. });
  1519. if (config.output === "standalone") {
  1520. for (const file of [
  1521. ...requiredServerFiles.files,
  1522. _path.default.join(config.distDir, _constants1.SERVER_FILES_MANIFEST),
  1523. ...loadedEnvFiles.reduce((acc, envFile)=>{
  1524. if ([
  1525. ".env",
  1526. ".env.production"
  1527. ].includes(envFile.path)) {
  1528. acc.push(envFile.path);
  1529. }
  1530. return acc;
  1531. }, []),
  1532. ]){
  1533. const filePath = _path.default.join(dir, file);
  1534. const outputPath = _path.default.join(distDir, "standalone", _path.default.relative(outputFileTracingRoot, filePath));
  1535. await _fs.promises.mkdir(_path.default.dirname(outputPath), {
  1536. recursive: true
  1537. });
  1538. await _fs.promises.copyFile(filePath, outputPath);
  1539. }
  1540. await (0, _recursiveCopy).recursiveCopy(_path.default.join(distDir, _constants1.SERVER_DIRECTORY, "pages"), _path.default.join(distDir, "standalone", _path.default.relative(outputFileTracingRoot, distDir), _constants1.SERVER_DIRECTORY, "pages"), {
  1541. overwrite: true
  1542. });
  1543. }
  1544. staticPages.forEach((pg)=>allStaticPages.add(pg));
  1545. pageInfos.forEach((info, key)=>{
  1546. allPageInfos.set(key, info);
  1547. });
  1548. await nextBuildSpan.traceChild("print-tree-view").traceAsyncFn(()=>(0, _utils2).printTreeView(pageKeys, allPageInfos, isLikeServerless, {
  1549. distPath: distDir,
  1550. buildId: buildId,
  1551. pagesDir,
  1552. useStatic404,
  1553. pageExtensions: config.pageExtensions,
  1554. appBuildManifest,
  1555. buildManifest,
  1556. middlewareManifest,
  1557. gzipSize: config.experimental.gzipSize
  1558. }));
  1559. if (debugOutput) {
  1560. nextBuildSpan.traceChild("print-custom-routes").traceFn(()=>(0, _utils2).printCustomRoutes({
  1561. redirects,
  1562. rewrites,
  1563. headers
  1564. }));
  1565. }
  1566. if (config.analyticsId) {
  1567. console.log(_chalk.default.bold.green("Next.js Analytics") + " is enabled for this production build. " + "You'll receive a Real Experience Score computed by all of your visitors.");
  1568. console.log("");
  1569. }
  1570. if (Boolean(config.experimental.nextScriptWorkers)) {
  1571. await nextBuildSpan.traceChild("verify-partytown-setup").traceAsyncFn(async ()=>{
  1572. await (0, _verifyPartytownSetup).verifyPartytownSetup(dir, (0, _path).join(distDir, _constants1.CLIENT_STATIC_FILES_PATH));
  1573. });
  1574. }
  1575. await nextBuildSpan.traceChild("telemetry-flush").traceAsyncFn(()=>telemetry.flush());
  1576. });
  1577. return buildResult;
  1578. } finally{
  1579. // Ensure we wait for lockfile patching if present
  1580. await _swc.lockfilePatchPromise.cur;
  1581. // Ensure all traces are flushed before finishing the command
  1582. await (0, _trace).flushAllTraces();
  1583. (0, _swc).teardownTraceSubscriber();
  1584. (0, _swc).teardownCrashReporter();
  1585. }
  1586. }
  1587. function _interopRequireDefault(obj) {
  1588. return obj && obj.__esModule ? obj : {
  1589. default: obj
  1590. };
  1591. }
  1592. function _getRequireWildcardCache() {
  1593. if (typeof WeakMap !== "function") return null;
  1594. var cache = new WeakMap();
  1595. _getRequireWildcardCache = function() {
  1596. return cache;
  1597. };
  1598. return cache;
  1599. }
  1600. function _interopRequireWildcard(obj) {
  1601. if (obj && obj.__esModule) {
  1602. return obj;
  1603. }
  1604. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  1605. return {
  1606. default: obj
  1607. };
  1608. }
  1609. var cache = _getRequireWildcardCache();
  1610. if (cache && cache.has(obj)) {
  1611. return cache.get(obj);
  1612. }
  1613. var newObj = {};
  1614. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  1615. for(var key in obj){
  1616. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1617. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  1618. if (desc && (desc.get || desc.set)) {
  1619. Object.defineProperty(newObj, key, desc);
  1620. } else {
  1621. newObj[key] = obj[key];
  1622. }
  1623. }
  1624. }
  1625. newObj.default = obj;
  1626. if (cache) {
  1627. cache.set(obj, newObj);
  1628. }
  1629. return newObj;
  1630. }
  1631. /**
  1632. * typescript will be loaded in "next/lib/verifyTypeScriptSetup" and
  1633. * then passed to "next/lib/typescript/runTypeCheck" as a parameter.
  1634. *
  1635. * Since it is impossible to pass a function from main thread to a worker,
  1636. * instead of running "next/lib/typescript/runTypeCheck" in a worker,
  1637. * we will run entire "next/lib/verifyTypeScriptSetup" in a worker instead.
  1638. */ function verifyTypeScriptSetup(dir, intentDirs, typeCheckPreflight, tsconfigPath, disableStaticImages, cacheDir, numWorkers, enableWorkerThreads) {
  1639. const typeCheckWorker = new _jestWorker.Worker(require.resolve("../lib/verifyTypeScriptSetup"), {
  1640. numWorkers,
  1641. enableWorkerThreads,
  1642. maxRetries: 0
  1643. });
  1644. typeCheckWorker.getStdout().pipe(process.stdout);
  1645. typeCheckWorker.getStderr().pipe(process.stderr);
  1646. return typeCheckWorker.verifyTypeScriptSetup({
  1647. dir,
  1648. intentDirs,
  1649. typeCheckPreflight,
  1650. tsconfigPath,
  1651. disableStaticImages,
  1652. cacheDir
  1653. }).then((result)=>{
  1654. typeCheckWorker.end();
  1655. return result;
  1656. });
  1657. }
  1658. function generateClientSsgManifest(prerenderManifest, { buildId , distDir , locales }) {
  1659. const ssgPages = new Set([
  1660. ...Object.entries(prerenderManifest.routes)// Filter out dynamic routes
  1661. .filter(([, { srcRoute }])=>srcRoute == null).map(([route])=>(0, _normalizeLocalePath).normalizeLocalePath(route, locales).pathname),
  1662. ...Object.keys(prerenderManifest.dynamicRoutes),
  1663. ].sort());
  1664. const clientSsgManifestContent = `self.__SSG_MANIFEST=${(0, _devalue).default(ssgPages)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`;
  1665. (0, _fs).writeFileSync(_path.default.join(distDir, _constants1.CLIENT_STATIC_FILES_PATH, buildId, "_ssgManifest.js"), clientSsgManifestContent);
  1666. }
  1667. function isTelemetryPlugin(plugin) {
  1668. return plugin instanceof _telemetryPlugin.TelemetryPlugin;
  1669. }
  1670. function pageToRoute(page) {
  1671. const routeRegex = (0, _routeRegex).getNamedRouteRegex(page);
  1672. return {
  1673. page,
  1674. regex: (0, _loadCustomRoutes).normalizeRouteRegex(routeRegex.re.source),
  1675. routeKeys: routeRegex.routeKeys,
  1676. namedRegex: routeRegex.namedRegex
  1677. };
  1678. }
  1679. //# sourceMappingURL=index.js.map