import m from"path";import{REDOCLY_ROUTE_RBAC as A,REDOCLY_TEAMS_RBAC as C}from"@redocly/config";import{withoutPathPrefix as S}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as E,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as b}from"../../constants/common.js";import{sanitizeRedirectPathname as M,processRedirects as q}from"../../../shared/urls.js";import{normalizeRouteSlug as D,isPathInFolder as O,sanitizePath as F,removeTrailingSlash as z}from"../../../shared/utils.js";import{renderPage as G,getServerProps as H}from"../../ssr/index.js";import{canAccessAsset as v,canAccessResource as B}from"../../utils/rbac.js";import{handleErrorPageRender as w,handleUnauthorized as Y,handleUnauthorizedAsset as _}from"../utils.js";import{findInIterable as k}from"../../../shared/jsUtils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as N,MIME_TYPES as W}from"../mime-types.js";import{fileExistsAsync as X}from"../../utils/index.js";import{getRedirectRoute as $}from"../utils/legacy-openapi-redirects.js";import{otelTelemetry as V}from"../../telemetry/telemetry.js";function ce(t,L,U){return async e=>{const f=e.get("logger"),c=e.req,a=new URL(c.url),r=S(F(decodeURIComponent(a.pathname))),I=m.parse(r).ext===".md",s=D(r),o=c.method==="GET"&&!I?t.getRouteBySlug(s,{followRedirect:!1})||k(t.routesBySlug?.values(),n=>n.hasClientRoutes&&(r===n.slug||r.startsWith(n.slug+"/"))):void 0,l=q({redirects:t.config.redirects,requestedSlug:s,reqUrlSearch:a.search});if(l)return V.send("redirect",{from:s,templateId:l.type.toString()}),e.newResponse(null,l.type,{Location:l.location});if(o?.metadata?.type==="openapi"){const n=$(a.pathname);if(n)return f.info("Legacy OpenAPI docs redirect from "+a.pathname),e.newResponse(null,301,{Location:encodeURI(n)});if(a.pathname.match(/[A-Z]/))return f.warn("Redirect to lowercase route to avoid 404 error"),e.newResponse(null,301,{Location:encodeURI(a.pathname.toLowerCase())})}if(r.endsWith("/")&&r!=="/"){const n=M(new URL(s||"/",e.req.url).pathname);return e.newResponse(null,301,{Location:encodeURI((n==="/"?"/":z(n))+a.search)})}const{isAuthenticated:u,teams:h,claims:{email:g}}=e.get("auth");if(o){if(!B(o,{isAuthenticated:u,email:g,teams:h},t.config.rbac,t.config.requiresLogin))return u?w(e,t,{slug:o.slug,[C]:o[C],[A]:o[A]},"403"):Y(e,t,o.slug);const n=await L(o),p=await H(o,e,n,t),{html:y,statusCode:P}=await G(o,p,e,t);return e.html(y,P,{"Cache-Control":E})}const i=m.resolve(t.outdir,"."+r);if(!O(i,t.outdir))return _(e);if(!v(r,t.getGlobalConfig("rbac"),t.getGlobalConfig("requiresLogin"),t.getGlobalConfig("directoryPaths"),{isAuthenticated:u,email:g,teams:h}))return _(e);const R=W[m.extname(i)]||"text/plain",d=i.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||i.match(/runtime\/chunks\/.*/)?b:N[R],T=d?{"Cache-Control":`public, max-age=${d}, immutable`,Expires:new Date(Date.now()+d*1e3).toUTCString()}:{"Cache-Control":E};if(await X(i)){const n=c.query("download")!=null,p=await U(i);return e.newResponse(p,200,{"Content-Type":R,"Access-Control-Allow-Origin":"*",...T,...n&&{"Content-Disposition":`attachment; filename="${m.basename(i)}"`}})}else return w(e,t,{slug:s},"404")}}export{ce as dynamicRouteHandler};
