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