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

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

`)}i.warnings&&f.warn(`${b} while bundling %rp definition`,r);const V=x(I,t.metadata),j=x(P,t.metadata),E={document:V,documentWithReferences:j,config:m,relativePath:r,realRelativePath:e?.realRelativePath||r,customOutputRelativeFile:c.output&&r,markdocChunks:S,isVirtual:e?.isVirtual??!1};l.push(E)}return l}async function nn(n,o){const{fs:f,cache:u,getConfig:p}=o,d=[];for(const a of await f.scan(/(\.ya?ml|\.json)$/)){if(!await p(s.posix.dirname(a.relativePath)))continue;let e;try{e=await u.load(a.relativePath,"asyncapi-doc")}catch{continue}e.data?.length&&d.push(...e.data.map(t=>({...t,isVirtual:a.isVirtual||t.isVirtual,hash:e.compoundHash})))}return d}function x(n,o){return o?{...n,info:{...n.info,"x-metadata":{...n.info["x-metadata"],...o}}}:n}export{Z as asyncapiDocLoader,nn as asyncapiDocsLoader};
