import a from"node:path";import{bundle as N,createConfig as S,getTotals as T}from"@redocly/openapi-core";import{CONFIG_FILE_NAME as k}from"../../../constants/index.js";import{getAllApiConfigsByPath as B}from"../get-api-config.js";import{injectDecoratorIntoConfig as M}from"../openapi-docs/decorators.js";import{ExternalResolver as J}from"../../fs/utils/external-ref-resolver.js";import{deepMerge as L}from"../../../shared/jsUtils.js";import{pluralize as $}from"../../../shared/utils.js";import{mapChannelToOperations as _}from"./utils/map-channel-to-opertaions.js";async function Y(o,{fs:t,logger:f,cache:b,getConfig:y,isPathIgnored:x}){let s;try{s=(await b.load(o,"yaml")).data}catch{return[]}if(!s?.asyncapi)return f.verbose(`${o} file is not AsyncAPI document. Skipping`),[];const p=[],c=await t.getFileInfo(o),e=await y(a.posix.dirname(o)),R=B(e?.apis,o,e.configPath),O=await x(o);for(const i of R){if(!i.output&&O)continue;const A=e.configPath?a.posix.dirname(e.configPath):".",r=i.output?a.posix.join(A,i.output):o;c&&i.output&&!await t.exists(r)&&t.addVirtualFile(r,c);const d=L(e,{rbac:void 0},i),l=[],I=a.resolve(t.cwd,e.realConfigPath||k),u=new J(t),D=await S(M(d,r,l),{configPath:I,externalRefResolver:u}),g=a.resolve(t.cwd,o),E={config:D,base:a.dirname(g),doc:{source:{absoluteRef:g},parsed:JSON.parse(JSON.stringify(s))},externalRefResolver:u,dereference:!0},{bundle:{parsed:F},problems:m}=await N(E),n=T(m);let w=[n.errors&&`${n.errors} ${$(n.errors,"error","errors")}`,n.warnings&&`${n.warnings} ${$(n.warnings,"warning","warnings")}`,n.ignored&&`${n.ignored} ignored`].filter(Boolean).join(", ");if(n.errors){const C=m.find(v=>v.severity==="error");throw new Error(`${w} while bundling ${r} definition.

${C?.message} at ${C?.location?.[0].pointer}

`)}n.warnings&&f.warn(`${w} while bundling %rp definition`,r);const h=z(F,e.metadata),P=_(h),j={document:h,config:d,relativePath:r,realRelativePath:c?.realRelativePath||r,customOutputRelativeFile:i.output&&r,markdocChunks:l,channelToOperations:P};p.push(j)}return p}function z(o,t){return t?{...o,info:{...o.info,"x-metadata":{...o.info["x-metadata"],...t}}}:o}export{Y as asyncapiDocLoader};
