import _ from"@markdoc/markdoc";import D from"node:path";import{AI_SEARCH_CHUNK_SIZE as E,AI_SEARCH_DOCUMENT_CHUNK_SIZE as M}from"../../../constants/plugins/search.js";import{slugger as P}from"../../../utils/slugger.js";import{toMarkdown as U}from"./to-markdown.js";import{AstToSearchNodeTransformer as b}from"./walk-sections.js";import{getLocaleFromRelativePath as x}from"../../../fs/utils/get-locale-from-relative-path.js";import{HeadingNode as I}from"./nodes/heading-node.js";import{extractDocumentSearchFacets as y}from"./search-facets.js";import{formatDocumentMetadata as L}from"../../search/utils.js";import{TagNode as H}from"./nodes/tag-node.js";import{MARKDOC_PARTIALS_DATA_KEY as K}from"../../../store.js";const N=Symbol(),W=(n,c)=>async(e,r,u,s)=>{if(c?.excludeFromSearch)return;P.reset();const i=await e.getNavText?.()||D.basename(e.fsPath),p=_.Ast.fromJSON(r.ast),m=new b({partials:s.getGlobalConfig(K)||{},getInnerContent:U,ast:p,skipConditionals:!0}),f=Array.from(m.transform());return{async getLLMsTxts(){const o=c?.seo,g=o&&typeof o=="object"&&"description"in o?String(o.description):void 0,C=f.map(t=>t.content).filter(Boolean).join(`
`).trim();return[{title:i,description:g,slug:e.slug,fsPath:e.fsPath,content:C,includeInLLMsTxt:!0}]},async getSearchDocuments(){return j(e,f,n,i)}}};function j(n,c,e,r){const u=n.slug,s=new Map,i=n.metadata||{},p=y(i,e),m=L(i),f=m?`Metadata:
${m}
`:"";let o=[];for(const t of c)if(t instanceof I){o.splice(t.attributes.level-1,6);const a=t.attributes.level>2,l=o[o.length-1]?.title,S=o[o.length-1]?.url,A=a&&l?l:w(r,t),T=a&&S?S:t.getUrl(u),d={title:A,content:"",url:T,level:t.attributes.level,toc:o.map(v=>h(v.section)).join(`
`)};(t.attributes.level>1||h(t)!==r)&&(d.content+=d.content?`
`:"",d.content+=t.content.trimEnd()),s.set(t.id,d),o.push({section:t,title:A,url:T})}else if(t instanceof H)s.set(t.id,{title:t.content,content:t.content,url:t.getUrl(u),level:t.attributes.level+1,toc:o.map(a=>h(a.section)).concat(t.content).join(`
`)});else{const a=t.parentNode?.id??N,l=s.get(a)??{title:r,content:"",url:u,level:1/0,toc:""};l.content+=l.content?`
`:"",l.content+=t.content.trimEnd(),s.set(a,l)}const g=R(Array.from(s.values())),C=x(n.fsPath);return g.filter(t=>t.content).map(t=>({title:t.title,url:t.url,content:[f,t.toc||`# ${r}`,t.content].filter(Boolean).join(`
`),fsPath:n.fsPath,locale:C,product:n.product?.name,facets:p}))}function k(n){return n.length/4}function R(n){if(n.length===0)return[];const c=[];let e=n[0];for(const r of n.slice(1)){const u=k(e.content),s=k(r.content),i=n.indexOf(r)===n.length-1;s<E&&(u<M||i)&&r.level>e.level?e.content+=`
`+r.content:(c.push(e),e=r)}return c.push(e),c}function w(n,c){return c.content===n?n:`${n} \u2192 ${h(c)}`}function h(n){return n.content.replace(/^#+/,"").trim()}export{W as getAiDocumentsStore};
