import n from"node:path";import{OPENAPI_DOCS_TEMPLATE_ID as S}from"../../../../constants/index.js";import{getInnerText as B,getNodeAttribute as E,setNodeAttributeValue as f}from"../../../../shared/markdoc.js";import{isLocalLink as T,normalizeRouteSlug as x}from"../../../../shared/utils.js";import{MdResolveError as g}from"./md-resolve-error.js";import{getLinkOriginalAttrName as W}from"./utils.js";import{isOpenApiURL as j}from"../../openapi-docs/is-openapi-doc.js";import{parseBaseName as D}from"../../utils.js";import{isMarkdownPage as M}from"../is-markdown-page.js";import{copyStaticFile as U}from"../../../utils/fs.js";async function J(i,r,a,{actions:u,context:l}){const{contentDir:y,outdir:A,getRouteByFsPath:F,getRouteBySlug:L}=u,P=W(r),s=i[P]||E(i,r);if(i[P]=s,!T(s))return;const[_,t="",I,w]=/^([^\?#]+)?([^#]+)?(.+)?/.exec(s)||[],m=i.type==="image"?"IMAGE":"LINK",p=String(i.attributes.title||i.attributes.alt||B([i])||""),{isOpenapiDetected:R,isOpenapiValid:d}=await j(t,a,u,l);if(R&&!d)throw new g(`OpenAPI route ${s} does not exist`,{rawLink:s,link:t,title:p,brokenLinkType:m});if(n.extname(t)===""){if(t.startsWith("/")){if(!L(x(t)))throw new g(`Route ${t} does not exist`,{rawLink:s,link:t,title:p,brokenLinkType:m});f(i,r,t+(I||"")+(w||""))}if(!s.startsWith("#")&&!t.startsWith("/")&&M(a)){const o=u.getRouteByFsPath(a)?.slug;if(!o)return;const{isIndexFile:h}=D(a),k=h?x(n.posix.join(o,t)):x(n.posix.join(o,"../",t));if(!L(k))throw new g(`Route ${t} does not exist`,{rawLink:s,link:k,title:p,brokenLinkType:m});f(i,r,k+(I||"")+(w||""))}return}const e=t.startsWith("/")?t.substring(1):n.posix.join(n.posix.dirname(a),decodeURI(t)),O=t.startsWith("/")?n.posix.join("static",t.substring(1)):"";if(!await l.fs.exists(e)&&!u.getRouteByFsPath(e)&&!await l.fs.exists(O))throw f(i,r,"#"),new g(`File ${e} does not exist`,{rawLink:s,link:e,title:p,brokenLinkType:m});const c=F(e);if(c)f(i,r,(c.templateId===S?c.baseSlug:c.slug)+(w||""));else if(await l.fs.exists(e)){const o=await l.fs.getFileInfo(e);if(!o||o.isVirtual)return;const h=U(y,o.realRelativePath,A);f(i,r,h)}}export{J as resolveLink};
