import T from"node:path";import{unlink as h}from"node:fs/promises";import{writeFileSync as y}from"node:fs";import{envConfig as S}from"../../server/config/env-config.js";import{PORTAL_VERSION as A}from"../../server/version.js";import{logger as e}from"../../server/tools/notifiers/logger.js";import{reporter as b}from"../../server/tools/notifiers/reporter.js";import{shutdowner as O}from"../../server/tools/shutdowner.js";import{promiseMapLimit as D}from"../../server/utils/async/promise-map-limit.js";import{validateReactPages as E}from"../../server/plugins/pages/validators/validate-react-pages.js";import{ensureDir as v}from"../../server/utils/index.js";import{initPlugins as M,runPlugins as _,writeClientEntries as x}from"../../server/plugins/lifecycle.js";import{createClientCompiler as L,createNodeBundleCompiler as J}from"../../server/esbuild/esbuild.js";import{validateAllMarkdowns as j}from"../../server/plugins/markdown/compiler.js";import{copyEnvFiles as k}from"./copy-env-files.js";import{EsbuildError as l,esbuildLogger as p}from"../../server/esbuild/esbuild-logger.js";import{reportAllErrors as F}from"../../server/utils/report-all-errors.js";import{collectAnalytics as U}from"./analytics/collect-analytics.js";import{copyMigrationsFolder as z}from"../../server/providers/database/copy-migrations.js";import{telemetry as c}from"../telemetry/index.js";import{telemetryTraceStep as m}from"../telemetry/helpers/trace-step.js";async function si(C,i){c.initialize(A),e.info("Starting project build.");const P=e.startTiming();await m("build.start",async R=>{x(i);const d=await L(i,i.outdir,"production"),u=await J(i,i.serverOutDir,"production");let n,f;try{await m("build.client_compilation",async()=>{const s=e.startTiming(),o=await d.rebuild().catch(a=>{throw new l(a)});Array.isArray(o.warnings)&&p(new l({warnings:o.warnings}));const r=e.infoTime(s,"Client JavaScript compiled");r&&c.sendTimingPerformedMessage(r)}),await m("build.server_compilation",async()=>{const s=e.startTiming(),o=await u.rebuild().catch(a=>{throw new l(a)});Array.isArray(o.warnings)&&p(new l({warnings:o.warnings}));const r=e.infoTime(s,"Server JavaScript compiled");r&&c.sendTimingPerformedMessage({message:r.message,timeMs:r.timeMs})}),await i.reloadMarkdocOptions();let t;({pluginInstances:t,lifecycleContext:n}=await M({outdir:i.outdir,serverOutDir:i.serverOutDir,contentDir:i.contentDir,devLogin:C.devLogin,setGlobalConfig:i.setGlobalConfig})),n.fs.dispose(),i.lifecycleContext=n,z(i),await _(t,i,n),f=U(i,n),await m("build.client_server_recompile",async()=>{const s=e.startTiming();e.info("Re-compiling JavaScript with user code"),(await Promise.all([d.rebuild(),u.rebuild()]).catch(a=>{throw new l(a)})).forEach(({warnings:a})=>{Array.isArray(a)&&p(new l({warnings:a}))});const r=e.infoTime(s,"JavaScript re-compiled");r&&c.sendTimingPerformedMessage(r)}),await m("build.pages_validation",async()=>{await E(i,n),await j(i,n)}),await F(n),i.markUserCodeReady()}catch(t){R?.error(t),t instanceof l&&p(t)}finally{f&&await f.catch(()=>{}),await d.dispose(),await u.dispose()}b.printErrors(),e.info("Rendering pages..."),await m("build.prepare_static_data",async t=>{const s=e.startTiming(),o=[...i.getAllRoutes(),...i.getAllApiRoutes()];t?.setAttribute("totalRoutes",o.length.toString()),await D(o,15,a=>i.writeRouteStaticData(a,n));const r=e.successTime(s,"Page static data prepared.");r&&c.sendTimingPerformedMessage(r)}),await m("build.store_serialization",async()=>{const t=e.startTiming();v(i.serverOutDir),y(T.join(i.serverOutDir,"store.json"),JSON.stringify(await i.toJson())),e.successTime(t,"Store serialized and written."),k(i)});const g=S.REDOCLY_PROBLEMS_OUTPUT_FILE;if(g){const t=e.startTiming();y(v(g),JSON.stringify(b.getProblems()),"utf-8"),e.successTime(t,"Broken links written.")}await h(T.join(i.serverOutDir,"index.css"));const w=e.successTime(P,"All done");w&&c.sendTimingPerformedMessage(w)}),await O.exitWithCode(0)}export{si as build};
