import{otelTelemetry as p}from"../../telemetry/telemetry.js";import*as u from"workerpool";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{MemoryUsageLimitError as O,TimeoutExceededError as _}from"./errors.js";import{serializeRequest as g}from"./utils/serialize-request.js";import{isDevelopMode as S}from"../../utils/is-develop-mode.js";import{fromCurrentDir as h}from"../../utils/paths.js";import{EXCLUDED_ENV_VARS as k,MAX_RESPONSE_SIZE_MB as M,MAX_WORKERS_COUNT as T,TIMEOUT_LIMIT as w}from"./constants.js";import a from"../../utils/reporter/logger.js";let n;const A="Workerpool Worker terminated Unexpectedly";function I(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>!k.includes(e)))}function y(){const e=S()?"js":"mjs",o=h(import.meta.url,"./api-functions-handler-worker."+e);return n||(n=u.pool(o,{maxWorkers:T,minWorkers:1,workerType:"process",forkOpts:{env:{...I(),REDOCLY_RUNNING_COMMAND:process.env.REDOCLY_RUNNING_COMMAND,PORTAL_LOG_FORMAT:process.env.PORTAL_LOG_FORMAT,REPORTER_VERBOSE:process.env.REPORTER_VERBOSE},stdio:"inherit"}})),n}async function H(e,o,s){const E=y(),r=o.get("auth"),c=await s.resolveRouteStaticData(e)||{};try{const t=E.exec("runHandler",[{serverOutDir:s.serverOutDir,slug:f(e.slug),requestHandlerId:e.requestHandlerId,maxResponseSizeMB:M,ctxData:{user:{teams:r.teams,email:r.claims.email,claims:r.claims,idpAccessToken:r.idpAccessToken,idpId:r.claims.idpId,isAuthenticated:r.isAuthenticated},config:s.config},staticData:{...c,props:{...c.props,routeSlug:e.slug,outdir:s.outdir}},req:await g(o.req.raw),loggerStickyState:a.getStickyState()}]).catch(i=>{throw i.message.includes(A)?new O("Memory usage exceeded limit."):(a.error(`[${e.requestHandlerId}] ${i.message} ${i.stack}`),i)}).timeout(w),{status:m,headers:l,body:d,loggerStickyState:R}=await t;return a.setStickyState(R),p.send("api_function_called",{error:null,handler:e.requestHandlerId,body:d,headers:l,status:m}),new Response(d,{status:m,headers:l})}catch(t){throw p.send("api_function_error",{handler:e.requestHandlerId,message:t?.message,stack:t?.stack}),t instanceof u.Promise.TimeoutError?new _("Timeout exceeded"):t}}export{H as runApiFunctionHandler};
