import{REDOCLY_ROUTE_RBAC as D,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{existsSync as _}from"fs";import{rm as w}from"node:fs/promises";import{DEFAULT_LOCALE_PLACEHOLDER as x}from"../../../../constants/common.js";import{SEARCH_DATA_EXPORT_FOLDER as T}from"../../../constants/plugins/search.js";import{isBuildMode as h}from"../../../utils/envs/is-build-mode.js";import{logger as c}from"../../../tools/notifiers/logger.js";import{telemetry as b}from"../../../telemetry/index.js";import{extractTeamsForSearch as O,getRbacTeamsForSearch as $}from"../../../utils/index.js";import{getSearchDocumentGroup as M}from"../utils.js";async function G(S,t,f){c.info("Preparing search documents and create indexes..."),h()&&_(`${t.outdir}/${T}`)&&await w(`${t.outdir}/${T}`,{recursive:!0});const R=c.startTiming(),v=t.getConfig().rbac,F=[x,...S.localeFolders.map(s=>s.toLowerCase())];for(const s of F){const i=t.getAllRoutesForLocale(s);for(const r of i){const d=new Map,{product:n}=r,A=await r.getStaticData?.(r,{...t,contentDir:t.contentDir,parseMarkdoc:(a,e,u)=>t.parseMarkdoc(a,e,u)})||{},m=await r.getSearchDocuments?.(r,{...A,[p]:r[p],[D]:r[D]},t),o=r.versions?.find(a=>a.active),C=$(r,v??{});if(m&&m.length)for(const a in m){let e=m[a];const u=O(e?.[p]),g=u?.length?u:C,L=e.tags||[];e={...e,...o&&{version:o.version,isDefaultVersion:o.default,versionFolderId:o.folderId},...n&&{product:n},rbacTeams:g,tags:[...L,...g,...o?o.default?["v:default"]:[`v:${o.folderId}:${o.version}`]:["v:default"],...n?[`p:${n.name}`]:[]],url:e.url&&(e.path&&e.path.length>1?e.url:e.url.split("#")[0])};const l=M(e.facets);if(l){const E=d.get(l)??[];d.set(l,[...E,e])}}for(const[a,e]of d)await f.addDocuments(e,{locale:s,group:a,outDir:t.outdir})}}if(f.cleanupFacetValues(t),c.infoTime(R,"Search indexes created"),h()){c.info("Writing out search data...");const s=c.startTiming();await f.export(t.outdir);const i=c.infoTime(s,"Search data written");i&&b.sendTimingPerformedMessage(i)}}export{G as prepareSearchDocuments};
