import p from"node:path";import{existsSync as b}from"node:fs";import{writeFile as h,access as v,rm as N,constants as X}from"fs/promises";import{REDOCLY_ROUTE_RBAC as S,REDOCLY_TEAMS_RBAC as x}from"@redocly/config";import $ from"picomatch";import{DEFAULT_LOCALE_PLACEHOLDER as _}from"../../../../constants/common.js";import{AI_INDEX_EXPORT_FOLDER as j}from"../../../constants/plugins/search.js";import{LLMS_TXT_FILE_NAME as k}from"../../../constants/common.js";import{isBuildMode as B}from"../../../utils/envs/is-build-mode.js";import{logger as a}from"../../../tools/notifiers/logger.js";import{shaHexShort as G}from"../../../utils/crypto.js";import{ensureDir as A}from"../../../utils/fs.js";import{isResourcePubliclyAccessible as H,extractTeamsForSearch as U,getRbacTeamsForSearch as Y}from"../../../utils/rbac.js";import{promiseMapLimit as M}from"../../../utils/async.js";import{validateLLMsTxtConfig as J,generateLLMsTxt as K,getLLMsTxtMdSlug as V}from"../llmstxt/index.js";const P=20,R="llms.txt:";async function pt(t,o,{aiSearchEnabled:e,llmstxtEnabled:r}){const s=p.join(t.outdir,k);if(!r){try{await v(s,X.W_OK),await N(s)}catch{}if(!e)return}e&&a.info("Preparing AI search documents..."),r&&a.info(`${R} Generating llms.txt files...`);const L=a.startTiming(),c=a.startTiming(),f=t.getGlobalConfig("seo"),l=f?.llmstxt,T=p.resolve(t.outdir,j),u=t.getConfig(),w=u.rbac??{},C=t.getAllRoutes(),F=u?.l10n?.defaultLocale||u?.i18n?.defaultLocale||_,O=(l?.excludeFiles||[]).map(i=>$(i)),d=[];if(await M(C,P,async i=>{const y=await W(i,t),D=await q(i,y,o,t);if(D){if(r)for(const n of await D.getLLMsTxts()){if(O.some(m=>m(n.fsPath)))continue;const g=p.join(t.outdir,V(n.slug));A(g),await h(g,n.content),n.includeInLLMsTxt&&H(i,u)&&d.push(n)}if(e&&B()){const n=await D.getSearchDocuments();if(!n.length)return;const g=z(i,w),m=i.versions?.find(({active:I})=>I),E=m&&{folder:m.folderId,label:m.label,default:m.default};await Q(n,i.fsPath,g,T,F,E)}}}),e&&a.infoTime(c,"AI search documents prepared"),d.length)try{J(l);const i=await K(d,l,{title:f?.title,description:f?.description},o);A(s),await h(s,i),a.infoTime(L,`${R} files generated`)}catch(i){a.error(`${R} Failed to generate llms.txt file. ${i.message}`)}}async function W(t,o){return t.getStaticData?t.getStaticData(t,{...o,contentDir:o.contentDir,parseMarkdoc:(e,r,s)=>o.parseMarkdoc(e,r,s)}):{}}async function q(t,o,e,r){if(t.getAiDocumentsStore)return t.getAiDocumentsStore(t,{...o,[x]:t[x],[S]:t[S]},e,r)}function z(t,o){const e=U(t?.[x]);return e?.length?e:Y(t,o)}async function Q(t,o,e,r,s,L){await M(t,P,async c=>{const f=`${G(o+c.content)}.json`,l=A(p.join(r,f)),T=c.locale===_?s:c.locale;b(l)||await h(l,JSON.stringify({...c,rbacTeams:e||[],version:L,locale:T}),"utf-8")})}export{pt as prepareAiSearchDocuments};
