@redocly/redoc-reef 0.141.0-next.12 → 0.141.0-next.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/constants/l10n/langs/ar.js +1 -1
  3. package/dist/constants/l10n/langs/de.js +1 -1
  4. package/dist/constants/l10n/langs/en.js +1 -1
  5. package/dist/constants/l10n/langs/es.js +1 -1
  6. package/dist/constants/l10n/langs/fr.js +1 -1
  7. package/dist/constants/l10n/langs/hi.js +1 -1
  8. package/dist/constants/l10n/langs/it.js +1 -1
  9. package/dist/constants/l10n/langs/ja.js +1 -1
  10. package/dist/constants/l10n/langs/ko.js +1 -1
  11. package/dist/constants/l10n/langs/pl.js +1 -1
  12. package/dist/constants/l10n/langs/pt-BR.js +1 -1
  13. package/dist/constants/l10n/langs/pt.js +1 -1
  14. package/dist/constants/l10n/langs/ru.js +1 -1
  15. package/dist/constants/l10n/langs/uk.js +1 -1
  16. package/dist/constants/l10n/langs/zh.js +1 -1
  17. package/dist/markdoc/helpers/get-resolved-sample-code-block.js +4 -4
  18. package/dist/markdoc/nodes/fence/index.js +1 -1
  19. package/dist/markdoc/tags/openapi-code-sample.js +1 -1
  20. package/dist/markdoc/tags/openapi-response-sample.js +1 -1
  21. package/dist/server/constants/assets.d.ts +3 -0
  22. package/dist/server/constants/assets.js +1 -0
  23. package/dist/server/constants/common.d.ts +0 -3
  24. package/dist/server/constants/common.js +1 -1
  25. package/dist/server/constants/config-schema.d.ts +12 -0
  26. package/dist/server/constants/config-schema.js +1 -0
  27. package/dist/server/constants/project-plugins.d.ts +2 -0
  28. package/dist/server/constants/project-plugins.js +1 -0
  29. package/dist/server/constants/versions.d.ts +3 -0
  30. package/dist/server/constants/versions.js +1 -0
  31. package/dist/server/esbuild/plugins/assets-resolver.js +1 -1
  32. package/dist/server/external-plugins/resolve-external-plugins.js +1 -1
  33. package/dist/server/plugins/api-docs/utils/is-api-doc.js +1 -1
  34. package/dist/server/plugins/api-docs/utils/relative-path-to-base-slug.js +1 -1
  35. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.d.ts +1 -10
  36. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  37. package/dist/server/plugins/config-parser/loaders/index.d.ts +1 -1
  38. package/dist/server/plugins/config-parser/loaders/redocly-config-loader.js +1 -1
  39. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.d.ts +32 -0
  40. package/dist/server/plugins/config-parser/loaders/utils/calculate-content-slugs.js +1 -0
  41. package/dist/server/plugins/config-parser/loaders/versions-config-loader.d.ts +0 -2
  42. package/dist/server/plugins/config-parser/loaders/versions-config-loader.js +1 -1
  43. package/dist/server/plugins/create-slugify.d.ts +1 -1
  44. package/dist/server/plugins/create-slugify.js +1 -1
  45. package/dist/server/plugins/get-reserved-routes.js +1 -1
  46. package/dist/server/plugins/lifecycle.js +1 -1
  47. package/dist/server/plugins/markdown/attribute-resolvers/helpers/load-openapi-bundle.js +1 -1
  48. package/dist/server/plugins/markdown/attribute-resolvers/resolve-link.js +1 -1
  49. package/dist/server/plugins/markdown/attribute-resolvers/resolve-openapi-code-samples.js +1 -1
  50. package/dist/server/plugins/markdown/runtime-transform.js +1 -1
  51. package/dist/server/plugins/markdown/utils/resolve-markdown-template.js +1 -1
  52. package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
  53. package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
  54. package/dist/server/plugins/mcp/utils/route-reservation.d.ts +9 -0
  55. package/dist/server/plugins/mcp/utils/route-reservation.js +1 -0
  56. package/dist/server/plugins/nav-utils.js +1 -1
  57. package/dist/server/plugins/utils.d.ts +0 -4
  58. package/dist/server/plugins/utils.js +1 -1
  59. package/dist/server/utils/content/parse-base-name.d.ts +15 -0
  60. package/dist/server/utils/content/parse-base-name.js +1 -0
  61. package/dist/server/utils/rbac/can-access-feature.d.ts +5 -0
  62. package/dist/server/utils/rbac/can-access-feature.js +1 -0
  63. package/dist/server/utils/rbac/can-anonymous-access-mcp-feature.js +1 -1
  64. package/dist/server/utils/rbac/has-scope-access.d.ts +3 -0
  65. package/dist/server/utils/rbac/has-scope-access.js +1 -0
  66. package/dist/server/utils/rbac.d.ts +5 -3
  67. package/dist/server/utils/rbac.js +1 -1
  68. package/dist/server/web-server/routes/ask-ai.js +1 -1
  69. package/dist/server/web-server/routes/mcp-routes/mcp-client-metadata.js +1 -1
  70. package/dist/server/web-server/routes/semantic-search.js +1 -1
  71. package/package.json +3 -3
@@ -1,2 +1,2 @@
1
- import B from"@redocly/portal-plugin-mock-server";import{REDOCLY_ROUTE_RBAC as x}from"@redocly/config";import{combineUrls as E,withPathPrefix as L}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as k}from"../constants/common.js";import{removeTrailingSlash as N}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as j}from"../../utils/url/remove-leading-slash.js";import{isTruthy as $}from"../../utils/guards/is-truthy.js";import{normalizeRouteSlug as D}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as V}from"../../utils/path/parse-path-versions.js";import{reporter as v}from"../tools/notifiers/reporter.js";import{logger as P}from"../tools/notifiers/logger.js";import{envConfig as S}from"../config/env-config.js";import{shaDirPathShort as M}from"../utils/crypto/sha-dir-path-short.js";import{writeServerRebuildTrigger as _,generateBrowserPluginsModule as q,generateClientRoutes as z,generateTemplatesModule as H}from"../esbuild/generate.js";import{customPagesPlugin as U}from"../../server/plugins/pages/index.js";import{apiDocsPlugin as G}from"../../server/plugins/api-docs/index.js";import{configParserPlugin as I}from"./config-parser/index.js";import{createSlugify as W}from"./create-slugify.js";import{markdownPlugin as K}from"./markdown/index.js";import{searchPlugin as Y}from"./search/index.js";import{skillsPlugin as J}from"./skills/index.js";import{defaultThemePlugin as Q}from"./default-theme/index.js";import{apiKeyMgmtPlugin as X}from"./dev-onboarding/index.js";import{apiFunctionsPlugin as Z}from"./api-functions/index.js";import{scorecardClassicPlugin as ee}from"./scorecard-classic/index.js";import{lintPlugin as te}from"./lint/index.js";import{resolveExternalPlugins as oe}from"../external-plugins/resolve-external-plugins.js";import{sidebarsPlugin as ie}from"./sidebars/index.js";import{l10nPlugin as re}from"./l10n/index.js";import{validateRedirects as ne}from"../utils/redirects/validate-redirects.js";import{analyticsPlugins as se}from"./analytics/index.js";import{consentPlugin as ae}from"./consent/index.js";import{sitemapPlugin as le}from"./sitemap/index.js";import{entitlementsPlugin as ce}from"./entitlements/index.js";import{getBilledPagesCount as ue}from"../utils/index.js";import{telemetry as fe}from"../../cli/telemetry/index.js";import{telemetryTraceStep as b}from"../../cli/telemetry/helpers/trace-step.js";import{EntitlementsProvider as A}from"../entitlements/entitlements-provider.js";import{enforceLoginPlugin as me}from"./enforce-login/index.js";import{ssoPlugin as de}from"./sso/index.js";import{Cache as ge}from"../fs/cache.js";import{ContentFs as pe}from"../fs/content-fs.js";import{findProductBySlug as Pe}from"../utils/product.js";import{isRouteReserved as ye}from"./get-reserved-routes.js";import{catalogClassicPlugin as he}from"./catalog-classic/index.js";import{arazzoDocsPlugin as Re}from"./arazzo-docs/index.js";const Ce=[I,me,de,Q,re,K,G,Re,ee,te,Z,U,X,he,{importPath:"./catalog-entities/plugin.js",loadCondition:()=>S.NEW_CATALOG_ENABLED??!1},{importPath:"./scorecards/plugin.js",loadCondition:()=>S.NEW_SCORECARDS_ENABLED??!1},{importPath:"./mcp/index.js",loadCondition:()=>A.instance().canAccessFeature("mcp")},ie,le,ce,Y,J,B,ae,...se];async function Pt(t,e=Ce){return await b("com.redocly.build.pluginsInit",async()=>{const r=[],R=A.instance(),y={};for(const s of e){let u;if("loadCondition"in s){if(!s.loadCondition())continue;const i=await import(s.importPath);if(!i.default||typeof i.default!="function"){await v.panicOnBuild(`Dynamic plugin ${s.importPath} does not export a default export or it is not a function`);continue}u=i.default}else u=s;const h=await u(t);for(const[i,f]of Object.entries(h.loaders||{}))y[i]&&await v.panicOnBuild(`Duplicate loader with name ${i}`),y[i]=f;(!h.requiredEntitlements||h.requiredEntitlements?.every(i=>R.canAccessFeature(i)))&&r.push(h)}const l=new pe(t.contentDir);await l.ready;const c=new ge(l);return c.setLoaders(y),P.verbose("All plugins instantiated"),{pluginInstances:r,lifecycleContext:be(l,c)}})}function O(t){P.verbose("Generating templates"),b("com.redocly.build.writeClientEntries",()=>{H(t),q(t),z(t)})}async function ve(t){const e=t.getAllRoutes();ue(e)||await v.panicOnBuild("No routes created by plugins. Please check your project configuration.")}async function yt(t,e,r,R={}){const y=A.instance();try{await b("com.redocly.build.pluginsRun",async()=>{e.startPluginsRun();const l=S.isDevelopMode&&e.buildRevision>0,c=l?F(e):"";let s=[];await b("com.redocly.build.pluginsProcessContent",async i=>{for(const o of t){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}s=(await oe(e.contentDir,e.config.plugins)).map(o=>o.lifecyclePlugin).filter(o=>$(o)&&(!o.requiredEntitlements||o.requiredEntitlements?.every(a=>y.canAccessFeature(a)))),r.cache.setLoaders(Object.fromEntries(s.flatMap(o=>Object.entries(o.loaders||{}))));for(const o of s){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}i?.setAttribute("externalPluginsProcessed",s.length.toString())});const u=await we(e,r),h=[...t,...s];O(e),S.isDevelopMode?await e.userCodeReady:e.buildRevision++,await b("com.redocly.build.pluginsAfterRoutesCreated",async()=>{for(const i of h){const f=P.startTiming();await i.afterRoutesCreated?.(e,u),P.verboseTime(f,`afterRoutesCreated for ${i.id}`)}}),ne(e),await e.reportUnsetEnvVars(),await ve(e),O(e),l&&c!==F(e)&&(e.markRequestHandlersEntryOutdated(),_(e.serverOutDir))})}catch(l){const c="Unhandled error in plugin. "+l.message+`
1
+ import B from"@redocly/portal-plugin-mock-server";import{REDOCLY_ROUTE_RBAC as x}from"@redocly/config";import{combineUrls as E,withPathPrefix as L}from"@redocly/theme/core/utils";import{VERSION_SEPARATOR as k}from"../constants/versions.js";import{removeTrailingSlash as N}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as j}from"../../utils/url/remove-leading-slash.js";import{isTruthy as $}from"../../utils/guards/is-truthy.js";import{normalizeRouteSlug as D}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as V}from"../../utils/path/parse-path-versions.js";import{reporter as v}from"../tools/notifiers/reporter.js";import{logger as P}from"../tools/notifiers/logger.js";import{envConfig as S}from"../config/env-config.js";import{shaDirPathShort as M}from"../utils/crypto/sha-dir-path-short.js";import{writeServerRebuildTrigger as _,generateBrowserPluginsModule as q,generateClientRoutes as z,generateTemplatesModule as H}from"../esbuild/generate.js";import{customPagesPlugin as U}from"../../server/plugins/pages/index.js";import{apiDocsPlugin as G}from"../../server/plugins/api-docs/index.js";import{configParserPlugin as I}from"./config-parser/index.js";import{createSlugify as W}from"./create-slugify.js";import{markdownPlugin as K}from"./markdown/index.js";import{searchPlugin as Y}from"./search/index.js";import{skillsPlugin as J}from"./skills/index.js";import{defaultThemePlugin as Q}from"./default-theme/index.js";import{apiKeyMgmtPlugin as X}from"./dev-onboarding/index.js";import{apiFunctionsPlugin as Z}from"./api-functions/index.js";import{scorecardClassicPlugin as ee}from"./scorecard-classic/index.js";import{lintPlugin as te}from"./lint/index.js";import{resolveExternalPlugins as oe}from"../external-plugins/resolve-external-plugins.js";import{sidebarsPlugin as ie}from"./sidebars/index.js";import{l10nPlugin as re}from"./l10n/index.js";import{validateRedirects as ne}from"../utils/redirects/validate-redirects.js";import{analyticsPlugins as se}from"./analytics/index.js";import{consentPlugin as ae}from"./consent/index.js";import{sitemapPlugin as le}from"./sitemap/index.js";import{entitlementsPlugin as ce}from"./entitlements/index.js";import{getBilledPagesCount as ue}from"../utils/index.js";import{telemetry as fe}from"../../cli/telemetry/index.js";import{telemetryTraceStep as b}from"../../cli/telemetry/helpers/trace-step.js";import{EntitlementsProvider as A}from"../entitlements/entitlements-provider.js";import{enforceLoginPlugin as me}from"./enforce-login/index.js";import{ssoPlugin as de}from"./sso/index.js";import{Cache as ge}from"../fs/cache.js";import{ContentFs as pe}from"../fs/content-fs.js";import{findProductBySlug as Pe}from"../utils/product.js";import{isRouteReserved as ye}from"./get-reserved-routes.js";import{catalogClassicPlugin as he}from"./catalog-classic/index.js";import{arazzoDocsPlugin as Re}from"./arazzo-docs/index.js";const Ce=[I,me,de,Q,re,K,G,Re,ee,te,Z,U,X,he,{importPath:"./catalog-entities/plugin.js",loadCondition:()=>S.NEW_CATALOG_ENABLED??!1},{importPath:"./scorecards/plugin.js",loadCondition:()=>S.NEW_SCORECARDS_ENABLED??!1},{importPath:"./mcp/index.js",loadCondition:()=>A.instance().canAccessFeature("mcp")},ie,le,ce,Y,J,B,ae,...se];async function Pt(t,e=Ce){return await b("com.redocly.build.pluginsInit",async()=>{const r=[],R=A.instance(),y={};for(const s of e){let u;if("loadCondition"in s){if(!s.loadCondition())continue;const i=await import(s.importPath);if(!i.default||typeof i.default!="function"){await v.panicOnBuild(`Dynamic plugin ${s.importPath} does not export a default export or it is not a function`);continue}u=i.default}else u=s;const h=await u(t);for(const[i,f]of Object.entries(h.loaders||{}))y[i]&&await v.panicOnBuild(`Duplicate loader with name ${i}`),y[i]=f;(!h.requiredEntitlements||h.requiredEntitlements?.every(i=>R.canAccessFeature(i)))&&r.push(h)}const l=new pe(t.contentDir);await l.ready;const c=new ge(l);return c.setLoaders(y),P.verbose("All plugins instantiated"),{pluginInstances:r,lifecycleContext:be(l,c)}})}function O(t){P.verbose("Generating templates"),b("com.redocly.build.writeClientEntries",()=>{H(t),q(t),z(t)})}async function ve(t){const e=t.getAllRoutes();ue(e)||await v.panicOnBuild("No routes created by plugins. Please check your project configuration.")}async function yt(t,e,r,R={}){const y=A.instance();try{await b("com.redocly.build.pluginsRun",async()=>{e.startPluginsRun();const l=S.isDevelopMode&&e.buildRevision>0,c=l?F(e):"";let s=[];await b("com.redocly.build.pluginsProcessContent",async i=>{for(const o of t){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}s=(await oe(e.contentDir,e.config.plugins)).map(o=>o.lifecyclePlugin).filter(o=>$(o)&&(!o.requiredEntitlements||o.requiredEntitlements?.every(a=>y.canAccessFeature(a)))),r.cache.setLoaders(Object.fromEntries(s.flatMap(o=>Object.entries(o.loaders||{}))));for(const o of s){const a=P.startTiming();await o.processContent?.(e,r),P.verboseTime(a,`processContent for ${o.id}`)}i?.setAttribute("externalPluginsProcessed",s.length.toString())});const u=await we(e,r),h=[...t,...s];O(e),S.isDevelopMode?await e.userCodeReady:e.buildRevision++,await b("com.redocly.build.pluginsAfterRoutesCreated",async()=>{for(const i of h){const f=P.startTiming();await i.afterRoutesCreated?.(e,u),P.verboseTime(f,`afterRoutesCreated for ${i.id}`)}}),ne(e),await e.reportUnsetEnvVars(),await ve(e),O(e),l&&c!==F(e)&&(e.markRequestHandlersEntryOutdated(),_(e.serverOutDir))})}catch(l){const c="Unhandled error in plugin. "+l.message+`
2
2
  `+l.stack;fe.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:c}]),R.failFast?await v.panic(c):await v.panicOnBuild(c)}finally{e.finishPluginsRun()}}async function we(t,e){const{cache:r,fs:R}=e,y=await e.getConfig(),l=Object.values(y.products||{}),c=(await r.load("versions-config","versions-config")).data,s=(await r.load("content-slugs","content-slugs")).data,u=W(s);for(const{duplicateInAllLocales:i,slugSuffix:f,sharedData:o=[],redirectFrom:a=[],...d}of t.newRoutes){const w=D(d.slug?d.slug:u(d.fsPath)),g=N(f?E(w,f):w),n={...d,[x]:{slug:g,fsPath:d.fsPath},slug:g,baseSlug:w,versions:h(d.fsPath,f),product:Pe(l,g,u)};ye(g,y)&&await v.panicOnBuildContentError(`Route "${g}" is reserved and cannot be used. Please choose a different slug for "${d.fsPath}".`),t.routesByFsPath.set(n.fsPath,n.slug),t.routesBySlug.set(n.slug,n);for(const{key:p,id:m}of o)t.addRouteSharedData(n.slug,p,m);for(const p of a)t.addRedirect(p.from,{type:p.type,to:n.slug});if(i)for(const p of R.localeFolders){const m={...n,slug:"/"+p.toLowerCase()+n.slug};t.routesByFsPath.set(m.fsPath,m.slug),t.routesBySlug.set(m.slug,m);for(const{key:C,id:T}of o)t.addRouteSharedData(m.slug,C,T);for(const C of a){const T=E(R.localizationFolder,p,C.from);t.addRedirect(T,{type:C.type,to:m.slug},{trackOriginalSource:!1})}}}return t.newRoutes=[],{...e,slugify:u};function h(i,f=""){const o=V(i);if(!o?.versionName)return;const{versionFolderPath:a,filePathInVersion:d,versionName:w}=o,g=c.get(a);if(g)return g.versions.map(n=>{const p=g.defaultVersion===n.version,m=j(E(a,k+n.version,d)),C=u(m);return{version:n.version,label:n.name||n.version,link:D(E(C,f)),default:p,active:w===n.version,folderId:M(`${a}`)}})}}function be(t,e){return{fs:t,cache:e,getConfig:async(r=".")=>(await e.load(r,"nearest-redocly-config",t.localeFolders)).data,isPathIgnored:async r=>(await e.load(r,"is-ignored")).data,withPathPrefix:L,logger:P}}function F(t){return[...t.apiRoutesRequestHandlers.keys(),...t.getMcpTools().map(e=>`${e.name}:${e.importPath}`)].sort().join(",")}export{Ce as INTERNAL_PLUGINS,be as createLifecycleContext,Pt as initPlugins,yt as runPlugins,O as writeClientEntries};
@@ -1 +1 @@
1
- import{API_DOCS_SHARED_DATA_PREFIX as r}from"../../../../constants/plugins/api-docs.js";import{getNodeAttribute as p}from"../../../../../markdoc/helpers/get-node-attribute.js";import{logger as s}from"../../../../tools/notifiers/logger.js";async function l(i,a){const e=p(i,"descriptionFile");if(typeof e!="string"||!e.startsWith(r))return;const o=e.slice(r.length);try{const{data:t}=await a.cache.load(o,"api-doc"),n=t?.find(d=>d.type==="openapi");return n?{definition:n.document,rawOptions:n.options}:void 0}catch(t){s.verbose(`Failed to load OpenAPI definition ${o} for the ${i.tag} tag: ${t instanceof Error?t.message:"Unknown error"}`);return}}export{l as loadOpenapiBundle};
1
+ import{REDOCLY_ROUTE_RBAC as u,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{API_DOCS_SHARED_DATA_PREFIX as f}from"../../../../constants/plugins/api-docs.js";import{ANONYMOUS_AUTH_DETAILS as l}from"../../../../constants/rbac.js";import{applyL10nToRbacConfig as m,canAccessResource as d,filterDataByAccessDeep as g}from"../../../../utils/rbac.js";import{describeDefinitionAccess as A}from"../../../../plugins/api-docs/definition-access.js";import{createSlugify as R}from"../../../../plugins/create-slugify.js";import{normalizeRouteSlug as h}from"../../../../../utils/path/normalize-route-slug.js";import{getNodeAttribute as D}from"../../../../../markdoc/helpers/get-node-attribute.js";import{logger as b}from"../../../../tools/notifiers/logger.js";const c=new WeakMap;function y(t){return c.has(t)||c.set(t,g(t,l)),c.get(t)}async function O(t,e){const[n,r]=await Promise.all([e.getConfig(),e.cache.load("content-slugs","content-slugs")]),o=R(r.data),{rbac:i,slug:a,sourcePath:s}=A(t,h(o(t.customOutputRelativeFile||t.relativePath)));return d({[p]:i,[u]:{slug:a,fsPath:s}},l,m(e.fs,n.access?.rbac))}async function I(t,e){const n=D(t,"descriptionFile");if(typeof n!="string"||!n.startsWith(f))return;const r=n.slice(f.length);try{const{data:o}=await e.cache.load(r,"api-doc"),i=o?.find(s=>s.type==="openapi");if(!i||!await O(i,e))return;const a=y(i.document);return a&&{definition:a,rawOptions:i.options}}catch(o){b.verbose(`Failed to load OpenAPI definition ${r} for the ${t.tag} tag: ${o instanceof Error?o.message:"Unknown error"}`);return}}export{I as loadOpenapiBundle};
@@ -1 +1 @@
1
- import l from"node:path";import{API_DOCS_TEMPLATE_ID as O,ASYNC_API_DOCS_TEMPLATE_ID as y,GRAPHQL_TEMPLATE_ID as M,OPENAPI_DOCS_TEMPLATE_ID as U}from"../../../../constants/common.js";import{isLocalLink as C}from"../../../../utils/path/is-local-link.js";import{normalizeRouteSlug as P}from"../../../../utils/path/normalize-route-slug.js";import{removeFragment as B}from"../../../../utils/path/remove-fragment.js";import{getInnerText as W}from"../../../../markdoc/helpers/get-inner-text.js";import{getNodeAttribute as j}from"../../../../markdoc/helpers/get-node-attribute.js";import{setNodeAttributeValue as p}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{isAuthRoutePath as $}from"../../../../utils/auth/is-auth-route-path.js";import{isApiDownloadLink as b}from"../../../utils/is-api-download-link.js";import{isTranslationFallback as V}from"../../../fs/utils/is-translation-fallback.js";import{removeL10nPrefix as z}from"../../../fs/utils/remove-l10n-prefix.js";import{MdResolveError as A}from"./md-resolve-error.js";import{getLinkOriginalAttrName as G}from"./utils.js";import{isOpenApiURL as N}from"../../api-docs/utils/is-api-doc.js";import{parseBaseName as q}from"../../utils.js";import{isMarkdownPage as H}from"../is-markdown-page.js";import{copyStaticFile as K}from"../../../utils/fs.js";async function ht(i,s,u,{actions:I,context:m}){const{contentDir:T,outdir:v,getRouteByFsPath:d,getRouteBySlug:k,hasRouteOrRedirectBySlug:w}=I,x=G(s),o=i[x]||j(i,s);if(i[x]=o,!C(o)||b(o)||$(o))return;const[Q,t="",R,L]=/^([^?#]+)?([^#]+)?(.+)?/.exec(o)||[],g=i.type==="image"?"IMAGE":"LINK",h=String(i.attributes.title||i.attributes.alt||W([i])||""),c=B(u);if(i.type!=="image"){const{isOpenapiDetected:e,isOpenapiValid:r}=await N(t,c,I,m);if(e&&!r)throw new A(`OpenAPI route ${o} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g})}if(l.extname(t)===""){if(t.startsWith("/")){const e=P(t),r=w(e)?t:_(e,k);if(!r)throw new A(`Route ${t} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g});p(i,s,r+(R||"")+(L||""))}if(!o.startsWith("#")&&!t.startsWith("/")&&H(c)){const e=d(c)?.slug;if(!e)return;const{isIndexFile:r}=q(c),a=r?P(l.posix.join(e,t)):P(l.posix.join(e,"../",t)),E=w(P(a))?a:_(a,k);if(!E)throw new A(`Route ${t} does not exist`,{rawLink:o,link:a,title:h,brokenLinkType:g});p(i,s,E+(R||"")+(L||""))}return}const n=t.startsWith("/")?t.substring(1):l.posix.join(l.posix.dirname(c),decodeURI(t)),D=t.startsWith("/")?l.posix.join("static",t.substring(1)):"",S=m.fs.exists(n),F=m.fs.exists(D),f=d(n);if(!S&&!f&&!F)throw p(i,s,"#"),new A(`File ${n} does not exist`,{rawLink:o,link:n,title:h,brokenLinkType:g});if(f){const e=[U,M,y].includes(f.templateId);p(i,s,(e?f.baseSlug:f.slug)+(L||""))}else if(S){const e=m.fs.getFileInfo(n),r=V(e)?m.fs.getFileInfo(z(n)):e;if(!r||r.isVirtual)return;const a=await K(T,r.realRelativePath,v);p(i,s,a)}}function _(i,s){const u=s(i.toLowerCase());return u?.templateId===O?u.slug:void 0}export{ht as resolveLink};
1
+ import l from"node:path";import{API_DOCS_TEMPLATE_ID as O,ASYNC_API_DOCS_TEMPLATE_ID as y,GRAPHQL_TEMPLATE_ID as M,OPENAPI_DOCS_TEMPLATE_ID as U}from"../../../../constants/common.js";import{isLocalLink as C}from"../../../../utils/path/is-local-link.js";import{normalizeRouteSlug as P}from"../../../../utils/path/normalize-route-slug.js";import{removeFragment as B}from"../../../../utils/path/remove-fragment.js";import{getInnerText as W}from"../../../../markdoc/helpers/get-inner-text.js";import{getNodeAttribute as j}from"../../../../markdoc/helpers/get-node-attribute.js";import{setNodeAttributeValue as p}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{isAuthRoutePath as $}from"../../../../utils/auth/is-auth-route-path.js";import{isApiDownloadLink as b}from"../../../utils/is-api-download-link.js";import{isTranslationFallback as V}from"../../../fs/utils/is-translation-fallback.js";import{removeL10nPrefix as z}from"../../../fs/utils/remove-l10n-prefix.js";import{parseBaseName as G}from"../../../utils/content/parse-base-name.js";import{MdResolveError as A}from"./md-resolve-error.js";import{getLinkOriginalAttrName as N}from"./utils.js";import{isOpenApiURL as q}from"../../api-docs/utils/is-api-doc.js";import{isMarkdownPage as H}from"../is-markdown-page.js";import{copyStaticFile as K}from"../../../utils/fs.js";async function ht(i,s,u,{actions:I,context:m}){const{contentDir:T,outdir:v,getRouteByFsPath:d,getRouteBySlug:k,hasRouteOrRedirectBySlug:w}=I,x=N(s),o=i[x]||j(i,s);if(i[x]=o,!C(o)||b(o)||$(o))return;const[Q,t="",R,L]=/^([^?#]+)?([^#]+)?(.+)?/.exec(o)||[],g=i.type==="image"?"IMAGE":"LINK",h=String(i.attributes.title||i.attributes.alt||W([i])||""),c=B(u);if(i.type!=="image"){const{isOpenapiDetected:e,isOpenapiValid:r}=await q(t,c,I,m);if(e&&!r)throw new A(`OpenAPI route ${o} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g})}if(l.extname(t)===""){if(t.startsWith("/")){const e=P(t),r=w(e)?t:_(e,k);if(!r)throw new A(`Route ${t} does not exist`,{rawLink:o,link:t,title:h,brokenLinkType:g});p(i,s,r+(R||"")+(L||""))}if(!o.startsWith("#")&&!t.startsWith("/")&&H(c)){const e=d(c)?.slug;if(!e)return;const{isIndexFile:r}=G(c),a=r?P(l.posix.join(e,t)):P(l.posix.join(e,"../",t)),E=w(P(a))?a:_(a,k);if(!E)throw new A(`Route ${t} does not exist`,{rawLink:o,link:a,title:h,brokenLinkType:g});p(i,s,E+(R||"")+(L||""))}return}const n=t.startsWith("/")?t.substring(1):l.posix.join(l.posix.dirname(c),decodeURI(t)),D=t.startsWith("/")?l.posix.join("static",t.substring(1)):"",S=m.fs.exists(n),F=m.fs.exists(D),f=d(n);if(!S&&!f&&!F)throw p(i,s,"#"),new A(`File ${n} does not exist`,{rawLink:o,link:n,title:h,brokenLinkType:g});if(f){const e=[U,M,y].includes(f.templateId);p(i,s,(e?f.baseSlug:f.slug)+(L||""))}else if(S){const e=m.fs.getFileInfo(n),r=V(e)?m.fs.getFileInfo(z(n)):e;if(!r||r.isVirtual)return;const a=await K(T,r.realRelativePath,v);p(i,s,a)}}function _(i,s){const u=s(i.toLowerCase());return u?.templateId===O?u.slug:void 0}export{ht as resolveLink};
@@ -1 +1 @@
1
- import{buildCodeSamples as v,getRequestBodySamples as d,normalizeOptions as f,resolveOperationSampleContext as S}from"@redocly/api-docs";import{setNodeAttributeValue as O}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{loadOpenapiBundle as b}from"./helpers/load-openapi-bundle.js";import{getOptionalAttribute as t}from"./utils.js";const h={curl:"shell",JavaScript:"javascript","Node.js":"javascript",Python:"python",Java:"java","Java8+Apache":"java","C#":"csharp","C#+Newtonsoft":"csharp",PHP:"php",Go:"go",Ruby:"ruby",R:"r"};async function N(e,u,x,{context:g}){const o=await b(e,g);if(!o)return;const i=t(e,"language"),l=t(e,"options"),n={exampleKey:t(e,"exampleKey"),mimeType:t(e,"mimeType"),parameters:t(e,"parameters"),requestBody:t(e,"requestBody"),environments:t(e,"environments"),environment:t(e,"environment")},y={...o.rawOptions,...l,...o.rawOptions.mockServer&&{mockServer:{...o.rawOptions.mockServer,position:"off"}},codeSamples:{...o.rawOptions.codeSamples,...l?.codeSamples,...i&&{languages:[{lang:i}]}}},m=f(y),r=S(o.definition,m,{operationId:t(e,"operationId"),pointer:t(e,"pointer")});if(!r)return;const s=v(r,n).map(a=>({lang:h[a.lang]??a.lang?.toLowerCase(),title:a.label??a.lang,source:a.source})),c=m.codeSamples?.languages??[],p=c.findIndex(({lang:a})=>a==="Payload");if(p!==-1){const a=d(r,{exampleKey:n.exampleKey,mimeType:n.mimeType,titlePrefix:c[p].label});s.splice(p,0,...a)}s.length&&O(e,u,s)}export{N as resolveOpenapiCodeSamples};
1
+ import{buildMarkdownCodeSamples as u,normalizeOptions as f,resolveOperationSampleContext as O}from"@redocly/api-docs";import{setNodeAttributeValue as g}from"../../../../markdoc/helpers/set-node-attribute-value.js";import{loadOpenapiBundle as v}from"./helpers/load-openapi-bundle.js";import{getOptionalAttribute as t}from"./utils.js";async function x(e,p,S,{context:s}){const o=await v(e,s);if(!o)return;const r=t(e,"language"),n=t(e,"options"),m={exampleKey:t(e,"exampleKey"),mimeType:t(e,"mimeType"),parameters:t(e,"parameters"),requestBody:t(e,"requestBody"),environments:t(e,"environments"),environment:t(e,"environment")},l={...o.rawOptions,...n,...o.rawOptions.mockServer&&{mockServer:{...o.rawOptions.mockServer,position:"off"}},codeSamples:{...o.rawOptions.codeSamples,...n?.codeSamples,...r&&{languages:[{lang:r}]}}},c=f(l),i=O(o.definition,c,{operationId:t(e,"operationId"),pointer:t(e,"pointer")});if(!i)return;const a=u(i,m);a.length&&g(e,p,a)}export{x as resolveOpenapiCodeSamples};
@@ -1 +1 @@
1
- import c from"@redocly/markdoc";import{isTag as b}from"../../../markdoc/helpers/guards/is-tag.js";import{slugger as f}from"../../utils/index.js";import{getMarkdocOptions as l}from"./markdoc/markdoc-options.js";import{visit as h,getHeadingData as k,getNumberedItemHeadingData as D}from"./markdoc/plugins/utils.js";import{renderDiagramsWithVariants as H}from"./markdoc/plugins/render-diagrams.js";import{deepStringify as v}from"./markdoc/utils/deep-stringify.js";import{stringifyTagChildrenObjects as y}from"./utils/stringify-tag-children-objects.js";async function S(d,e,p){const g=await l(p),i=[],a=[],o=v(e.variables?.pageProps),{headers:T,...u}=e.variables||{};f.reset();const m=c.transform(d,{...g,...e,variables:{...u,pageProps:o}});let n=0;h(m,r=>{if(b(r)){switch(r.name){case"Heading":{r.attributes.__idx=n,n++;const t=k(r);t&&i.push(t);break}case"NumberedItem":{const t=D(r);t&&i.push(t);break}case"Diagram":a.push({tag:r,input:{type:r.attributes.diagramType,source:r.attributes.diagramSource}});break}y(r)}});const s=await H(a.map(r=>r.input));for(let r=0;r<a.length;r++)a[r].tag.attributes.diagramError=s[r].error,a[r].tag.attributes.diagramHtml=s[r].light,a[r].tag.attributes.diagramHtmlDark=s[r].dark;return{headings:i,renderableAst:m,pageProps:o}}export{S as transformMdAst};
1
+ import b from"@redocly/markdoc";import{isTag as c}from"../../../markdoc/helpers/guards/is-tag.js";import{slugger as f}from"../../utils/index.js";import{getMarkdocOptions as l}from"./markdoc/markdoc-options.js";import{visit as h,getHeadingData as k,getNumberedItemHeadingData as D}from"./markdoc/plugins/utils.js";import{renderDiagramsWithVariants as H}from"./markdoc/plugins/render-diagrams.js";import{deepStringify as v}from"./markdoc/utils/deep-stringify.js";import{stringifyTagChildrenObjects as y}from"./utils/stringify-tag-children-objects.js";async function P(d,i,p){const g=await l(p),s=[],a=[],m=v(i.variables?.pageProps),{headers:T,...u}=i.variables||{};f.reset();const n=b.transform(d,{...g,...i,variables:{...u,pageProps:m}});let e=0;h(n,r=>{if(c(r)){switch(r.name){case"Heading":{r.attributes.__idx=e,e++;const t=k(r);t&&s.push(t);break}case"Hero":r.attributes.__idx=e,e++;break;case"NumberedItem":{const t=D(r);t&&s.push(t);break}case"Diagram":a.push({tag:r,input:{type:r.attributes.diagramType,source:r.attributes.diagramSource}});break}y(r)}});const o=await H(a.map(r=>r.input));for(let r=0;r<a.length;r++)a[r].tag.attributes.diagramError=o[r].error,a[r].tag.attributes.diagramHtml=o[r].light,a[r].tag.attributes.diagramHtmlDark=o[r].dark;return{headings:s,renderableAst:n,pageProps:m}}export{P as transformMdAst};
@@ -1 +1 @@
1
- import i from"path";import{resolveGlobMapValue as p}from"../../../utils/globs.js";function u({realRelativePath:t,frontmatter:e,markdown:r,contentDir:a}){const o=typeof e?.template=="string"?e.template:void 0;if(o)return{templateRef:o,templatePath:l(o,i.posix.dirname(t),a)};const n=p(t,r?.template);return n?{templateRef:n,templatePath:l(n,".",a)}:null}function l(t,e,r){return t.startsWith("./")||t.startsWith("../")?i.resolve(r,e,t):t}export{u as resolveMarkdownTemplate};
1
+ import i from"path";import{resolveGlobMapValue as p}from"../../../utils/globs.js";function f({realRelativePath:e,frontmatter:t,markdown:r,contentDir:o}){const l=typeof t?.template=="string"?s(t.template):void 0;if(l)return{templateRef:l,templatePath:m(l,i.posix.dirname(e),o)};const a=p(e,r?.template),n=a?s(a):void 0;return n?{templateRef:n,templatePath:m(n,".",o)}:null}const u=new Map([["default","@redocly/theme/core/templates/Markdown"],["wide","@redocly/theme/core/templates/Wide"],["full-width","@redocly/theme/core/templates/FullWidth"]]);function s(e){return u.get(e)??e}function m(e,t,r){return e.startsWith("./")||e.startsWith("../")?i.resolve(r,t,e):e}export{f as resolveMarkdownTemplate};
@@ -1,6 +1,6 @@
1
- import{removeTrailingSlash as g,withPathPrefix as y,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../../../constants/common.js";const w=async(n,t)=>{const{query:e,product:o,locale:l}=n,u=t.config.l10n?.defaultLocale||S,h=JSON.stringify({query:e,...o?{product:o}:{},locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${y(L.SEMANTIC_SEARCH)}`,s=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const a=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...s?{Cookie:s}:{}},body:h});if(!a.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await a.json(),d=new Set(t.searchIgnoredRoutes??[]),i=(p||[]).filter(r=>!R(r.url,d));if(i.length===0)return{content:[{type:"text",text:"No results found."}]};const m=r=>{try{return new URL(r,t.baseUrl).toString()}catch{return r}},c=i.map(r=>`### [${r.title}](${m(r.url)})
1
+ import{removeTrailingSlash as y,withPathPrefix as U,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{envConfig as S}from"../../../../../config/env-config.js";import{resolveDocsSiteUrl as v}from"../../../../../plugins/mcp/utils/docs-site-url.js";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as w}from"../../../../../../constants/common.js";const C=async(n,t)=>{const{query:e,product:o,locale:l}=n,u=t.config.l10n?.defaultLocale||w,h=JSON.stringify({query:e,...o?{product:o}:{},locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${U(L.SEMANTIC_SEARCH)}`,s=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const i=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...s?{Cookie:s}:{}},body:h});if(!i.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await i.json(),m=new Set(t.searchIgnoredRoutes??[]),a=(p||[]).filter(r=>!R(r.url,m));if(a.length===0)return{content:[{type:"text",text:"No results found."}]};const d=S.isProductionEnv?v(t.config?.seo?.siteUrl,t.baseUrl):t.baseUrl,g=r=>{try{return new URL(r,d).toString()}catch{return r}},c=a.map(r=>`### [${r.title}](${g(r.url)})
2
2
 
3
3
  ${r.content}
4
4
  `).join(`
5
5
 
6
- `).trim();return{content:[{type:"text",text:c.length?c:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=g(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var v={search:w};export{v as default};
6
+ `).trim();return{content:[{type:"text",text:c.length?c:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=y(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var b={search:C};export{b as default};
@@ -1 +1 @@
1
- import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as M,getInternalOrigin as N}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as L,DEFAULT_ANONYMOUS_VISITOR_TEAM as B,RbacFeatures as H}from"../../../../constants/common.js";import{isObject as j}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as V}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as $}from"../../../utils/skills/get-skill-url.js";import{createMcpHandler as Y}from"@modelcontextprotocol/server";import{createDocsMcpServer as G}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as J,filterGraphqlDescriptionsByRbac as K}from"../utils.js";import{userSubject as z}from"../gateway-mcp/subject.js";import{ipRateLimitKey as X}from"../gateway-mcp/rate-limit/utils/ip-key.js";import{createMethodNotAllowedError as Q,withErrorHandling as W}from"./errors.js";import{constructForbiddenResponse as Z,constructInvalidTokenResponse as q,constructUnauthorizedResponse as x,handleMcpAuth as ee}from"../auth/auth-handlers.js";import{isAssistantAnonymousToken as oe}from"../auth/assistant-anonymous-token.js";import{shouldHandleMcpAuth as re}from"../../../utils/rbac/should-handle-mcp-auth.js";import{extractTokenFromAuthHeader as se}from"../utils/jwt.js";import{resolveMcpClient as ie}from"../utils/mcp-client.js";import{randomUUID as ne}from"../../../utils/crypto/random-uuid.js";import{getPublicMcpEndpointStatus as te}from"../utils/public-endpoint.js";import{narrowMcpConfigForCaller as ce}from"../gateway-mcp/caller-api-calls.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as ae,SSE_KEEPALIVE_INTERVAL_MS as pe}from"../constants.js";import{withPathPrefix as de}from"@redocly/theme/core/utils";import{PUBLIC_MCP_ROUTE as le}from"@redocly/theme/core/constants/mcp";import{canAccessFeature as me}from"../../../utils/rbac.js";import{ANONYMOUS_AUTH_DETAILS as fe}from"../../../constants/rbac.js";const E="X-Redocly-AI-Metadata",ue=1024*1024;function ge(o){if(o)try{const e=JSON.parse(o);if(j(e))return e;A.warn(`Ignoring ${E} header: not a JSON object.`)}catch{A.warn(`Ignoring ${E} header: invalid JSON.`)}}function he(o,e){return new URL(o).searchParams.get("mode")==="tools"?"tools":e}function b(){return{...fe,email:"",idpAccessToken:void 0,idpId:void 0}}const Ae=async(o,e,n)=>{const t=!!e?.config?.access?.requiresLogin,c=e?.config?.access?.rbac||{},I=n?.props?.config?.mcpMode??"tools",p=he(o.url,I),U=n?.props?.config?.gatewayFetchBudgetPerExec??L.budgetPerExec,R=n?.props?.config?.searchIgnoredRoutes??[],r=n,C=!!r?.props?.config?.isPublicEndpoint;let u;const T=o.headers.get("Authorization");if(C)e.user=b();else if(re(t,c)){const{isAuthenticated:i,isTokenValid:d,isFirstPartyAnonymous:g,currentUser:l,accessToken:h}=await ee(o,e);if(g)e.user=b();else if(i)l&&(e.user=l),u=h;else{const a=M(o),m=te(e.config)==="served"?`${a}${de(le)}`:void 0;return d===!1?q(a,m):x(a,m)}}else if(T){const i=se(T)??void 0;u=(i?await oe(i):!1)?void 0:i}const _={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[B],claims:e.user?.claims??{}};return me(H.MCP,_,c,t)?await W(async()=>{const i=p==="code"&&(n?.props?.config?.elicitationEnabled??!1);if(o.method==="GET")return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${o.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(o.method!=="POST")return Q();const d=r?.props?.config?.apiDescriptionsMap||{},g=r?.props?.config?.graphqlDescriptions||[],l=r?.props?.config?.mcpDocsServerName||ae,{config:{mcp:h={}}}=e,a=J(d,e.user,c,t),m=K(g,e.user,c,t),y=e.config.products?Object.values(e.config.products).map(s=>s?.name):[],D=h.docs?.name||l,f=ge(o.headers.get(E)),P=r?.props?.tools||[],O=r?.props?.skillsBaseUrl||M(o),w=V(r?.props?.skills||[],e.user,c,t).map(s=>({slug:s.slug,name:s.name,description:s.description,content:s.content,uri:$(O,s.slug)})),S=r?.props?.fetchCountSecret,F={name:D,tools:P,skills:w,context:{...e,config:{...e.config,mcp:ce(e.config.mcp,f)},configFile:r?.props?.configFile,accessToken:u,outdir:e.outdir||"",baseUrl:e.baseUrl||M(o),internalBaseUrl:N(o),apiDescriptionsMap:a,graphqlDescriptions:m,products:y,metadata:f,mcpMode:p,elicitationEnabled:i,gatewayFetchBudgetPerExec:U,fetchCountRequest:p==="code"&&S?{caller:{subject:z(e.user),ip:X(o)},secret:S}:void 0,searchIgnoredRoutes:R,clientIp:v(o),...ie(o),requestId:ne(),messageId:typeof f?.messageId=="string"?f.messageId:void 0}},k=await G({...F,getKv:e.getKv});return await Y(async()=>k,{keepAliveMs:pe,maxRequestBodySize:ue,onerror:s=>A.warn(`MCP handler: ${s.message}`)}).fetch(o)},p):Z()};var Je=Ae;export{Je as default};
1
+ import{logger as A}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as v}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as M,getInternalOrigin as N}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as L,DEFAULT_ANONYMOUS_VISITOR_TEAM as B,RbacFeatures as H}from"../../../../constants/common.js";import{isObject as j}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as V}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as $}from"../../../utils/skills/get-skill-url.js";import{createMcpHandler as Y}from"@modelcontextprotocol/server";import{createDocsMcpServer as G}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as J,filterGraphqlDescriptionsByRbac as K}from"../utils.js";import{userSubject as z}from"../gateway-mcp/subject.js";import{ipRateLimitKey as X}from"../gateway-mcp/rate-limit/utils/ip-key.js";import{createMethodNotAllowedError as Q,withErrorHandling as W}from"./errors.js";import{constructForbiddenResponse as Z,constructInvalidTokenResponse as q,constructUnauthorizedResponse as x,handleMcpAuth as ee}from"../auth/auth-handlers.js";import{isAssistantAnonymousToken as oe}from"../auth/assistant-anonymous-token.js";import{shouldHandleMcpAuth as re}from"../../../utils/rbac/should-handle-mcp-auth.js";import{extractTokenFromAuthHeader as se}from"../utils/jwt.js";import{resolveMcpClient as ie}from"../utils/mcp-client.js";import{randomUUID as ne}from"../../../utils/crypto/random-uuid.js";import{getPublicMcpEndpointStatus as te}from"../utils/public-endpoint.js";import{narrowMcpConfigForCaller as ce}from"../gateway-mcp/caller-api-calls.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as ae,SSE_KEEPALIVE_INTERVAL_MS as pe}from"../constants.js";import{withPathPrefix as de}from"@redocly/theme/core/utils";import{PUBLIC_MCP_ROUTE as le}from"@redocly/theme/core/constants/mcp";import{canAccessFeature as me}from"../../../utils/rbac/can-access-feature.js";import{ANONYMOUS_AUTH_DETAILS as fe}from"../../../constants/rbac.js";const E="X-Redocly-AI-Metadata",ue=1024*1024;function ge(o){if(o)try{const e=JSON.parse(o);if(j(e))return e;A.warn(`Ignoring ${E} header: not a JSON object.`)}catch{A.warn(`Ignoring ${E} header: invalid JSON.`)}}function he(o,e){return new URL(o).searchParams.get("mode")==="tools"?"tools":e}function b(){return{...fe,email:"",idpAccessToken:void 0,idpId:void 0}}const Ae=async(o,e,n)=>{const t=!!e?.config?.access?.requiresLogin,c=e?.config?.access?.rbac||{},I=n?.props?.config?.mcpMode??"tools",p=he(o.url,I),U=n?.props?.config?.gatewayFetchBudgetPerExec??L.budgetPerExec,R=n?.props?.config?.searchIgnoredRoutes??[],r=n,C=!!r?.props?.config?.isPublicEndpoint;let u;const T=o.headers.get("Authorization");if(C)e.user=b();else if(re(t,c)){const{isAuthenticated:i,isTokenValid:d,isFirstPartyAnonymous:g,currentUser:l,accessToken:h}=await ee(o,e);if(g)e.user=b();else if(i)l&&(e.user=l),u=h;else{const a=M(o),m=te(e.config)==="served"?`${a}${de(le)}`:void 0;return d===!1?q(a,m):x(a,m)}}else if(T){const i=se(T)??void 0;u=(i?await oe(i):!1)?void 0:i}const _={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[B],claims:e.user?.claims??{}};return me(H.MCP,_,c,t)?await W(async()=>{const i=p==="code"&&(n?.props?.config?.elicitationEnabled??!1);if(o.method==="GET")return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${o.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(o.method!=="POST")return Q();const d=r?.props?.config?.apiDescriptionsMap||{},g=r?.props?.config?.graphqlDescriptions||[],l=r?.props?.config?.mcpDocsServerName||ae,{config:{mcp:h={}}}=e,a=J(d,e.user,c,t),m=K(g,e.user,c,t),y=e.config.products?Object.values(e.config.products).map(s=>s?.name):[],D=h.docs?.name||l,f=ge(o.headers.get(E)),P=r?.props?.tools||[],O=r?.props?.skillsBaseUrl||M(o),w=V(r?.props?.skills||[],e.user,c,t).map(s=>({slug:s.slug,name:s.name,description:s.description,content:s.content,uri:$(O,s.slug)})),S=r?.props?.fetchCountSecret,F={name:D,tools:P,skills:w,context:{...e,config:{...e.config,mcp:ce(e.config.mcp,f)},configFile:r?.props?.configFile,accessToken:u,outdir:e.outdir||"",baseUrl:e.baseUrl||M(o),internalBaseUrl:N(o),apiDescriptionsMap:a,graphqlDescriptions:m,products:y,metadata:f,mcpMode:p,elicitationEnabled:i,gatewayFetchBudgetPerExec:U,fetchCountRequest:p==="code"&&S?{caller:{subject:z(e.user),ip:X(o)},secret:S}:void 0,searchIgnoredRoutes:R,clientIp:v(o),...ie(o),requestId:ne(),messageId:typeof f?.messageId=="string"?f.messageId:void 0}},k=await G({...F,getKv:e.getKv});return await Y(async()=>k,{responseMode:o.headers.get("mcp-method")==="tools/call"?"sse":"auto",keepAliveMs:pe,maxRequestBodySize:ue,onerror:s=>A.warn(`MCP handler: ${s.message}`)}).fetch(o)},p):Z()};var Je=Ae;export{Je as default};
@@ -0,0 +1,9 @@
1
+ import type { RedoclyConfig } from '@redocly/config';
2
+ /** Whether the config serves the docs MCP server at `/mcp`. Ignores the `mcp` entitlement. */
3
+ export declare function isMcpRouteServedByConfig(config: Pick<RedoclyConfig, 'mcp'>): boolean;
4
+ /**
5
+ * Whether the config serves the public docs MCP endpoint at `/mcp-public`.
6
+ * Ignores the `mcp` entitlement.
7
+ */
8
+ export declare function isPublicMcpRouteServedByConfig(config: Pick<RedoclyConfig, 'mcp' | 'access'>): boolean;
9
+ //# sourceMappingURL=route-reservation.d.ts.map
@@ -0,0 +1 @@
1
+ import{getPublicMcpEndpointStatus as t}from"./public-endpoint.js";function o(e){return!e?.mcp?.hide&&!e?.mcp?.docs?.hide}function r(e){return t(e)==="served"}export{o as isMcpRouteServedByConfig,r as isPublicMcpRouteServedByConfig};
@@ -1 +1 @@
1
- import*as h from"path";import{REDOCLY_ROUTE_RBAC as b,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{VERSION_SEPARATOR as x}from"../constants/common.js";import{DEFAULT_LOCALE_PLACEHOLDER as M}from"../../constants/common.js";import{removeTrailingSlash as j}from"../../utils/url/remove-trailing-slash.js";import{isPrimitive as W}from"../../utils/guards/is-primitive.js";import{slash as w}from"../../utils/path/slash.js";import{isAbsoluteUrl as z}from"../../utils/url/is-absolute-url.js";import{normalizeRouteSlug as J}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as C}from"../../utils/path/parse-path-versions.js";import{logger as A}from"../tools/notifiers/logger.js";import{reporter as F}from"../tools/notifiers/reporter.js";import{shaDirPathShort as R}from"../utils/crypto/sha-dir-path-short.js";import{copyStaticFile as U,FileNotFoundError as D}from"../utils/fs.js";import{isIconPath as H,resolveAssetPath as Y}from"../utils/index.js";import{resolveSrcSet as G}from"../utils/resolve-src-set.js";import{isL10nPath as E}from"../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as q}from"../fs/utils/get-locale-from-relative-path.js";async function B(e,i,n,s,a){if(!e)return;const f={...a,ignoreCustomSidebar:!0};if(W(e)){if(typeof e=="string"){const r=I(n.contentDir,i,a,e,s.fs);if(s.fs.exists(r)){if(n.getRouteByFsPath(r))return K({page:e},i,n,s,f);{const g=s.fs.getFileInfo(r);return g?U(n.contentDir,g.realRelativePath,n.outdir):void 0}}}return e}return Array.isArray(e)?k(N(e),i,n,s,f):Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,l])=>[r,await B(l,i,n,s,a)])))}function N(e){return e.map(i=>({...i,items:i.items?N(i.items):void 0}))}async function k(e,i,n,s,a){if(Array.isArray(e))return(await Promise.all(e.map(f=>K(f,i,n,s,a)))).flatMap(f=>f)}async function y(e,i,n,s){let a,f;if(typeof e.icon=="object"){if("srcSet"in e.icon)try{a=await G(e.icon.srcSet,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`):await F.panicOnBuild(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`)}}else if(typeof e.icon=="string")if(z(e.icon)||H(e.icon))try{f=await Y(e.icon,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon" from ${s.navFile}: file ${f} does not exist`):await F.panicOnBuild(`Cannot resolve "item.icon" from ${s.navFile}: ${d.message}`)}else f=e.icon;return{icon:f,srcSet:a}}function Q(e){return i=>{if(i.type==="link"||i.type==="group"){const n=i.metadata;return n?Object.entries(e).every(([s,a])=>Array.isArray(a)?a.some(f=>n[s]===f):n[s]===a):!1}return!0}}async function K(e,i,n,s,a){if(e?.tab!==void 0||e?.menu!==void 0){const t=`Navigation tabs ("tab"/"menu") are only allowed at the top level of a sidebars.yaml file: ${JSON.stringify(e)}`;return await F.panicOnBuildContentError(`Invalid nav item in %rp. ${t}`,a.navFile),{type:"error",label:t}}if(e?.directory&&e.items?.length)return{type:"error",label:`Can't have both "directory" and "items" in the nav item: ${JSON.stringify(e)}`};e?.directory&&e?.group&&(e={...e,directory:void 0,items:[{directory:e.directory}]});const f=e?.directory?I(n.contentDir,i,a,e.directory,s.fs):void 0;if(f!==void 0){const t=f===""?"":f+"/",{locale:u,ignoredRoutes:o}=a,v=n.getAllRoutesForLocale(u).filter(c=>!o?.has(c.baseSlug||"")&&c.fsPath.startsWith(t)&&!c.excludeFromSidebar).sort((c,P)=>c.fsPath===P.fsPath?0:c.baseSlug.localeCompare(P.baseSlug,void 0,{numeric:!0})),L=e.includeByMetadata?Q(e.includeByMetadata):Boolean;if(!v.length)return[];const T=(await Promise.all(v.map(async c=>{const P=c.versions?.find(_=>_.active),S=P&&{version:P.version,isDefault:P.default,versionFolderId:P.folderId},V=ee(h.posix.relative(f,c.fsPath)),O=c.getSidebar?.(c);return!a.ignoreCustomSidebar&&O?.length?{type:"group",fsPath:c.fsPath,metadata:c.metadata,link:c.slug,routeSlug:c.slug,label:await c.getNavText?.()||c.slug,[p]:c[p],[b]:c[b],sidebarItems:m(O,S,c[p],c[b]),version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:h.relative(f,c.fsPath).replace(/@(?<!@[^/]*?@)[^/]+\//,"")}:{type:"link",fsPath:c.fsPath,metadata:c.metadata,[p]:c[p],[b]:c[b],label:await c.getNavText?.()||c.slug,link:c.slug,routeSlug:c.slug,version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:V}}))).filter(L);return e.flatten?$(T,a):Z(T,a)}let d=typeof e=="string"?e:e?.page,r,l;if(d){if(d.includes("#")){const[t,u]=d.split("#");u?l=u:A.warn(`Invalid heading anchor format in sidebar: "${u}". Heading anchors should contain only alphanumeric characters, hyphens, and underscores.`),d=t}if(d=j(d),a.locale&&a.locale!==M){const t=J(h.join(a.locale.toLowerCase(),d));r=n.getRouteBySlug(t)}r||(r=n.getRouteBySlug(d)),r||(r=n.getRouteByFsPath(I(n.contentDir,i,a,d,s.fs)))}const g=r?.metadata;if(e?.$ref){let t=I(n.contentDir,i,a,e.$ref,s.fs);if(a.ref!==void 0&&(t=h.posix.join(a.ref,e.$ref)),!s.fs.exists(t))return await F.panicOnBuildContentError(`Failed to load ${t} file. Make sure sidebar $ref path is correct.`),[];const u=await s.cache.load(t,"yaml"),o=h.dirname(t);return await k(u.data,i,n,s,{...a,navFile:t,ref:o})||[]}if(!r){const t=a.excludedFromLinkCheckerPatterns?.catalog.some(o=>o.test(d||"")),u=a.excludedFromLinkCheckerPatterns?.apiFunctions.some(o=>o.test(d||e.href||""));(u||t)&&(e={...e,href:d||e.href,page:void 0,target:e.target??(u?"_blank":void 0)}),await X(e,a,s,i)}if(r&&!e.disconnect&&!a.ignoreCustomSidebar&&(l||r?.getSidebar)){const t=r.versions?.find(o=>o.active),u=t&&{version:t.version,isDefault:t.default,versionFolderId:t.folderId};if(l){let o=[];if(r.getSidebar&&(o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),o&&o.length>0)){const v=o[0];v&&v.link&&(v.link=`${v.link}#${l}`)}if(!o||o.length===0){const v=e.group||e.label||l;o=[{type:"link",fsPath:r.fsPath,metadata:r.metadata,link:`${r.slug}#${l}`,routeSlug:r.slug,label:v,labelTranslationKey:e.labelTranslationKey,...await y(e,n,s,a),[p]:r[p],[b]:{slug:r.slug,fsPath:r.fsPath},...u}]}return m(o,u,r[p],r[b])}if(r?.getSidebar){const o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),v=e.group&&o?.[0]?.routeSlug===r.slug?o.slice(1):o;return m(a.groupCustomSidebars||e.group?[{type:"group",fsPath:r.fsPath,link:r.slug,routeSlug:r.slug,label:e.group||e.label||await r.getNavText?.()||r.slug,items:v,labelTranslationKey:e.labelTranslationKey,metadata:g,badges:e.badges,...await y(e,n,s,a)}]:o,u,r[p],r[b])}}if(r&&!e.group){const t=l?`${r.slug}#${l}`:r.slug;let u=e.label||l||"";u||(u=await r.getNavText?.()||r.slug);const o=r.versions?.find(L=>L.active),v=o&&{version:o.version,isDefault:o.default,versionFolderId:o.folderId};return{type:"link",fsPath:r.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,[p]:e?.rbac||r[p],[b]:{slug:r.slug,fsPath:r.fsPath},label:u,labelTranslationKey:e.labelTranslationKey,link:t,items:await k(e.items,i,n,s,a),separatorLine:e.separatorLine,linePosition:e.linePosition,routeSlug:e.disconnect?void 0:t,external:e.external,target:e.target,badges:e.badges,...await y(e,n,s,a),...v,additionalProps:e.additionalProps}}else if(e?.group){const t=r?.versions?.find(o=>o.active),u=C(a?.navFile);return{type:"group",fsPath:r?.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,version:t?.version||u?.versionName,versionFolderId:t?.folderId||(u?.versionFolderPath?R(u.versionFolderPath):void 0),label:e.group,link:r?.slug,routeSlug:r?.slug,badges:e.badges,labelTranslationKey:e.groupTranslationKey,items:await k(e.items,i,n,s,a),expanded:e.expanded?e.expanded.toString():void 0,selectFirstItemOnExpand:e.selectFirstItemOnExpand,menuStyle:e.menuStyle,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,[b]:{slug:r?.slug||"",fsPath:r?.fsPath||""},additionalProps:e.additionalProps}}else{if(e?.href||e?.label)return{type:"link",metadata:g,link:e.href||"",label:e?.label||e?.href||"",labelTranslationKey:e.labelTranslationKey,external:e.external,target:e.target,separatorLine:e.separatorLine,linePosition:e.linePosition,badges:e.badges,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps};if(e?.separator!=null||e?.separatorLine!=null){const t=C(a?.navFile);return{type:"separator",metadata:g,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0,label:e.separator,labelTranslationKey:e.separatorTranslationKey,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps}}else{const t=C(a?.navFile);return{type:"error",label:`Can't resolve page: ${JSON.stringify(e)}`,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0}}}}async function X(e,i,n,s){const{href:a,page:f}=e;if(a||!f)return;const d=I(n.fs.cwd,s,i,f,n.fs),r=n.fs.exists(d),l=await n.isPathIgnored(d),g=(r?"The page is ignored: ":"Can't resolve page: ")+f;(!r||l)&&F.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",title:e.label||e.group||"",link:d,rawLink:f,message:g,sourceFileRelativePath:i.navFile,sourceFileLocation:{line:0}})}function I(e,i,n,s="",a){if(n.ref!==void 0)return w(h.relative(e,h.resolve(e,h.join(n.ref,s))));if(s.startsWith("/")){const f=E(i)?q(i):void 0,d=f?`${a.localizationFolder}/${f}/`:"",r=s.slice(1);return E(r)?r:d+w(r)}return w(h.relative(e,h.resolve(e,i,s)))}function Z(e,i){const n={};for(const r of e){const l=h.dirname(r.relativePathFromDirectory),g=r.version?x+r.version:"",t=h.basename(r.relativePathFromDirectory)+g;d(l,r,t)}const s=f(a(n));return $(s,i);function a(r){const l=[];for(const g of Object.keys(r)){const t=r[g];l.push({...t,items:t.items?a(t.items):void 0})}return l}function f(r){return r.sort((l,g)=>{const t=typeof l=="string"?l.toLowerCase():l.relativePathFromDirectory||l.label||"",u=typeof g=="string"?g.toLowerCase():g.relativePathFromDirectory||g.label||"";return t.startsWith("index.")?-1:u.startsWith("index.")?1:t.localeCompare(u,void 0,{numeric:!0})})}function d(r,l,g){r==="."&&(r="");const t=r.split("/").filter(Boolean);let u=n;for(const o of t){const v=o+(l?.version||"");u[v]||(u[v]={type:"group",version:l?.version,label:o,isDefault:l?.isDefault,versionFolderId:l.versionFolderId,items:{}}),u=u[v].items}u[g]=l}}function $(e,i){return e.flatMap(n=>n?.sidebarItems?i.groupCustomSidebars?{...n,items:n.sidebarItems,sidebarItems:void 0,relativePathFromDirectory:void 0}:n.sidebarItems:{...n,items:n.items?$(n.items,i):void 0})}function m(e,i,n,s){return e.map(a=>({...a,...i,[p]:a[p]||n,[b]:a[b]||s,items:a.type==="group"&&a.items?m(a.items,i,n):a.items}))}function ee(e){return e.replace(/@(?<!@[^/]*?@)[^/]+\//,"")}async function ye(e,i,n,s){const a=(e?.items||[]).filter(r=>r.linkedSidebars?.length).map(({items:r,...l})=>l),f=await B(a,i.contentDir,i,n,s),d=new Map;for(const r of f)if(r.linkedSidebars?.length)for(const l of r.linkedSidebars){if(d.has(l)){A.warn(`Only one navbar item can belong to sidebar. "${l}" on 'linkedSidebars' property on "${r.label}" will be ignored.`);continue}d.set(l,{label:r.label,link:r.link})}return d}export{ye as collectItemsLinkedToSidebars,N as normalizeItems,K as resolveItem,k as resolveItems,B as resolveLinksFromConfig};
1
+ import*as h from"path";import{REDOCLY_ROUTE_RBAC as b,REDOCLY_TEAMS_RBAC as p}from"@redocly/config";import{VERSION_SEPARATOR as x}from"../constants/versions.js";import{DEFAULT_LOCALE_PLACEHOLDER as M}from"../../constants/common.js";import{removeTrailingSlash as j}from"../../utils/url/remove-trailing-slash.js";import{isPrimitive as W}from"../../utils/guards/is-primitive.js";import{slash as w}from"../../utils/path/slash.js";import{isAbsoluteUrl as z}from"../../utils/url/is-absolute-url.js";import{normalizeRouteSlug as J}from"../../utils/path/normalize-route-slug.js";import{parsePathVersions as C}from"../../utils/path/parse-path-versions.js";import{logger as A}from"../tools/notifiers/logger.js";import{reporter as F}from"../tools/notifiers/reporter.js";import{shaDirPathShort as R}from"../utils/crypto/sha-dir-path-short.js";import{copyStaticFile as U,FileNotFoundError as D}from"../utils/fs.js";import{isIconPath as H,resolveAssetPath as Y}from"../utils/index.js";import{resolveSrcSet as G}from"../utils/resolve-src-set.js";import{isL10nPath as E}from"../fs/utils/is-l10n-path.js";import{getLocaleFromRelativePath as q}from"../fs/utils/get-locale-from-relative-path.js";async function B(e,i,n,s,a){if(!e)return;const f={...a,ignoreCustomSidebar:!0};if(W(e)){if(typeof e=="string"){const r=I(n.contentDir,i,a,e,s.fs);if(s.fs.exists(r)){if(n.getRouteByFsPath(r))return K({page:e},i,n,s,f);{const g=s.fs.getFileInfo(r);return g?U(n.contentDir,g.realRelativePath,n.outdir):void 0}}}return e}return Array.isArray(e)?k(N(e),i,n,s,f):Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,l])=>[r,await B(l,i,n,s,a)])))}function N(e){return e.map(i=>({...i,items:i.items?N(i.items):void 0}))}async function k(e,i,n,s,a){if(Array.isArray(e))return(await Promise.all(e.map(f=>K(f,i,n,s,a)))).flatMap(f=>f)}async function y(e,i,n,s){let a,f;if(typeof e.icon=="object"){if("srcSet"in e.icon)try{a=await G(e.icon.srcSet,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`):await F.panicOnBuild(`Cannot resolve "item.icon.srcSet" from ${s.navFile}: ${d.message}`)}}else if(typeof e.icon=="string")if(z(e.icon)||H(e.icon))try{f=await Y(e.icon,n.fs,{fromFileRelativePath:s.navFile,contentDir:i.contentDir,outdir:i.outdir})}catch(d){d instanceof D?await F.panicOnBuildContentError(`Cannot resolve "item.icon" from ${s.navFile}: file ${f} does not exist`):await F.panicOnBuild(`Cannot resolve "item.icon" from ${s.navFile}: ${d.message}`)}else f=e.icon;return{icon:f,srcSet:a}}function Q(e){return i=>{if(i.type==="link"||i.type==="group"){const n=i.metadata;return n?Object.entries(e).every(([s,a])=>Array.isArray(a)?a.some(f=>n[s]===f):n[s]===a):!1}return!0}}async function K(e,i,n,s,a){if(e?.tab!==void 0||e?.menu!==void 0){const t=`Navigation tabs ("tab"/"menu") are only allowed at the top level of a sidebars.yaml file: ${JSON.stringify(e)}`;return await F.panicOnBuildContentError(`Invalid nav item in %rp. ${t}`,a.navFile),{type:"error",label:t}}if(e?.directory&&e.items?.length)return{type:"error",label:`Can't have both "directory" and "items" in the nav item: ${JSON.stringify(e)}`};e?.directory&&e?.group&&(e={...e,directory:void 0,items:[{directory:e.directory}]});const f=e?.directory?I(n.contentDir,i,a,e.directory,s.fs):void 0;if(f!==void 0){const t=f===""?"":f+"/",{locale:u,ignoredRoutes:o}=a,v=n.getAllRoutesForLocale(u).filter(c=>!o?.has(c.baseSlug||"")&&c.fsPath.startsWith(t)&&!c.excludeFromSidebar).sort((c,P)=>c.fsPath===P.fsPath?0:c.baseSlug.localeCompare(P.baseSlug,void 0,{numeric:!0})),L=e.includeByMetadata?Q(e.includeByMetadata):Boolean;if(!v.length)return[];const T=(await Promise.all(v.map(async c=>{const P=c.versions?.find(_=>_.active),S=P&&{version:P.version,isDefault:P.default,versionFolderId:P.folderId},V=ee(h.posix.relative(f,c.fsPath)),O=c.getSidebar?.(c);return!a.ignoreCustomSidebar&&O?.length?{type:"group",fsPath:c.fsPath,metadata:c.metadata,link:c.slug,routeSlug:c.slug,label:await c.getNavText?.()||c.slug,[p]:c[p],[b]:c[b],sidebarItems:m(O,S,c[p],c[b]),version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:h.relative(f,c.fsPath).replace(/@(?<!@[^/]*?@)[^/]+\//,"")}:{type:"link",fsPath:c.fsPath,metadata:c.metadata,[p]:c[p],[b]:c[b],label:await c.getNavText?.()||c.slug,link:c.slug,routeSlug:c.slug,version:S?.version,isDefault:S?.isDefault,versionFolderId:S?.versionFolderId,relativePathFromDirectory:V}}))).filter(L);return e.flatten?$(T,a):Z(T,a)}let d=typeof e=="string"?e:e?.page,r,l;if(d){if(d.includes("#")){const[t,u]=d.split("#");u?l=u:A.warn(`Invalid heading anchor format in sidebar: "${u}". Heading anchors should contain only alphanumeric characters, hyphens, and underscores.`),d=t}if(d=j(d),a.locale&&a.locale!==M){const t=J(h.join(a.locale.toLowerCase(),d));r=n.getRouteBySlug(t)}r||(r=n.getRouteBySlug(d)),r||(r=n.getRouteByFsPath(I(n.contentDir,i,a,d,s.fs)))}const g=r?.metadata;if(e?.$ref){let t=I(n.contentDir,i,a,e.$ref,s.fs);if(a.ref!==void 0&&(t=h.posix.join(a.ref,e.$ref)),!s.fs.exists(t))return await F.panicOnBuildContentError(`Failed to load ${t} file. Make sure sidebar $ref path is correct.`),[];const u=await s.cache.load(t,"yaml"),o=h.dirname(t);return await k(u.data,i,n,s,{...a,navFile:t,ref:o})||[]}if(!r){const t=a.excludedFromLinkCheckerPatterns?.catalog.some(o=>o.test(d||"")),u=a.excludedFromLinkCheckerPatterns?.apiFunctions.some(o=>o.test(d||e.href||""));(u||t)&&(e={...e,href:d||e.href,page:void 0,target:e.target??(u?"_blank":void 0)}),await X(e,a,s,i)}if(r&&!e.disconnect&&!a.ignoreCustomSidebar&&(l||r?.getSidebar)){const t=r.versions?.find(o=>o.active),u=t&&{version:t.version,isDefault:t.default,versionFolderId:t.folderId};if(l){let o=[];if(r.getSidebar&&(o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),o&&o.length>0)){const v=o[0];v&&v.link&&(v.link=`${v.link}#${l}`)}if(!o||o.length===0){const v=e.group||e.label||l;o=[{type:"link",fsPath:r.fsPath,metadata:r.metadata,link:`${r.slug}#${l}`,routeSlug:r.slug,label:v,labelTranslationKey:e.labelTranslationKey,...await y(e,n,s,a),[p]:r[p],[b]:{slug:r.slug,fsPath:r.fsPath},...u}]}return m(o,u,r[p],r[b])}if(r?.getSidebar){const o=r.getSidebar(r,{...e,...await y(e,n,s,a)}),v=e.group&&o?.[0]?.routeSlug===r.slug?o.slice(1):o;return m(a.groupCustomSidebars||e.group?[{type:"group",fsPath:r.fsPath,link:r.slug,routeSlug:r.slug,label:e.group||e.label||await r.getNavText?.()||r.slug,items:v,labelTranslationKey:e.labelTranslationKey,metadata:g,badges:e.badges,...await y(e,n,s,a)}]:o,u,r[p],r[b])}}if(r&&!e.group){const t=l?`${r.slug}#${l}`:r.slug;let u=e.label||l||"";u||(u=await r.getNavText?.()||r.slug);const o=r.versions?.find(L=>L.active),v=o&&{version:o.version,isDefault:o.default,versionFolderId:o.folderId};return{type:"link",fsPath:r.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,[p]:e?.rbac||r[p],[b]:{slug:r.slug,fsPath:r.fsPath},label:u,labelTranslationKey:e.labelTranslationKey,link:t,items:await k(e.items,i,n,s,a),separatorLine:e.separatorLine,linePosition:e.linePosition,routeSlug:e.disconnect?void 0:t,external:e.external,target:e.target,badges:e.badges,...await y(e,n,s,a),...v,additionalProps:e.additionalProps}}else if(e?.group){const t=r?.versions?.find(o=>o.active),u=C(a?.navFile);return{type:"group",fsPath:r?.fsPath,linkedSidebars:e.linkedSidebars,metadata:g,version:t?.version||u?.versionName,versionFolderId:t?.folderId||(u?.versionFolderPath?R(u.versionFolderPath):void 0),label:e.group,link:r?.slug,routeSlug:r?.slug,badges:e.badges,labelTranslationKey:e.groupTranslationKey,items:await k(e.items,i,n,s,a),expanded:e.expanded?e.expanded.toString():void 0,selectFirstItemOnExpand:e.selectFirstItemOnExpand,menuStyle:e.menuStyle,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,[b]:{slug:r?.slug||"",fsPath:r?.fsPath||""},additionalProps:e.additionalProps}}else{if(e?.href||e?.label)return{type:"link",metadata:g,link:e.href||"",label:e?.label||e?.href||"",labelTranslationKey:e.labelTranslationKey,external:e.external,target:e.target,separatorLine:e.separatorLine,linePosition:e.linePosition,badges:e.badges,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps};if(e?.separator!=null||e?.separatorLine!=null){const t=C(a?.navFile);return{type:"separator",metadata:g,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0,label:e.separator,labelTranslationKey:e.separatorTranslationKey,separatorLine:e.separatorLine,linePosition:e.linePosition,...await y(e,n,s,a),[p]:e?.rbac,additionalProps:e.additionalProps}}else{const t=C(a?.navFile);return{type:"error",label:`Can't resolve page: ${JSON.stringify(e)}`,version:t?.versionName,versionFolderId:t?.versionFolderPath?R(t.versionFolderPath):void 0}}}}async function X(e,i,n,s){const{href:a,page:f}=e;if(a||!f)return;const d=I(n.fs.cwd,s,i,f,n.fs),r=n.fs.exists(d),l=await n.isPathIgnored(d),g=(r?"The page is ignored: ":"Can't resolve page: ")+f;(!r||l)&&F.reportBrokenLink({type:"BROKEN_LINK",brokenLinkType:"LINK",title:e.label||e.group||"",link:d,rawLink:f,message:g,sourceFileRelativePath:i.navFile,sourceFileLocation:{line:0}})}function I(e,i,n,s="",a){if(n.ref!==void 0)return w(h.relative(e,h.resolve(e,h.join(n.ref,s))));if(s.startsWith("/")){const f=E(i)?q(i):void 0,d=f?`${a.localizationFolder}/${f}/`:"",r=s.slice(1);return E(r)?r:d+w(r)}return w(h.relative(e,h.resolve(e,i,s)))}function Z(e,i){const n={};for(const r of e){const l=h.dirname(r.relativePathFromDirectory),g=r.version?x+r.version:"",t=h.basename(r.relativePathFromDirectory)+g;d(l,r,t)}const s=f(a(n));return $(s,i);function a(r){const l=[];for(const g of Object.keys(r)){const t=r[g];l.push({...t,items:t.items?a(t.items):void 0})}return l}function f(r){return r.sort((l,g)=>{const t=typeof l=="string"?l.toLowerCase():l.relativePathFromDirectory||l.label||"",u=typeof g=="string"?g.toLowerCase():g.relativePathFromDirectory||g.label||"";return t.startsWith("index.")?-1:u.startsWith("index.")?1:t.localeCompare(u,void 0,{numeric:!0})})}function d(r,l,g){r==="."&&(r="");const t=r.split("/").filter(Boolean);let u=n;for(const o of t){const v=o+(l?.version||"");u[v]||(u[v]={type:"group",version:l?.version,label:o,isDefault:l?.isDefault,versionFolderId:l.versionFolderId,items:{}}),u=u[v].items}u[g]=l}}function $(e,i){return e.flatMap(n=>n?.sidebarItems?i.groupCustomSidebars?{...n,items:n.sidebarItems,sidebarItems:void 0,relativePathFromDirectory:void 0}:n.sidebarItems:{...n,items:n.items?$(n.items,i):void 0})}function m(e,i,n,s){return e.map(a=>({...a,...i,[p]:a[p]||n,[b]:a[b]||s,items:a.type==="group"&&a.items?m(a.items,i,n):a.items}))}function ee(e){return e.replace(/@(?<!@[^/]*?@)[^/]+\//,"")}async function ye(e,i,n,s){const a=(e?.items||[]).filter(r=>r.linkedSidebars?.length).map(({items:r,...l})=>l),f=await B(a,i.contentDir,i,n,s),d=new Map;for(const r of f)if(r.linkedSidebars?.length)for(const l of r.linkedSidebars){if(d.has(l)){A.warn(`Only one navbar item can belong to sidebar. "${l}" on 'linkedSidebars' property on "${r.label}" will be ignored.`);continue}d.set(l,{label:r.label,link:r.link})}return d}export{ye as collectItemsLinkedToSidebars,N as normalizeItems,K as resolveItem,k as resolveItems,B as resolveLinksFromConfig};
@@ -1,10 +1,6 @@
1
1
  import type { ContentFs } from '../fs/content-fs.js';
2
2
  import type { LifecycleContext } from '../types';
3
3
  export declare function resolveFrontmatterSlugs(slugs: unknown, relativePath: string): string[];
4
- export declare function parseBaseName(relativePath: string): {
5
- baseName: string;
6
- isIndexFile: boolean;
7
- };
8
4
  export declare function findFrontmatterSlugs(relativePath: string, loaderName: string, frontmatter: Record<string, any> | undefined, context: LifecycleContext): Promise<string[] | undefined>;
9
5
  export declare function getSidebarSharedDataId(sidebar: string | {
10
6
  path: string;
@@ -1 +1 @@
1
- import a from"path";import{DEFAULT_LOCALE_PLACEHOLDER as m}from"../../constants/common.js";import{normalizeRouteSlug as l}from"../../utils/path/normalize-route-slug.js";import{slash as i}from"../../utils/path/slash.js";import{logger as u}from"../tools/notifiers/logger.js";import{getLocaleFromRelativePath as f}from"../fs/utils/get-locale-from-relative-path.js";import{isL10nPath as p}from"../fs/utils/is-l10n-path.js";import{removeL10nPrefix as c}from"../fs/utils/remove-l10n-prefix.js";import{resolveSidebarId as d}from"./sidebars/index.js";function b(e,r){return(Array.isArray(e)?e:e?[e]:[]).map(o=>g(o,r))}function g(e,r){const t=f(r).toLowerCase(),o=l(e);return t!==m?`/${t}${o}`:o}function I(e){const r=e.endsWith(".page.tsx")?".page.tsx":a.posix.extname(e),t=a.posix.basename(e,r);return{baseName:t,isIndexFile:t==="index"}}async function P(e,r,t,o){if(t?.slug||!p(e))return t?.slug;const n=c(e);if(!o.fs.exists(n))return;const{data:s}=await o.cache.load(n,r);return s?.frontmatter?.slug}async function w(e,r,t){const o=typeof e=="string",n=o?e:e.path;return o&&u.warnForRealFile("The 'sidebar' property in the front matter of %rp is deprecated. Use 'sidebar.path' instead.",r,t),n?d(r,n,t):null}function C(e,r){return e.filter(t=>i(t.fsPath)===i(r)).map(t=>t.slug)}export{P as findFrontmatterSlugs,C as getRouteSlugsForPath,w as getSidebarSharedDataId,I as parseBaseName,b as resolveFrontmatterSlugs};
1
+ import{DEFAULT_LOCALE_PLACEHOLDER as s}from"../../constants/common.js";import{normalizeRouteSlug as l}from"../../utils/path/normalize-route-slug.js";import{slash as n}from"../../utils/path/slash.js";import{logger as u}from"../tools/notifiers/logger.js";import{getLocaleFromRelativePath as f}from"../fs/utils/get-locale-from-relative-path.js";import{isL10nPath as m}from"../fs/utils/is-l10n-path.js";import{removeL10nPrefix as p}from"../fs/utils/remove-l10n-prefix.js";import{resolveSidebarId as c}from"./sidebars/index.js";function E(r,e){return(Array.isArray(r)?r:r?[r]:[]).map(o=>d(o,e))}function d(r,e){const t=f(e).toLowerCase(),o=l(r);return t!==s?`/${t}${o}`:o}async function P(r,e,t,o){if(t?.slug||!m(r))return t?.slug;const a=p(r);if(!o.fs.exists(a))return;const{data:i}=await o.cache.load(a,e);return i?.frontmatter?.slug}async function R(r,e,t){const o=typeof r=="string",a=o?r:r.path;return o&&u.warnForRealFile("The 'sidebar' property in the front matter of %rp is deprecated. Use 'sidebar.path' instead.",e,t),a?c(e,a,t):null}function v(r,e){return r.filter(t=>n(t.fsPath)===n(e)).map(t=>t.slug)}export{P as findFrontmatterSlugs,v as getRouteSlugsForPath,R as getSidebarSharedDataId,E as resolveFrontmatterSlugs};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Splits a content file path into the name its route is built from and whether it is an index.
3
+ *
4
+ * @param relativePath - Path relative to the content root; `.page.tsx` counts as one extension.
5
+ * @returns The file name without its extension, and `isIndexFile` when that name is `index`.
6
+ *
7
+ * @example
8
+ * parseBaseName('docs/index.page.tsx');
9
+ * // Returns: { baseName: 'index', isIndexFile: true }
10
+ */
11
+ export declare function parseBaseName(relativePath: string): {
12
+ baseName: string;
13
+ isIndexFile: boolean;
14
+ };
15
+ //# sourceMappingURL=parse-base-name.d.ts.map
@@ -0,0 +1 @@
1
+ import n from"path";function i(e){const x=e.endsWith(".page.tsx")?".page.tsx":n.posix.extname(e),s=n.posix.basename(e,x);return{baseName:s,isIndexFile:s==="index"}}export{i as parseBaseName};
@@ -0,0 +1,5 @@
1
+ import type { RbacConfig } from '@redocly/config';
2
+ import type { AuthDetails } from '../../types';
3
+ import type { RbacFeatures } from '../../../constants/common.js';
4
+ export declare function canAccessFeature(feature: RbacFeatures, auth: AuthDetails, rbacConfig?: RbacConfig, requiresLogin?: boolean): boolean;
5
+ //# sourceMappingURL=can-access-feature.d.ts.map
@@ -0,0 +1 @@
1
+ import{hasScopeAccess as n}from"./has-scope-access.js";function a(s,e,t={},c=!1){if(c&&Object.keys(t).length===0)return e.isAuthenticated;const r=t.features?.[s];return r?n(r,e.teams):!0}export{a as canAccessFeature};
@@ -1 +1 @@
1
- import{RbacFeatures as o}from"../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as c}from"../../constants/rbac.js";import{canAccessFeature as t}from"../rbac.js";function s(r,e){return t(o.MCP,c,r,e)}export{s as canAnonymousAccessMcpFeature};
1
+ import{RbacFeatures as o}from"../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as c}from"../../constants/rbac.js";import{canAccessFeature as t}from"./can-access-feature.js";function s(r,e){return t(o.MCP,c,r,e)}export{s as canAnonymousAccessMcpFeature};
@@ -0,0 +1,3 @@
1
+ import type { RbacScopeItems } from '@redocly/config';
2
+ export declare function hasScopeAccess(scopeItems: RbacScopeItems, teams: string[], email?: string): boolean;
3
+ //# sourceMappingURL=has-scope-access.d.ts.map
@@ -0,0 +1 @@
1
+ import{RBAC_ALL_OTHER_TEAMS as e}from"../../../constants/common.js";function c(r,f,n){const t=n?[...f,n]:f,s=[];for(const o of t)r[o]?s.push(r[o]):r[e]&&o!==n&&s.push(r[e]);return s.some(o=>o.toLowerCase()!=="none")}export{c as hasScopeAccess};
@@ -4,7 +4,6 @@ import type { RbacConfig, RbacScopeItems, RedoclyConfig, SsoConfig } from '@redo
4
4
  import type { AuthDetails } from '../types';
5
5
  import type { ApiDefinitionAccess } from '../plugins/api-docs/definition-access.js';
6
6
  import type { ContentFs } from '../fs/content-fs.js';
7
- import type { RbacFeatures } from '../../constants/common.js';
8
7
  export type ProjectRole = 'NONE' | 'READ' | 'TRIAGE' | 'WRITE' | 'MAINTAIN' | 'ADMIN';
9
8
  export declare const PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL: string[];
10
9
  export declare function getHigherRole(a: ProjectRole, b: ProjectRole): ProjectRole;
@@ -12,12 +11,15 @@ export declare function getScopeItemsForResource(rbacConfig: RbacConfig | undefi
12
11
  fsPath?: string;
13
12
  slug?: string;
14
13
  }): RbacScopeItems;
15
- export declare function hasScopeAccess(scopeItems: RbacScopeItems, teams: string[], email?: string): boolean;
16
- export declare function canAccessFeature(feature: RbacFeatures, auth: AuthDetails, rbacConfig?: RbacConfig, requiresLogin?: boolean): boolean;
17
14
  export declare function isResourcePubliclyAccessible(resource: {
18
15
  slug: string;
19
16
  [REDOCLY_TEAMS_RBAC]?: Record<string, string>;
20
17
  }, config: RedoclyConfig): boolean;
18
+ /**
19
+ * Whether the content rules give anonymous visitors at least one page. A rule for an API
20
+ * function (`@api`) is not a rule for a page. Reads only the config, not the pages.
21
+ */
22
+ export declare function areAnyPagesOpenToAnonymous(rbacConfig: RbacConfig | undefined): boolean;
21
23
  export declare function canAccessResource(resource: {
22
24
  slug?: string;
23
25
  [REDOCLY_TEAMS_RBAC]?: RbacScopeItems;
@@ -1 +1 @@
1
- import y from"path";import O from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as T,REDOCLY_ROUTE_RBAC as R}from"@redocly/config";import{MCP_ROUTE as U,PUBLIC_MCP_ROUTE as k}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as w}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as D,PUBLIC_RBAC_SCOPE_ITEM as _,RBAC_ALL_OTHER_TEAMS as l,DEFAULT_RBAC_SCOPE as x,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_API_DEFINITIONS_FOLDER as I,PUBLIC_ASSETS_FOLDER as b,RUNTIME_RESOURCES_DIR as $,SCORECARD_CLASSIC_FOLDER as W,SITEMAP_FILE_NAME as v,LLMS_TXT_FILE_NAME as Y}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as G}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as H}from"../constants/rbac.js";import{removeTrailingSlash as S}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as z}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as K}from"../../utils/path/parse-path-versions.js";import{reporter as V}from"../tools/notifiers/reporter.js";import{bold as J}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Q}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as X}from"../../utils/guards/is-truthy.js";import{isPathInFolder as C}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as Z,expandRbacConfig as q,getTeamFolderDefaults as tt,parseTeamFoldersTemplate as et,parseTeamNameTemplate as rt}from"./rbac-expand.js";import{getUserParamsFromCookies as nt}from"../web-server/auth.js";import{getDeeperGlobPattern as ot}from"./globs.js";import{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const j=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),at=new Set(Object.values(w).map(t=>S(t.split(":")[0])));function wt(t,e){const r=j.indexOf(t.toUpperCase()),n=j.indexOf(e.toUpperCase());return r>n?t:e}const P={};function F(t,e){if(!t?.content)return _;const r=t.content,{slug:n,fsPath:o}=e;if(!n&&!o)return _;const s=f=>{const E=`slug:${f}`,p=P[E]??O(f);P[E]=p;const A=`fsPath:${f}`,L=P[A]??O(z(f));return P[A]=L,!!(n&&p(n))||!!(o&&L(o))};if(ut(n||o||"")&&Object.keys(r).filter(p=>s(p)).length===0)return r[x]||_;const i=Object.keys(r).filter(f=>s(f));if(i.length==0)return _;const u=i.map(f=>O.scan(f,{tokens:!0,parts:!0}));let h=u[0];for(let f=1;f<u.length;f++)h=ot(h,u[f]);return r[h.input]}function N(t,e,r){const n=r?[...e,r]:e,o=[];for(const s of n)t[s]?o.push(t[s]):t[l]&&s!==r&&o.push(t[l]);return o.some(s=>s.toLowerCase()!=="none")}function Bt(t,e,r={},n=!1){if(n&&Object.keys(r).length===0)return e.isAuthenticated;const o=r.features?.[t];return o?N(o,e.teams):!0}function bt(t,e){return d(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function d(t,e={},r={},n=!1){if(t.slug&&typeof t.slug=="string"&&at.has(S(t.slug))||(t.slug===U||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(n&&Object.keys(r).length===0)return!!e.isAuthenticated;const o=q(r,e.teams||[]),s=t[T]||F(o,t[R]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[l]&&s[l].toLowerCase()!=="none"?!0:N(s,e?.teams||[],e?.email)}function $t(t,e,r,n,o){if(!t.startsWith(I)&&!t.startsWith(g))return!0;if(o){const u={[T]:o.rbac,[R]:{slug:o.slug,fsPath:o.sourcePath}};return d(u,n,e,r)}const s=t.replace(new RegExp(`^${I}/`),"").replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${B}/`),""),a=s==="."?"":s,i={[R]:{slug:t,fsPath:a},slug:t};return d(i,n,e,r)}function Wt(t,e,r,n,o){if(!C(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(A=>C(t,A));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=n[s];if(!c)return!0;const{base:a,ext:i}=y.parse(t),u=a.split(".")[0],h=i.split(".").join(""),E=c==="."?"":c,p={[R]:{slug:t,fsPath:y.posix.join(E,`${u}.${h}`)},slug:t};return d(p,o,e,r)}async function vt(t,e){const{isAuthenticated:r=!1,idpAccessToken:n,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:a=[]}=c;let i;return r?i=a.filter(u=>u!==D):i=[D],{isAuthenticated:r,idpAccessToken:n,teams:i,claims:c}}function M(t,e,r={},n=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=M(s,e,r,n);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!d(t,e,r,n))return;let o=!1;const s={};for(const c in t){if(c===T||c===R)continue;if(ct.has(c)){s[c]=t[c];continue}const a=M(t[c],e,r,n);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(a)&&a.length===0&&t[c].length!==0){o=!0;continue}a!==void 0&&(s[c]=a),c==="paths"&&it(a)&&ft(a)}return o?void 0:s}return t}function Yt(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function Gt(t,e){if(!e)return;const r=e.content;if(!r)return e;const n=Object.entries(r).flatMap(([s,c])=>s===x?[[s,c]]:[[s,c]].concat(t.localeFolders.map(a=>[s.startsWith("/")?`/${a.toLocaleLowerCase()}${s}`:y.posix.join(t.localizationFolder,a,s),c]))),o=Object.fromEntries(n);return{...e,content:o}}async function Ht(t,e){if(!e)return{};const r={},n=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=y.dirname(o);return s?[s,c]:c}));for(const o of n)r[Q(o)]=o;return r}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function it(t){return m(t)&&Object.keys(t).length>0}function ft(t){for(const e of Object.keys(t)){const r=t[e];m(r)&&Object.keys(r).length===0&&delete t[e]}}function ut(t){return t?t.split("/").filter(Boolean).some(r=>r.startsWith(".")):!1}const lt=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(r=>Object.values(r).every(n=>typeof n=="string"))}return!1},zt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(lt(t))return mt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},mt=t=>{const e={...t};if(e.content){const r={};for(const n in e.content)if(e.content[n]!==void 0){const o=S(n);r[o]=e.content[n]}e.content=r}return e};function Kt(t,e){const r=t.fsPath,n=t.slug,o=[],s=Z(e)&&(r||n)?et(e,[r,n].filter(X)):null;if(s){const a=e?.teamNamePatterns?.map(i=>i.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...a)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...pt(c)),ht(e,o)}function pt(t){if(!t)return[];const e=[],r=l in t?{authenticated:t[l],anonymous:t[l]}:{};for(const[n,o]of Object.entries({...r,...t}))o.toLowerCase()!=="none"&&n!==l&&e.push(n);return e}function ht(t,e){return e.map(n=>rt(t,n)??{teamName:n}).map(n=>n.projectRole&&n.projectRole!=="READ"?n.teamName?.toLowerCase().replace(n.projectRole?.toLowerCase?.()??"","read")??"":n.teamName?.toLowerCase()??"")}export{j as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,Gt as applyL10nToRbacConfig,Wt as canAccessAsset,Bt as canAccessFeature,d as canAccessResource,$t as canDownloadApiDefinition,ht as expandTeamsForRead,pt as extractTeamsFromScopeItems,M as filterDataByAccessDeep,vt as getAuthDetailsFromCookies,wt as getHigherRole,Kt as getRbacTeamsListForResource,F as getScopeItemsForResource,N as hasScopeAccess,lt as isRbacConfigValid,bt as isResourcePubliclyAccessible,mt as normalizeRbacConfig,zt as parseRbacConfig,Yt as parseTeamClaimToArray,Ht as resolveDirectoryHashes};
1
+ import _ from"path";import O from"picomatch";import"../node-crypto-polyfill.js";import{REDOCLY_TEAMS_RBAC as T,REDOCLY_ROUTE_RBAC as E}from"@redocly/config";import{MCP_ROUTE as M,PUBLIC_MCP_ROUTE as k}from"@redocly/theme/core/constants/mcp";import{ServerRoutes as w}from"../../constants/api.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as S,PUBLIC_RBAC_SCOPE_ITEM as d,RBAC_ALL_OTHER_TEAMS as p,DEFAULT_RBAC_SCOPE as D,GRAPHQL_SPEC_SLUG as B}from"../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as x,PUBLIC_API_DEFINITIONS_FOLDER as g,PUBLIC_ASSETS_FOLDER as b,RUNTIME_RESOURCES_DIR as $,SCORECARD_CLASSIC_FOLDER as W,SITEMAP_FILE_NAME as v,LLMS_TXT_FILE_NAME as Y}from"../constants/common.js";import{MCP_CREDENTIALS_ROUTE as G}from"../constants/mcp.js";import{ANONYMOUS_AUTH_DETAILS as H}from"../constants/rbac.js";import{removeTrailingSlash as L}from"../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as z}from"../../utils/url/remove-leading-slash.js";import{parsePathVersions as K}from"../../utils/path/parse-path-versions.js";import{reporter as V}from"../tools/notifiers/reporter.js";import{bold as J}from"../tools/notifiers/helpers/colors.js";import{shaDirPathShort as Q}from"../utils/crypto/sha-dir-path-short.js";import{isTruthy as X}from"../../utils/guards/is-truthy.js";import{isPathInFolder as C}from"../../utils/path/is-path-in-folder.js";import{canExpandConfig as Z,expandRbacConfig as q,getTeamFolderDefaults as tt,parseTeamFoldersTemplate as et,parseTeamNameTemplate as rt}from"./rbac-expand.js";import{getUserParamsFromCookies as nt}from"../web-server/auth.js";import{getDeeperGlobPattern as ot}from"./globs.js";import{hasScopeAccess as j}from"./rbac/has-scope-access.js";import{EntitlementsProvider as st}from"../entitlements/entitlements-provider.js";const N=["NONE","READ","TRIAGE","WRITE","MAINTAIN","ADMIN"],ct=new Set(["x-parsed-md-description","x-parsed-md-summary"]),at="@api",it=new Set(Object.values(w).map(t=>L(t.split(":")[0])));function bt(t,e){const n=N.indexOf(t.toUpperCase()),r=N.indexOf(e.toUpperCase());return n>r?t:e}const P={};function F(t,e){if(!t?.content)return d;const n=t.content,{slug:r,fsPath:o}=e;if(!r&&!o)return d;const s=f=>{const R=`slug:${f}`,u=P[R]??O(f);P[R]=u;const y=`fsPath:${f}`,I=P[y]??O(z(f));return P[y]=I,!!(r&&u(r))||!!(o&&I(o))};if(mt(r||o||"")&&Object.keys(n).filter(u=>s(u)).length===0)return n[D]||d;const i=Object.keys(n).filter(f=>s(f));if(i.length==0)return d;const l=i.map(f=>O.scan(f,{tokens:!0,parts:!0}));let h=l[0];for(let f=1;f<l.length;f++)h=ot(h,l[f]);return n[h.input]}function $t(t,e){return A(t,H,e.access?.rbac||{},e.access?.requiresLogin||!1)}function Wt(t){const e={[D]:d,...t?.content};return Object.entries(e).some(([n,r])=>!n.split("/").includes(at)&&j(r,[S]))}function A(t,e={},n={},r=!1){if(t.slug&&typeof t.slug=="string"&&it.has(L(t.slug))||(t.slug===M||t.slug===k||t.slug===G)&&st.instance().canAccessFeature("mcp"))return!0;if(r&&Object.keys(n).length===0)return!!e.isAuthenticated;const o=q(n,e.teams||[]),s=t[T]||F(o,t[E]||{});return Object.keys(s||{}).length===0?!1:Object.keys(s).length===1&&s[p]&&s[p].toLowerCase()!=="none"?!0:j(s,e?.teams||[],e?.email)}function vt(t,e,n,r,o){if(!t.startsWith(g)&&!t.startsWith(x))return!0;if(o){const l={[T]:o.rbac,[E]:{slug:o.slug,fsPath:o.sourcePath}};return A(l,r,e,n)}const s=t.replace(new RegExp(`^${g}/`),"").replace(new RegExp(`^${x}/`),"").replace(new RegExp(`^${B}/`),""),a=s==="."?"":s,i={[E]:{slug:t,fsPath:a},slug:t};return A(i,r,e,n)}function Yt(t,e,n,r,o){if(!C(t,b))return[`/${v}`,`/${Y}`].includes(t)||[$,W].some(y=>C(t,y));const s=t.match(/\..{64}\.([A-Fa-f0-9]{8})\.[^.]+$/)?.[1];if(!s)return!0;const c=r[s];if(!c)return!0;const{base:a,ext:i}=_.parse(t),l=a.split(".")[0],h=i.split(".").join(""),R=c==="."?"":c,u={[E]:{slug:t,fsPath:_.posix.join(R,`${l}.${h}`)},slug:t};return A(u,o,e,n)}async function Gt(t,e){const{isAuthenticated:n=!1,idpAccessToken:r,federatedAccessToken:o,federatedIdToken:s,...c}=await nt(t,e),{teams:a=[]}=c;let i;return n?i=a.filter(l=>l!==S):i=[S],{isAuthenticated:n,idpAccessToken:r,teams:i,claims:c}}function U(t,e,n={},r=!1){if(!t)return t;if(Array.isArray(t)){const o=[];for(const s of t){const c=U(s,e,n,r);c!==void 0&&o.push(c)}return o}if(typeof t=="object"){if(!A(t,e,n,r))return;let o=!1;const s={};for(const c in t){if(c===T||c===E)continue;if(ct.has(c)){s[c]=t[c];continue}const a=U(t[c],e,n,r);if(!t.link&&(c==="items"||c==="menu"&&t.type==="tab")&&Array.isArray(a)&&a.length===0&&t[c].length!==0){o=!0;continue}a!==void 0&&(s[c]=a),c==="paths"&&ft(a)&&lt(a)}return o?void 0:s}return t}function Ht(t){return typeof t=="string"?t.split(" ").filter(Boolean):Array.isArray(t)?t.map(e=>e.toString()):[]}function zt(t,e){if(!e)return;const n=e.content;if(!n)return e;const r=Object.entries(n).flatMap(([s,c])=>s===D?[[s,c]]:[[s,c]].concat(t.localeFolders.map(a=>[s.startsWith("/")?`/${a.toLocaleLowerCase()}${s}`:_.posix.join(t.localizationFolder,a,s),c]))),o=Object.fromEntries(r);return{...e,content:o}}async function Kt(t,e){if(!e)return{};const n={},r=new Set(t.scan().flatMap(({relativePath:o})=>{const{versionFolderPath:s}=K(o)||{},c=_.dirname(o);return s?[s,c]:c}));for(const o of r)n[Q(o)]=o;return n}const m=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ft(t){return m(t)&&Object.keys(t).length>0}function lt(t){for(const e of Object.keys(t)){const n=t[e];m(n)&&Object.keys(n).length===0&&delete t[e]}}function mt(t){return t?t.split("/").filter(Boolean).some(n=>n.startsWith(".")):!1}const ut=t=>{if(t&&m(t)&&("content"in t&&m(t.content)||"platform"in t&&m(t.platform)||"features"in t&&m(t.features)||t.teamFolders&&t.teamNamePatterns)){const e=Object.values(t.content||{});if(e.length===0)return!0;if(e.every(m))return e.every(n=>Object.values(n).every(r=>typeof r=="string"))}return!1},Vt=async t=>{if(t){if(Object.keys(t).length===0)return{};if(ut(t))return pt(t);await V.panicOnContentError(`You are using an incorrect format of ${J("rbac:")} configuration. See: https://redocly.com/docs/realm/access`)}},pt=t=>{const e={...t};if(e.content){const n={};for(const r in e.content)if(e.content[r]!==void 0){const o=L(r);n[o]=e.content[r]}e.content=n}return e};function Jt(t,e){const n=t.fsPath,r=t.slug,o=[],s=Z(e)&&(n||r)?et(e,[n,r].filter(X)):null;if(s){const a=e?.teamNamePatterns?.map(i=>i.replace("{teamPathSegment}",s.teamPathSegment).replace("{projectRole}","read"))??[];o.push(...a)}const c=F(s?{content:{...tt(e),...e.content}}:e,t);return o.push(...ht(c)),Rt(e,o)}function ht(t){if(!t)return[];const e=[],n=p in t?{authenticated:t[p],anonymous:t[p]}:{};for(const[r,o]of Object.entries({...n,...t}))o.toLowerCase()!=="none"&&r!==p&&e.push(r);return e}function Rt(t,e){return e.map(r=>rt(t,r)??{teamName:r}).map(r=>r.projectRole&&r.projectRole!=="READ"?r.teamName?.toLowerCase().replace(r.projectRole?.toLowerCase?.()??"","read")??"":r.teamName?.toLowerCase()??"")}export{N as PROJECT_ROLES_ORDERED_BY_ACCESS_LEVEL,zt as applyL10nToRbacConfig,Wt as areAnyPagesOpenToAnonymous,Yt as canAccessAsset,A as canAccessResource,vt as canDownloadApiDefinition,Rt as expandTeamsForRead,ht as extractTeamsFromScopeItems,U as filterDataByAccessDeep,Gt as getAuthDetailsFromCookies,bt as getHigherRole,Jt as getRbacTeamsListForResource,F as getScopeItemsForResource,ut as isRbacConfigValid,$t as isResourcePubliclyAccessible,pt as normalizeRbacConfig,Vt as parseRbacConfig,Ht as parseTeamClaimToArray,Kt as resolveDirectoryHashes};
@@ -1 +1 @@
1
- import{RbacFeatures as d}from"../../../constants/common.js";import{ASK_AI_API_URL as h,AI_ASSISTANT_ESCALATIONS_API_URL as l,AI_ASSISTANT_FEEDBACK_API_URL as T}from"../../constants/common.js";import{fetchWithClient as S}from"../../utils/fetch-with-client.js";import{canAccessFeature as m}from"../../utils/rbac.js";import{handleUnauthorizedApiRequest as I}from"../utils.js";import{isAiSearchEnabled as _}from"../../plugins/search/utils.js";import{createAssistantAnonymousToken as y}from"../../plugins/mcp/auth/assistant-anonymous-token.js";import{isMcpContentProtected as g}from"../../plugins/mcp/auth/auth-handlers.js";function E(e,i){const t=i.getConfig();return _(t)?m(d.AI_SEARCH,e.get("auth"),t.access?.rbac,t.access?.requiresLogin)?null:I(e):e.newResponse(null,403,{})}async function R(e,{mintsAnonymousMcpToken:i}){const t=e.get("auth"),r={"Content-Type":"application/json"},n=[];t.claims?.authCookie&&n.push(`authorization=${t.claims.authCookie}`),t.idpAccessToken&&n.push(`accessToken=${t.idpAccessToken}`),n.length>0&&(r.Cookie=n.join("; "));const s=e.req.header(p);s&&(r[p]=s);const a=e.req.header("Authorization");if(a)r.Authorization=a;else if(i&&n.length===0&&!s){const o=await y();o&&(r.Authorization=`Bearer ${o}`)}return r}const k="x-redocly-ai-assistant-origin",p="x-redocly-ai-assistant-identity",f="x-redocly-ai-assistant-identity-status";function C(e){const i=e.req.header("Origin");if(i)return i;const t=e.req.header("Referer");if(t)try{return new URL(t).origin}catch{}return new URL(e.req.url).origin}function u({store:e,apiUrl:i,successContentType:t="application/json",reachesMcp:r=!1}){return async n=>{if(!i)return n.newResponse(null,404);const s=E(n,e);if(s)return s;const a=r&&g(e),o=await R(n,{mintsAnonymousMcpToken:a});o[k]=C(n);const c=await S(i,{method:"POST",body:JSON.stringify(await n.req.json()),headers:o}),A=c.headers.get(f);return n.newResponse(c.body,c.status,{"Content-Type":c.ok?t:"application/json",...A?{[f]:A}:{}})}}function D(e){return u({store:e,apiUrl:h,successContentType:"text/event-stream",reachesMcp:!0})}function O(e){return u({store:e,apiUrl:l})}function P(e){return u({store:e,apiUrl:T})}export{f as AI_ASSISTANT_IDENTITY_STATUS_HEADER,O as aiAssistantEscalationsHandler,P as aiAssistantFeedbackHandler,D as askAiHandler};
1
+ import{RbacFeatures as p}from"../../../constants/common.js";import{ASK_AI_API_URL as h,AI_ASSISTANT_ESCALATIONS_API_URL as l,AI_ASSISTANT_FEEDBACK_API_URL as T}from"../../constants/common.js";import{fetchWithClient as m}from"../../utils/fetch-with-client.js";import{areAnyPagesOpenToAnonymous as S}from"../../utils/rbac.js";import{canAccessFeature as I}from"../../utils/rbac/can-access-feature.js";import{handleUnauthorizedApiRequest as _}from"../utils.js";import{isAiSearchEnabled as y}from"../../plugins/search/utils.js";import{createAssistantAnonymousToken as g}from"../../plugins/mcp/auth/assistant-anonymous-token.js";import{isMcpContentProtected as C}from"../../plugins/mcp/auth/auth-handlers.js";function E(e,r){const n=r.getConfig();if(!y(n))return e.newResponse(null,403,{});const o=e.get("auth"),t=n.access?.rbac;return!(!t?.features?.[p.AI_SEARCH]&&!o.isAuthenticated&&!e.req.header(u)&&!S(t))&&I(p.AI_SEARCH,o,t,n.access?.requiresLogin)?null:_(e)}async function R(e,{mintsAnonymousMcpToken:r}){const n=e.get("auth"),o={"Content-Type":"application/json"},t=[];n.claims?.authCookie&&t.push(`authorization=${n.claims.authCookie}`),n.idpAccessToken&&t.push(`accessToken=${n.idpAccessToken}`),t.length>0&&(o.Cookie=t.join("; "));const s=e.req.header(u);s&&(o[u]=s);const i=e.req.header("Authorization");if(i)o.Authorization=i;else if(r&&t.length===0&&!s){const a=await g();a&&(o.Authorization=`Bearer ${a}`)}return o}const k="x-redocly-ai-assistant-origin",u="x-redocly-ai-assistant-identity",f="x-redocly-ai-assistant-identity-status";function w(e){const r=e.req.header("Origin");if(r)return r;const n=e.req.header("Referer");if(n)try{return new URL(n).origin}catch{}return new URL(e.req.url).origin}function A({store:e,apiUrl:r,successContentType:n="application/json",reachesMcp:o=!1}){return async t=>{if(!r)return t.newResponse(null,404);const s=E(t,e);if(s)return s;const i=o&&C(e),a=await R(t,{mintsAnonymousMcpToken:i});a[k]=w(t);const c=await m(r,{method:"POST",body:JSON.stringify(await t.req.json()),headers:a}),d=c.headers.get(f);return t.newResponse(c.body,c.status,{"Content-Type":c.ok?n:"application/json",...d?{[f]:d}:{}})}}function D(e){return A({store:e,apiUrl:h,successContentType:"text/event-stream",reachesMcp:!0})}function j(e){return A({store:e,apiUrl:l})}function F(e){return A({store:e,apiUrl:T})}export{f as AI_ASSISTANT_IDENTITY_STATUS_HEADER,j as aiAssistantEscalationsHandler,F as aiAssistantFeedbackHandler,D as askAiHandler};
@@ -1 +1 @@
1
- import l from"@redocly/ajv";import{readStreamWithSizeLimit as p}from"../../../api-routes/helpers/read-stream-with-size-limit.js";import{ResponseSizeLimitError as u}from"../../../api-routes/errors/response-size-limit.js";const m=new l({allErrors:!0,strictSchema:!1,strictTypes:!1}),d={type:"object",properties:{redirect_uris:{type:"array",items:{type:"string",minLength:1},minItems:1},client_name:{type:"string",nullable:!0},grant_types:{type:"array",items:{type:"string"},nullable:!0},response_types:{type:"array",items:{type:"string"},nullable:!0},scope:{type:"string",nullable:!0},token_endpoint_auth_method:{type:"string",nullable:!0}},required:["redirect_uris"],additionalProperties:!0},o=m.compile(d),f=5e3,i=.0625,h=new Set(["127.0.0.1","localhost","[::1]"]);function y(e){return e.protocol==="http:"&&h.has(e.hostname)}function b(e,t){if(t.includes(e))return!0;const r=s(e);return r!==null&&t.some(n=>s(n)===r)}function s(e){const t=URL.parse(e);return!t||!y(t)?null:(t.port="",t.href)}function w(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol==="https:"}async function M(e){if(!w(e))throw new Error("client_id must be an https URL");const t=await fetch(e,{method:"GET",redirect:"error",headers:{Accept:"application/json"},signal:AbortSignal.timeout(f)});if(!t.ok)throw new Error(`Failed to fetch client metadata: HTTP ${t.status}`);const r=t.headers.get("content-type")||"";if(!/^application\/(.+\+)?json/i.test(r))throw new Error(`Unexpected content-type for client metadata: ${r}`);if(!t.body)throw new Error("Client metadata response has no body");const n=await p({stream:t.body,maxSizeMB:i,onSizeExceededErrorHandler:()=>{throw new u(`Client metadata exceeds maximum size of ${i*1024} KB`)}});let a;try{a=JSON.parse(n.toString("utf-8"))}catch(c){throw new Error(`Invalid JSON in client metadata: ${c.message}`)}return E(a)}function E(e){if(!o(e)){const t=o.errors?.[0],r=t?`${t.instancePath||"/"} ${t.message}`.trim():"Validation failed";throw new Error(`Invalid client metadata: ${r}`)}return e}export{M as fetchClientMetadataDocument,w as isClientMetadataDocumentUrl,y as isLoopbackRedirect,b as isRedirectUriRegistered};
1
+ import{isIP as m}from"node:net";import u from"@redocly/ajv";import{Agent as d}from"undici";import{readStreamWithSizeLimit as f}from"../../../api-routes/helpers/read-stream-with-size-limit.js";import{ResponseSizeLimitError as h}from"../../../api-routes/errors/response-size-limit.js";import{isBlockedIp as y}from"../../../web-server/utils/ssrf-blocklist.js";import{createSsrfSafeLookup as w}from"../../../web-server/utils/ssrf-safe-lookup.js";const S=new u({allErrors:!0,strictSchema:!1,strictTypes:!1}),g={type:"object",properties:{redirect_uris:{type:"array",items:{type:"string",minLength:1},minItems:1},client_name:{type:"string",nullable:!0},grant_types:{type:"array",items:{type:"string"},nullable:!0},response_types:{type:"array",items:{type:"string"},nullable:!0},scope:{type:"string",nullable:!0},token_endpoint_auth_method:{type:"string",nullable:!0}},required:["redirect_uris"],additionalProperties:!0},i=S.compile(g),E=5e3,s=.0625,_=new d({connect:{lookup:w()}}),b=new Set(["127.0.0.1","localhost","[::1]"]);function M(t){return t.protocol==="http:"&&b.has(t.hostname)}function P(t,e){if(e.includes(t))return!0;const n=c(t);return n!==null&&e.some(r=>c(r)===n)}function c(t){const e=URL.parse(t);return!e||!M(e)?null:(e.port="",e.href)}function L(t){if(!t)return!1;let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"}async function z(t){if(!L(t))throw new Error("client_id must be an https URL");const e=new URL(t).hostname.replace(/^\[|\]$/g,"");if(m(e)!==0&&y(e))throw new Error("client_id must not be a private network address");const n={method:"GET",redirect:"error",headers:{Accept:"application/json"},signal:AbortSignal.timeout(E),dispatcher:_},r=await fetch(t,n);if(!r.ok)throw new Error(`Failed to fetch client metadata: HTTP ${r.status}`);const o=r.headers.get("content-type")||"";if(!/^application\/(.+\+)?json/i.test(o))throw new Error(`Unexpected content-type for client metadata: ${o}`);if(!r.body)throw new Error("Client metadata response has no body");const l=await f({stream:r.body,maxSizeMB:s,onSizeExceededErrorHandler:()=>{throw new h(`Client metadata exceeds maximum size of ${s*1024} KB`)}});let a;try{a=JSON.parse(l.toString("utf-8"))}catch(p){throw new Error(`Invalid JSON in client metadata: ${p.message}`)}return x(a)}function x(t){if(!i(t)){const e=i.errors?.[0],n=e?`${e.instancePath||"/"} ${e.message}`.trim():"Validation failed";throw new Error(`Invalid client metadata: ${n}`)}return t}export{z as fetchClientMetadataDocument,L as isClientMetadataDocumentUrl,M as isLoopbackRedirect,P as isRedirectUriRegistered};
@@ -1 +1 @@
1
- import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as s}from"../../constants/common.js";import{fetchWithClient as d}from"../../utils/fetch-with-client.js";import{handleUnauthorizedApiRequest as h}from"../utils.js";function y(i){return async e=>{if(!s)return e.newResponse(null,404);const n=e.get("auth");if(i.getConfig().access?.requiresLogin&&!n.isAuthenticated)return h(e);const o={"Content-Type":"application/json"};n.idpAccessToken&&(o.Cookie=`accessToken=${n.idpAccessToken}`);const a=await e.req.json();try{const t=await d(s,{method:"POST",body:JSON.stringify(a),headers:o});if(t.ok){const u=(await t.json()).documents.map(r=>({...r,url:p(r.url)}));return e.json(u)}const c=await t.text();return e.newResponse(c,t.status,{"Content-Type":"application/json"})}catch(t){return e.json({error:"Failed to fetch semantic search results",details:String(t)},500)}}}export{y as semanticSearchHandler};
1
+ import{withPathPrefix as p}from"@redocly/theme/core/utils";import{SEMANTIC_SEARCH_API_URL as i}from"../../constants/common.js";import{fetchWithClient as d}from"../../utils/fetch-with-client.js";import{handleUnauthorizedApiRequest as f}from"../utils.js";function w(a){return async e=>{if(!i)return e.newResponse(null,404);const o=e.get("auth");if(a.getConfig().access?.requiresLogin&&!o.isAuthenticated)return f(e);const n={"Content-Type":"application/json"};o.idpAccessToken&&(n.Cookie=`accessToken=${o.idpAccessToken}`);const c=await e.req.json();try{const t=await d(i,{method:"POST",body:JSON.stringify(c),headers:n});if(t.ok){const r=await t.json();for(const s of r.documents)s.url=p(s.url);return e.json(r.documents)}const u=await t.text();return e.newResponse(u,t.status,{"Content-Type":"application/json"})}catch(t){return e.json({error:"Failed to fetch semantic search results",details:String(t)},500)}}}export{w as semanticSearchHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/redoc-reef",
3
- "version": "0.141.0-next.12",
3
+ "version": "0.141.0-next.14",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,14 +33,14 @@
33
33
  "@opentelemetry/sdk-trace-web": "2.8.0",
34
34
  "@opentelemetry/semantic-conventions": "1.40.0",
35
35
  "@redocly/ajv": "8.18.0",
36
- "@redocly/api-docs": "0.6.0-next.12",
36
+ "@redocly/api-docs": "0.6.0-next.14",
37
37
  "@redocly/config": "0.75.0",
38
38
  "@redocly/markdoc": "0.7.1",
39
39
  "@redocly/openapi-core": "2.78.0",
40
40
  "@redocly/portal-legacy-ui": "0.19.0",
41
41
  "@redocly/portal-plugin-mock-server": "0.26.0-next.4",
42
42
  "@redocly/realm-asyncapi-sdk": "0.18.0-next.1",
43
- "@redocly/theme": "0.73.0-next.8",
43
+ "@redocly/theme": "0.73.0-next.10",
44
44
  "@shikijs/transformers": "3.21.0",
45
45
  "@tanstack/react-query": "5.62.3",
46
46
  "@tanstack/react-table": "8.21.3",