import{REDOCLY_TEAMS_RBAC as k}from"@redocly/config";import{basename as R,join as _}from"node:path";import{toMarkdown as L}from"../../../plugins/markdown/search/to-markdown.js";import{canDownloadApiDefinition as G,isResourcePubliclyAccessible as E}from"../../../utils/rbac.js";import{PUBLIC_API_DEFINITIONS_FOLDER as J}from"../../../constants/common.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as z}from"../../../../constants/common.js";import{SearchIndexer as V}from"../search-indexer.js";import{getLocaleFromRelativePath as q}from"../../../fs/utils/get-locale-from-relative-path.js";import{extractDocumentSearchFacets as B}from"./search-facets.js";import{formatDocumentMetadata as C}from"../../search/utils.js";import{getLLMsTxtMdSlug as Y,llmsTxtLink as M}from"../../search/llmstxt/index.js";import{replaceFileExtension as H}from"../store-definition-bundles.js";const x=new Map,me=({parser:i,options:c,info:t,tagOperations:s,relativePath:n,openapiContentItem:e,metadata:r,getSearchFacets:o,includeInLLMsTxt:a,excludeFromSearch:m})=>async(u,f,l)=>{if(m)return;const D=await u.getNavText?.()||R(u.fsPath),A=new V(i,c,u.baseSlug||u.slug),p=A.addItem(e);if(!p)return;const O=await l.getConfig(),S=Array.isArray(p.title)?p.title.join(" "):p.title;let g,d,$=x.get(n);if((e.type==="tag"||e.type==="section"&&e.infoDefinition)&&!$){const{all:b,publiclyAccessible:y}=ee(s.tagged,A,O),{all:T,publiclyAccessible:w}=ne(s.untagged,A,O);x.set(n,{taggedSearchDocuments:new Map(b),untaggedSearchDocuments:T,publiclyAccessibleTaggedSearchDocuments:new Map(y),publiclyAccessibleUntaggedSearchDocuments:w})}$=x.get(n);const h="#";switch(e.type){case"operation":const b=A.getOperation(e);g=d=X({title:S,security:i.definition.security,document:p,version:p.version||t.version,headingLevel:h,operation:b});break;case"section":if(e.infoDefinition){$=x.get(n),d=await P({parser:i,info:t,staticData:f,relativePath:n,headingLevel:h,pageName:D,config:O}),d+=`
`;for(const[T,w]of $?.publiclyAccessibleTaggedSearchDocuments?.entries()||[]){if(!w.length)return;const U=i.definition.tags?.find(F=>F.name===T);d+=j({title:U?.["x-displayName"]||T,description:U?.description,operationSearchDocuments:w,headingLevel:`${h}#`})}const y=$?.publiclyAccessibleUntaggedSearchDocuments||[];y.length&&(d+=j({title:"Other",description:void 0,operationSearchDocuments:y,headingLevel:`${h}#`})),g=await P({parser:i,info:t,staticData:f,relativePath:n,headingLevel:h,pageName:D,config:O})}else e.ast&&(d=g=L(e.ast));break;case"tag":d=j({title:S,description:e.description,operationSearchDocuments:$?.publiclyAccessibleTaggedSearchDocuments.get(e.name)||[],headingLevel:h}),g=j({title:S,description:e.description,operationSearchDocuments:[],headingLevel:h});break;case"mcp":d=Z({title:S,description:e.description,name:e.name,xMcpConfig:i.definition["x-mcp"],headingLevel:h}),g=d;break}return{async getLLMsTxts(){return[{title:e.name,description:e.type==="tag"?e.description:void 0,content:d||"",slug:u.slug,fsPath:u.fsPath,includeInLLMsTxt:a}]},async getSearchDocuments(){if(e.type==="operation"||e.type==="section"&&(e.infoDefinition||e.ast)||e.type==="tag"){const b=q(u.fsPath),y=B({...p,...r},t,o);return[{title:S,description:Array.isArray(p.text)?p.text.join(" "):p.text,content:g||"",url:p.url??u.slug,fsPath:u.fsPath,locale:b,product:p.product?.name,rbacTeams:p.rbacTeams,facets:y}]}return[]}}};async function P({parser:i,info:c,staticData:t,relativePath:s,pageName:n,headingLevel:e,config:r}){const o=C(c["x-metadata"]);let a=c.title?`${e} ${c.title}

`:`${e} ${n}

`;return a+=c.description?`${c.description}

`:"",a+=c.summary?`${c.summary}

`:"",a+=c.version?`Version: ${c.version}
`:"",a+=c.license?`License: ${c.license.name}
`:"",e=`${e}#`,a+=o.length?`Metadata:
${o}
`:"",a+=`
`,a+=K({parser:i,headingLevel:e}),a+=W({parser:i,headingLevel:e}),a+=await Q({info:c,staticData:t,relativePath:s,pageName:n,headingLevel:e,config:r}),a}function j({title:i="",description:c,operationSearchDocuments:t,headingLevel:s}){let n=`${s} ${i}

`;return c&&(n+=`${c}

`),t.length&&t.forEach(e=>{const r=Array.isArray(e.title)?e.title.join(" "):e.title;n+=`${s}# ${r}${e.deprecated?" (deprecated)":""}

`,n+=` - ${M({title:`${e.httpMethod?.toUpperCase()} ${e.httpPath}`,description:Array.isArray(e.text)?e.text.join(" "):e.text,slug:Y(e.url)})}`,n+=`
`}),n}function K({parser:i,headingLevel:c}){const{servers:t}=i.definition;if(t&&t.length){let s=`${c} Servers

`;return t.forEach(n=>{s+=n.description?`${n.description}
`:"",s+=`\`\`\`
${n.url}
\`\`\`

`,n.variables&&(s+=`Variables:
`,Object.entries(n.variables).forEach(([e,r])=>{s+=`- \`${e}\`${r.description?`: ${r.description}`:""}
`,s+=r.default?`Default: ${JSON.stringify(r.default)}
`:"",s+=r.enum?`Enum: ${r.enum.map(o=>JSON.stringify(o)).join(", ")}
`:""}),s+=`
`)}),s}return""}async function Q({info:i,staticData:c,relativePath:t,pageName:s,headingLevel:n,config:e}){const r=_(c.props?.outdir||"",J,H(t,".yaml"));if(G(r,e.rbac||{},e.requiresLogin||!1,{isAuthenticated:!1,teams:[z]})){let o=`${n} Download OpenAPI description

`;return o+=M({title:i.title||s||"OpenAPI definition",description:void 0,slug:r}),o}return""}function W({parser:i,headingLevel:c}){if(!i.definition.components?.securitySchemes)return"";let t=`${c} Security

`;const{securitySchemes:s}=i.definition.components;return Object.keys(s).forEach(n=>{const e=s[n];e&&(t+=`${c}# ${n}

`,t+=e.description?`${e.description}

`:"",e.type&&(t+=`Type: ${e.type}
`),e.openIdConnectUrl&&(t+=`OpenID Connect URL: ${e.openIdConnectUrl}
`),e.in&&(t+=`In: ${e.in}
`),e.name&&(t+=`Name: ${e.name}
`),e.scheme&&(t+=`Scheme: ${e.scheme}
`),e.bearerFormat&&(t+=`Bearer Format: ${e.bearerFormat}
`),e.flows?.implicit?.authorizationUrl&&(t+=`Authorization URL: ${e.flows.implicit?.authorizationUrl}
`),e.flows?.implicit?.scopes&&(t+=`Scopes:
`,Object.entries(e.flows?.implicit?.scopes||{}).forEach(([r,o])=>{t+=`- \`${r}\`: ${o}
`})),e.flows?.password?.tokenUrl&&(t+=`Token URL: ${e.flows.password?.tokenUrl}
`),e.flows?.password?.scopes&&(t+=`Scopes:
`,Object.entries(e.flows?.password?.scopes||{}).forEach(([r,o])=>{t+=`- \`${r}\`: ${o}
`})),t+=`
`)}),t}function X({title:i,security:c,document:t,version:s,headingLevel:n,operation:e}){const{text:r,httpMethod:o,httpPath:a,deprecated:m}=t,u=v(t.parameters||[],`${n}#`),f=I(`${n}#`,t.parameters,e);let l=i?`${n} ${i}${m?" (deprecated)":""}

`:"";return l+=r?`${r}

`:"",l+=`Endpoint: ${o?.toUpperCase()} ${a}
`,l+=s?`Version: ${s}
`:"",l+=t.security?.length?`Security: ${t.security.join(", ")}
`:c?.length?`Security: ${c.map(D=>D.id).join(", ")}
`:"",l+=`
`,l+=u?`${u}
`:"",l+=`
`,l+=`${f.join(`
`)}`,l}function Z({title:i,name:c,xMcpConfig:t,headingLevel:s}){const n=t?.tools.find(r=>r.name===c);if(!n)return"";let e=`${s} ${i}

`;return e+=n.description?`${n.description}

`:"",e+=`${s}# Input schema:

`,e+=`\`\`\`json
${JSON.stringify(n.inputSchema,null,2)}
\`\`\`

`,n.outputSchema&&(e+=`${s}# Output schema:

`,e+=`\`\`\`json
${JSON.stringify(n.outputSchema,null,2)}
\`\`\`

`),e}function I(i,c,t){return!c&&!t||!t?.responses?[]:t?.responses.filter(n=>!n.content?.mediaTypes[0]?.schema).map(n=>`${i} ${N(`response ${n.code} fields`)}
`)}function v(i,c){const t={};for(const n of i){const e=`${n.place}${n.mediaType?` (${n.mediaType})`:""}`;t[e]=[...t[e]||[],n]}return Object.entries(t).map(([n,e])=>{const r=e.map(o=>{const a="    ",m=[...o.path||[],o.name],u=Array.isArray(o.description)?o.description.join(" "):o.description;let f=`  - \`${m.join(".")}\` (${o.type}${o.required?", required":""})
`;return f+=u?`${a}${u.trim()}
`:"",o.enum?f+=`${a}Enum: ${o.enum.map(l=>JSON.stringify(l)).join(", ")}
`:o.example&&(f+=`${a}Example: ${o.example}
`),f});return`${c} ${N(n)}:

${r.join(`
`)}`}).join(`
`)}function ee(i,c,t){const s=[],n=[];return i.forEach((e,r)=>{const o=[],a=[];e.forEach(m=>{const u=c.addItem(m);u&&(o.push(u),E({[k]:m[k],slug:u.url},t)&&a.push(u))}),s.push([r,o]),n.push([r,a])}),{all:s,publiclyAccessible:n}}function ne(i,c,t){const s=[],n=[];return i.forEach(e=>{const r=c.addItem(e);r&&(s.push(r),E({[k]:e[k],slug:r.url},t)&&n.push(r))}),{all:s,publiclyAccessible:n}}function N(i){return i.charAt(0).toUpperCase()+i.slice(1)}export{me as getAiDocumentsStore};
