@redocly/framework 1.0.0-next.6 → 1.0.0-next.7

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 (158) hide show
  1. package/dist/bundler/build/run.js +1 -1
  2. package/dist/bundler/build/vite-config.js +2 -2
  3. package/dist/bundler/dev/dev-content-build.js +1 -0
  4. package/dist/bundler/dev/dev-problems.js +1 -1
  5. package/dist/bundler/dev/dev-reporter.js +1 -1
  6. package/dist/bundler/dev/routes/dev-content-build-route.js +1 -0
  7. package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
  8. package/dist/bundler/dev/routes/source-sync-route.js +1 -1
  9. package/dist/bundler/dev/run.js +1 -1
  10. package/dist/bundler/dev/runtime-app.js +1 -1
  11. package/dist/bundler/dev/vite-chunk-url.js +1 -1
  12. package/dist/bundler/user-markdoc-schema.js +1 -1
  13. package/dist/bundler/vite-config.base.js +2 -2
  14. package/dist/cli/commands/build.js +1 -1
  15. package/dist/cli/commands/dev.js +1 -1
  16. package/dist/cli/commands/ingest.js +1 -1
  17. package/dist/cli/commands/translate.js +2 -2
  18. package/dist/cli/dev-console/{sweep.js → content-build.js} +1 -1
  19. package/dist/cli/dev-console/index.js +1 -1
  20. package/dist/cli/dev-console/lines.js +2 -2
  21. package/dist/cli/dev-console/plain.js +1 -1
  22. package/dist/cli/dev-console/tui.js +2 -2
  23. package/dist/cli/log-output/index.js +1 -1
  24. package/dist/cli/validate-react-pages.js +1 -1
  25. package/dist/client/ai-search/use-ai-search.js +1 -1
  26. package/dist/client/analytics-page-view.js +1 -1
  27. package/dist/client/app.js +3 -3
  28. package/dist/client/client-entry.js +1 -1
  29. package/dist/client/contexts.js +1 -1
  30. package/dist/client/dev-problems/ProblemsBar.js +61 -11
  31. package/dist/client/dev-problems/build-segment.js +1 -0
  32. package/dist/client/dev-problems/index.js +1 -1
  33. package/dist/client/dev-problems/use-dev-problems.js +1 -1
  34. package/dist/client/feedback.js +1 -1
  35. package/dist/client/l10n/ssr-l10n.js +1 -1
  36. package/dist/client/l10n/use-l10n-config.js +1 -1
  37. package/dist/client/products.js +1 -1
  38. package/dist/client/review/ReviewBar.js +50 -50
  39. package/dist/client/review/use-review.js +1 -1
  40. package/dist/client/sidebar/SidebarDataProvider.js +1 -1
  41. package/dist/client/sidebar/drilldown.js +1 -1
  42. package/dist/client/ssr.js +1 -1
  43. package/dist/client/telemetry/config.js +1 -1
  44. package/dist/client/theme-logo.js +1 -1
  45. package/dist/client/use-entity-revisions.js +1 -1
  46. package/dist/client/use-page-versions.js +1 -1
  47. package/dist/client/use-search.js +1 -1
  48. package/dist/client/webmcp/tools/shared.js +1 -1
  49. package/dist/client/webmcp/tools/site-tools.js +1 -1
  50. package/dist/client/webmcp/use-webmcp-tools.js +1 -1
  51. package/dist/content-layer/config.d.ts +2 -1
  52. package/dist/content-layer/config.js +1 -1
  53. package/dist/content-layer/database/invalidation.js +26 -26
  54. package/dist/content-layer/ingest/finalize-phase.js +1 -1
  55. package/dist/content-layer/ingest/git-last-modified.js +3 -3
  56. package/dist/content-layer/ingest/l10n-warnings.js +1 -1
  57. package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
  58. package/dist/content-layer/ingest/run.js +1 -1
  59. package/dist/content-layer/ingest/search-sync.js +1 -1
  60. package/dist/content-layer/link-checker/load-view.js +1 -1
  61. package/dist/content-layer/link-checker/validate.js +1 -1
  62. package/dist/content-layer/markdown/client/markdown-text.js +1 -1
  63. package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
  64. package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
  65. package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
  66. package/dist/content-layer/markdown/nodes/fence.js +1 -1
  67. package/dist/content-layer/markdown/nodes/heading.js +1 -1
  68. package/dist/content-layer/markdown/nodes/table.js +1 -1
  69. package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
  70. package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
  71. package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
  72. package/dist/content-layer/markdown/resolve/references.js +1 -1
  73. package/dist/content-layer/markdown/search/to-markdown.js +2 -2
  74. package/dist/content-layer/markdown/server/render.js +1 -1
  75. package/dist/content-layer/markdown/tags/variant.js +1 -1
  76. package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
  77. package/dist/content-layer/materialization/static-files.js +1 -1
  78. package/dist/content-layer/plugins/index.js +1 -1
  79. package/dist/content-layer/plugins/internal/api-docs/client/template.js +2 -2
  80. package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
  81. package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +13 -13
  82. package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
  83. package/dist/content-layer/plugins/internal/api-docs/server/spec-download.js +1 -1
  84. package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
  85. package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
  86. package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
  87. package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
  88. package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
  89. package/dist/content-layer/plugins/internal/index.js +1 -1
  90. package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
  91. package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
  92. package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
  93. package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
  94. package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
  95. package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
  96. package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
  97. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js +1 -1
  98. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
  99. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
  100. package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -6
  101. package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +2 -2
  102. package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
  103. package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
  104. package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
  105. package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
  106. package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
  107. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
  108. package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
  109. package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
  110. package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
  111. package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
  112. package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
  113. package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
  114. package/dist/content-layer/plugins/internal/skills/index.js +1 -1
  115. package/dist/content-layer/plugins/project/load.js +2 -2
  116. package/dist/content-layer/plugins/utils/link-access.js +1 -1
  117. package/dist/content-layer/templates/template-set.js +1 -1
  118. package/dist/content-layer/versions/redirect.js +1 -1
  119. package/dist/content-layer/versions/resolve.js +1 -1
  120. package/dist/server/app.js +3 -3
  121. package/dist/server/ask-ai/route.js +1 -1
  122. package/dist/server/auth/middleware.js +1 -1
  123. package/dist/server/auth/request.js +1 -1
  124. package/dist/server/auth/routes.js +1 -1
  125. package/dist/server/content.js +12 -12
  126. package/dist/server/cors-proxy/handler.js +1 -1
  127. package/dist/server/feedback/route.js +1 -1
  128. package/dist/server/lambda-entry.js +1 -1
  129. package/dist/server/manifest-assets.js +4 -4
  130. package/dist/server/node-entry.js +1 -1
  131. package/dist/server/page-handlers.js +1 -1
  132. package/dist/server/plugin-context.js +1 -1
  133. package/dist/server/redirects.js +1 -1
  134. package/dist/server/search/route.js +1 -1
  135. package/dist/server/seo-tags.js +2 -2
  136. package/dist/server/sitemap.js +1 -1
  137. package/dist/server/static-files/serve.js +1 -1
  138. package/dist/server/telemetry/mock-server-events.js +1 -0
  139. package/dist/server/telemetry/redirect-event.js +1 -0
  140. package/dist/server/telemetry/sender.js +1 -1
  141. package/dist/shared/constants/content-update.js +1 -1
  142. package/dist/shared/constants/dev-content-build.js +1 -0
  143. package/dist/shared/constants/dev-problems.js +1 -1
  144. package/dist/shared/constants/dev-source-sync.js +1 -1
  145. package/dist/shared/constants/system-routes.js +1 -1
  146. package/dist/shared/rbac/l10n-rules.js +1 -1
  147. package/dist/shared/rbac/team-templates.js +1 -1
  148. package/dist/shared/types/search.d.ts +7 -2
  149. package/dist/shared/utils/l10n.js +1 -1
  150. package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
  151. package/package.json +22 -2
  152. package/dist/bundler/dev/__tests__/reset-content-update-state.js +0 -1
  153. package/dist/bundler/dev/materialization-sweeper.js +0 -1
  154. package/dist/client/dev-problems/sweep-segment.js +0 -1
  155. package/dist/content-layer/plugins/internal/mcp/server/gateway/__tests__/fake-kv.js +0 -1
  156. package/dist/content-layer/plugins/internal/mcp/server/gateway/__tests__/secret-store-fixture.js +0 -1
  157. package/dist/server/__tests__/rbac-fixture.js +0 -1
  158. package/dist/server/__tests__/test-session.js +0 -1
@@ -1 +1 @@
1
- import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{runtimeTemplate as i}from"../../templates.js";import{SEARCH_GROUP_FACET_FIELD as a}from"../../../../shared/search/facets.js";import{configuredFacetFields as o,extractFacetsFromFrontmatter as s,invalidFacetValueProblems as c,searchCategoryOf as l}from"../../../search/facet-values.js";import{isPlanFeatureGranted as u}from"../../../../shared/plan-gates.js";import{SOURCE_TEMPLATE_PREFIX as d}from"../../../../shared/constants/template-ids.js";import{isObject as f}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as p}from"../../../../shared/utils/routes/normalize-route-slug.js";import{resolveContentPath as m}from"../../../../shared/utils/resolve-content-path.js";import{PAGE_BANNER_SCHEMA as h,sanitizeConfig as g}from"../../../config-schema.js";import{notInPlanProblem as _}from"../../../plan-gates.js";import{matchPathMap as v}from"../../utils/glob.js";import{filePathToRouteSlug as y}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{splitUrlSuffix as b}from"../../../../shared/utils/routes/split-url-suffix.js";import{packMarkdocAst as x,unpackMarkdocAst as S}from"../../../../shared/utils/packed-ast.js";import{isRouteSlugTarget as ee}from"../../../../shared/utils/routes/is-route-slug-target.js";import{loadSidebarSubtreeLabel as te}from"../../utils/sidebar-label.js";import{markdocNodeRange as ne}from"../../../markdown/utils/node-source-range.js";import{replaceWithMarkdocError as C}from"../../../markdown/tags/markdoc-error.js";import{getPartialTwins as w}from"../../../markdown/tags/partial.js";import{CODE_WALKTHROUGH_TAG_NAMES as re,builtInMarkdocTags as ie}from"../../../markdown/constants/builtin-tags.js";import{walkMarkdocAst as T}from"../../../markdown/utils/walk-markdoc-ast.js";import{markdocFirstHeading as ae}from"../../../markdown/search/to-text.js";import{safeDecodeURI as oe}from"../../../../shared/utils/safe-decode-uri.js";import{shiftRange as se}from"../../../../shared/utils/shift-range.js";import{classifyLinkTarget as ce}from"../../../link-checker/classify.js";import{onDiskLinkRefs as le}from"../../../link-checker/node-ref.js";import{isPartialPath as ue}from"../../../markdown/utils/partials.js";import{FRONTMATTER_BLOCK_RE as de,computeFrontmatterLineOffset as fe}from"../../../markdown/utils/frontmatter-offset.js";import{inlineRawPartials as E}from"../../../markdown/resolve/raw-partials.js";import{resolveMarkdownAst as D}from"../../../markdown/resolve/ast.js";import{resolveBannerForAppData as O}from"../app-data/banner.js";import{MARKDOC_DOCUMENT_LOADER_KEY as k}from"../../../../shared/constants/route-deps.js";import{isMarkdocValidationEnabled as A,resolveMarkdocTagSet as j,resolveMarkdownPageValidationSet as M,userMarkdocSchemaFiles as N,userMarkdocTagNames as P}from"../../../markdown/constants/tag-sets.js";import{pageLocale as F}from"../../utils/page-locale.js";import{markdocAstToMarkdownDoc as I}from"../../../markdown/search/to-markdown.js";import{collectAnchors as L}from"../../../markdown/utils/collect-anchors.js";import{frontmatterVariable as R}from"../../../markdown/utils/frontmatter-variable.js";import{markdownFirstHeading as z}from"../../../markdown/utils/first-heading.js";import{markdocAstToSearchSections as B}from"../../../markdown/search/to-sections.js";import{isInternalPagePath as V}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as pe}from"../../utils/explicit-slugs.js";import{isSkillContentPath as me}from"../../utils/skill-paths.js";import{captureSnippet as H,splitSourceLines as he}from"../../../../shared/utils/capture-snippet.js";import{curationKeywordsOf as U}from"../../../search/keywords.js";import ge from"js-yaml";const W=`markdoc-page`,G=r(`internal.markdoc`,`document`),K=r(`internal.markdoc`,`sidebar-item`),_e=`Documentation`,q=t(G,async e=>{let t=await e.io.readFile(e.file.absolutePath),{content:n,frontmatter:r,frontmatterError:i}=X(t),a=Y(e),{ast:o,entityDeps:s,assetUsages:c,tagList:l,problems:d,linkRefs:f}=await D(n,e.file.path,{resolverContext:a,tags:(await j()).tags,variables:{get env(){return e.config.publicEnv??{}}},transform:t=>Ee(t,e.file.path,Te(e.config)),validation:A()?await M():void 0}),p=fe(t);Me(o);let m=await we(r.seo,e),h=u(e.config,`banner`)?await O(Ne(r,e.file.path,e.logger),a):void 0,g=await Oe(r,e),_=await ke(r.navigation,e),v={...g.frontmatter,navigation:_.value,seo:m.seo,banner:h?.banner},y=Pe(r,o);return{value:{ast:x(o),frontmatter:v,tagList:l,title:y,editPage:Ce(e.config,r,e.file.path),lastModified:e.file.lastModifiedAt},entityDeps:[...s,...ye(),...m.entityDeps,...h?.deps??[],...g.entityDeps,..._.entityDeps],assetUsages:[...c,...m.assetUsages,...h?.assetUsages??[],...g.assetUsages],problems:be(t,e.file.path,p,d,i),linkRefs:[...le(f,p),..._.linkRefs],targetInventories:[xe(o,{frontmatter:R(v,y)})]}},{usesProjectMarkdocSchema:!0,async markdown(e,t){let{tags:n}=await j(),{chunks:r,headings:i}=I(S(e.ast),{tags:n,locale:F(t),variables:{frontmatter:R(e.frontmatter,e.title),env:t.config.publicEnv??{}}});return[{chunks:r,headings:i,...e.title?{title:e.title}:{}}]},searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=t.route.slug,r=e.title??Q(t.route.originFilePath??n),{category:i,isInvalid:u}=l(t.route.metadata),{facets:d,invalidFields:f}=s(t.route.metadata,o(t.config)),p=U(e.frontmatter.keywords);return{docs:B(S(e.ast),r,{frontmatter:R(e.frontmatter,e.title)}).map((e,t)=>{let r={docKey:e.docKey,routeSlug:n,title:e.title,text:e.text,groupKey:i??`Documentation`,facets:d};e.anchor!==void 0&&(r.anchor=e.anchor),e.path!==void 0&&(r.path=e.path);let a=t===0?p:{excludes:p?.excludes};return(a?.includes||a?.excludes)&&(r.keywords=a),e.rbacTeams!==void 0&&(r.rbacScope=Object.fromEntries(e.rbacTeams.map(e=>[e,`read`]))),r}),problems:c([...f,...u?[a]:[]],t.route.originFilePath)}}}),J=t(K,async e=>{let{content:t,frontmatter:n}=X(await e.io.readFile(e.file.absolutePath)),r=await E(t,e.file.path,Y(e));return{value:{label:Z(n)??z(r.source)??Q(e.args.filePath)},entityDeps:r.entityDeps}});function Y(e){return{config:e.config,contentDir:e.contentDir,entities:e.entities,file:e.file,io:e.io,logger:e.logger,markdown:e.markdown,plugin:e.plugin}}const ve=e({id:`internal.markdoc`,version:`3.46.0`,content:{filter:{match:e=>e.toLowerCase().endsWith(`.md`)&&!me(e)},extractFile(e,t){if(V(e.path)||ue(e.path,t.config))return{routes:[]};if(!u(t.config,`markdown`))return{routes:[],problems:[_(`Markdown pages`)]};let{banner:n,...r}=e.manifest,i=Fe(e,t),a=pe(r.slug),o=q.withArgs({filePath:e.path}),s=J.withArgs({filePath:e.path});return{routes:a.length>0?a.map(e=>({deps:{[k]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:e,slugHint:null,template:i})):[{deps:{[k]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:null,slugHint:y(e.path),template:i}],entities:[o]}}},loaders:[q,J],templates:{[W]:i(n(`./client/template.tsx`,import.meta.url))}});function X(e){let t=e.match(de);if(!t)return{content:e,frontmatter:{}};let n=t[1]??``;try{let r=ge.load(n);return{content:e.slice(t[0].length),frontmatter:f(r)?r:{}}}catch(n){let r=n instanceof Error?n.message:String(n);return{content:e.slice(t[0].length),frontmatter:{},frontmatterError:r}}}function ye(){return(N()??[]).map(e=>({kind:`file`,path:e}))}function be(e,t,n,r,i){if(r.length===0&&i===void 0)return[];let a=he(e),o=r.map(e=>Se(e,a,n,t));if(i!==void 0){let e={start:{line:1},end:{line:n}};o.push({code:`markdown/frontmatter-parse`,message:i,location:{filePath:t,range:e,snippet:H(a,e)}})}return o}function xe(e,t){let{ids:n,exhaustive:r}=L(e,t);return{kind:`anchor`,exhaustive:r,targets:n}}function Se(e,t,n,r){let i=e.location?.range;if(!i)return e;let a=se(i,n);return{...e,location:{filePath:r,range:a,snippet:H(t,a)}}}function Ce(e,t,n){let r=f(t.markdown)?t.markdown:{},i={...e.markdown?.editPage,...f(r.editPage)?r.editPage:{}};if(i.hide!==!0&&typeof i.baseUrl==`string`&&i.baseUrl!==``)return{to:`${i.baseUrl.replace(/(?<!\/)\/+$/,``)}/${n}`}}async function we(e,t){if(!f(e)||typeof e.image!=`string`)return{seo:e,entityDeps:[],assetUsages:[]};let n=await t.markdown.resolveImageReference(e.image,t.file.path);return n.result.kind===`assetRef`?{seo:{...e,image:n.result.url},entityDeps:n.entityDeps,assetUsages:n.assetUsages}:{seo:e,entityDeps:n.entityDeps,assetUsages:[]}}function Te(e){let t=/* @__PURE__ */ new Map;if(!u(e,`customMarkdocTags`))for(let e of P())t.set(e,`Custom Markdoc tags are not in this project's plan, so \`${e}\` is ignored.`);if(!u(e,`codeWalkthrough`))for(let e of re)t.set(e,`\`${e}\` is not in this project's plan and is ignored.`);return t}function Ee(e,t,n){let r=[];if(n.size===0)return r;for(let i of T(e,{getExtraNodes:w})){let e=i.type===`tag`&&i.tag!==void 0?n.get(i.tag):void 0;e!==void 0&&(r.push({code:`configuration/ignored`,message:e,location:{filePath:t,range:ne(i)??{start:{line:1},end:{line:1}}}}),C(i,e))}return r}const De=[`image`,`links`];async function Oe(e,t){let n=t.config.markdown?.frontMatterKeysToResolve??De,r={...e},i=[],a=[];for(let o of n){let n=e[o];if(typeof n!=`string`)continue;let s=await t.markdown.resolveLocalReference(n,t.file.path);i.push(...s.entityDeps),a.push(...s.assetUsages),s.result.kind!==`passthrough`&&(r[o]=s.result.url)}return{frontmatter:r,entityDeps:i,assetUsages:a}}async function ke(e,t){let n=[],r=[];if(!f(e))return{value:e,entityDeps:n,linkRefs:r};let i={...e};for(let a of[`nextButton`,`previousButton`]){let o=e[a];if(!f(o)||typeof o.page!=`string`)continue;let{page:s,...c}=o,l=ce(oe(s),t.file.path);l!==null&&r.push({kind:`link`,raw:s,...l});let u=await je(s,t);n.push(...u.entityDeps),i[a]={...c,label:typeof c.label==`string`?c.label:u.route&&await Ae(u.route,t),link:u.link}}return{value:i,entityDeps:n,linkRefs:r}}async function Ae(e,t){let n=await te(t.entities,e);if(n!==void 0)return n;let r=t.routes.get(e.slug)?.metadata.seo;return f(r)&&typeof r.title==`string`&&r.title.trim()!==``?r.title:e.slug}async function je(e,t){let n=e.trim(),{path:r,suffix:i}=b(n);if(ee(r)){let e=t.routes.bySlug(p(r));return{link:e&&`${e.slug}${i}`,route:e,entityDeps:[]}}let a=await t.markdown.resolveLocalReference(n,t.file.path);if(a.result.kind!==`pageUrl`)return{entityDeps:a.entityDeps};let o=a.result.url;return{link:o,route:t.routes.bySlug(b(o).path)??a.entityDeps.map(e=>e.kind===`file`?t.routes.byFilePath(e.path):void 0).reverse().find(e=>e!==void 0),entityDeps:a.entityDeps}}function Me(e){let t=/* @__PURE__ */ new Map;for(let n of T(e)){if(n.type!==`tag`||n.tag===void 0||ie[n.tag]?.attributes?.__idx===void 0)continue;let e=(t.get(n.tag)??0)+1;t.set(n.tag,e),n.attributes.__idx=e}}function Ne(e,t,n){if(e.banner===void 0)return;let{value:r,problems:i}=g(h,{banner:e.banner});for(let e of i)n?.warn(`${t}: ${e.message}`);return r.banner}function Pe(e,t){return Z(e)??ae(t)??void 0}function Z(e){let t=f(e.seo)?e.seo.title:void 0;return typeof t==`string`&&t.trim()!==``?t:void 0}function Q(e){let t=(e.split(`/`).pop()??e).replace(/\.[^.]+$/,``);return t===``?e:t}function Fe(e,t){let n=e.manifest.template;if(typeof n==`string`&&n.trim()!==``)return $(n,e.path,t.logger);let r=v(e.path,t.config.markdown?.template);return typeof r==`string`&&r.trim()!==``?$(r,`redocly.yaml`,t.logger):W}function $(e,t,n){if(!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.startsWith(`/`))return e;let r=m(e,t);return r===null?(n.warn(`Template reference "${e}" in ${t} escapes the content root; falling back to ${W}.`),W):`${d}${r}`}export{G as MARKDOC_DOCUMENT_LOADER_ID,_e as MARKDOC_SEARCH_GROUP,K as MARKDOC_SIDEBAR_ITEM_LOADER_ID,W as MARKDOC_TEMPLATE_ID,ve as markdocContentPlugin};
1
+ import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t}from"../../../loaders/define.js";import{runtimeFile as n}from"../../utils/runtime-file.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{runtimeTemplate as i}from"../../templates.js";import{SEARCH_GROUP_FACET_FIELD as a}from"../../../../shared/search/facets.js";import{configuredFacetFields as o,extractFacetsFromFrontmatter as s,invalidFacetValueProblems as c,searchCategoryOf as l}from"../../../search/facet-values.js";import{isPlanFeatureGranted as u}from"../../../../shared/plan-gates.js";import{isObject as d}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as f}from"../../../../shared/utils/routes/normalize-route-slug.js";import{MARKDOC_DOCUMENT_LOADER_KEY as p}from"../../../../shared/constants/route-deps.js";import{markdocNodeRange as m}from"../../../markdown/utils/node-source-range.js";import{replaceWithMarkdocError as h}from"../../../markdown/tags/markdoc-error.js";import{getPartialTwins as g}from"../../../markdown/tags/partial.js";import{CODE_WALKTHROUGH_TAG_NAMES as _,builtInMarkdocTags as v}from"../../../markdown/constants/builtin-tags.js";import{isMarkdocValidationEnabled as ee,resolveMarkdocTagSet as y,resolveMarkdownPageValidationSet as b,userMarkdocSchemaFiles as x,userMarkdocTagNames as te}from"../../../markdown/constants/tag-sets.js";import{splitUrlSuffix as S}from"../../../../shared/utils/routes/split-url-suffix.js";import{isSkillContentPath as ne}from"../../utils/skill-paths.js";import{SOURCE_TEMPLATE_PREFIX as re}from"../../../../shared/constants/template-ids.js";import{resolveContentPath as ie}from"../../../../shared/utils/resolve-content-path.js";import{PAGE_BANNER_SCHEMA as ae,sanitizeConfig as oe}from"../../../config-schema.js";import{notInPlanProblem as se}from"../../../plan-gates.js";import{matchPathMap as ce}from"../../utils/glob.js";import{filePathToRouteSlug as le}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{packMarkdocAst as ue,unpackMarkdocAst as C}from"../../../../shared/utils/packed-ast.js";import{isRouteSlugTarget as de}from"../../../../shared/utils/routes/is-route-slug-target.js";import{loadSidebarSubtreeLabel as fe}from"../../utils/sidebar-label.js";import{walkMarkdocAst as w}from"../../../markdown/utils/walk-markdoc-ast.js";import{markdocFirstHeading as T}from"../../../markdown/search/to-text.js";import{safeDecodeURI as E}from"../../../../shared/utils/safe-decode-uri.js";import{shiftRange as D}from"../../../../shared/utils/shift-range.js";import{classifyLinkTarget as O}from"../../../link-checker/classify.js";import{onDiskLinkRefs as k}from"../../../link-checker/node-ref.js";import{isPartialPath as A}from"../../../markdown/utils/partials.js";import{FRONTMATTER_BLOCK_RE as j,computeFrontmatterLineOffset as M}from"../../../markdown/utils/frontmatter-offset.js";import{inlineRawPartials as N}from"../../../markdown/resolve/raw-partials.js";import{resolveMarkdownAst as P}from"../../../markdown/resolve/ast.js";import{resolveBannerForAppData as F}from"../app-data/banner.js";import{pageLocale as I}from"../../utils/page-locale.js";import{markdocAstToMarkdownDoc as L}from"../../../markdown/search/to-markdown.js";import{collectAnchors as R}from"../../../markdown/utils/collect-anchors.js";import{frontmatterVariable as z}from"../../../markdown/utils/frontmatter-variable.js";import{markdownFirstHeading as B}from"../../../markdown/utils/first-heading.js";import{markdocAstToSearchSections as V}from"../../../markdown/search/to-sections.js";import{isInternalPagePath as pe}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as me}from"../../utils/explicit-slugs.js";import{captureSnippet as H,splitSourceLines as he}from"../../../../shared/utils/capture-snippet.js";import{curationKeywordsOf as ge}from"../../../search/keywords.js";import _e from"js-yaml";const U=`markdoc-page`,W=r(`internal.markdoc`,`document`),G=r(`internal.markdoc`,`sidebar-item`),ve=`Documentation`,K=t(W,async e=>{let t=await e.io.readFile(e.file.absolutePath),{content:n,frontmatter:r,frontmatterError:i}=Y(t),a=J(e),{ast:o,entityDeps:s,assetUsages:c,tagList:l,problems:d,linkRefs:f}=await P(n,e.file.path,{resolverContext:a,tags:(await y()).tags,variables:{get env(){return e.config.publicEnv??{}}},transform:t=>De(t,e.file.path,Ee(e.config)),validation:ee()?await b():void 0}),p=M(t);Me(o);let m=await Te(r.seo,e),h=u(e.config,`banner`)?await F(Ne(r,e.file.path,e.logger),a):void 0,g=await ke(r,e),_=await Ae(r.navigation,e),v={...g.frontmatter,navigation:_.value,seo:m.seo,banner:h?.banner},x=Pe(r,o);return{value:{ast:ue(o),frontmatter:v,tagList:l,title:x,editPage:we(e.config,r,e.file.path),lastModified:e.file.lastModifiedAt},entityDeps:[...s,...be(),...m.entityDeps,...h?.deps??[],...g.entityDeps,..._.entityDeps],assetUsages:[...c,...m.assetUsages,...h?.assetUsages??[],...g.assetUsages],problems:xe(t,e.file.path,p,d,i),linkRefs:[...k(f,p),..._.linkRefs],targetInventories:[Se(o,{frontmatter:z(v,x)})]}},{usesProjectMarkdocSchema:!0,async markdown(e,t){let{tags:n}=await y(),{chunks:r,headings:i}=L(C(e.ast),{tags:n,locale:I(t),variables:{frontmatter:z(e.frontmatter,e.title),env:t.config.publicEnv??{}}});return[{chunks:r,headings:i,...e.title?{title:e.title}:{}}]},searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let n=t.route.slug,r=e.title??Q(t.route.originFilePath??n),{category:i,isInvalid:u}=l(t.route.metadata),{facets:d,invalidFields:f}=s(t.route.metadata,o(t.config)),p=ge(e.frontmatter.keywords);return{docs:V(C(e.ast),r,{frontmatter:z(e.frontmatter,e.title)}).map((e,t)=>{let r={docKey:e.docKey,routeSlug:n,title:e.title,text:e.text,groupKey:i??`Documentation`,facets:d};e.anchor!==void 0&&(r.anchor=e.anchor),e.path!==void 0&&(r.path=e.path);let a=t===0?p:{excludes:p?.excludes};return(a?.includes||a?.excludes)&&(r.keywords=a),e.rbacTeams!==void 0&&(r.rbacScope=Object.fromEntries(e.rbacTeams.map(e=>[e,`read`]))),r}),problems:c([...f,...u?[a]:[]],t.route.originFilePath)}}}),q=t(G,async e=>{let{content:t,frontmatter:n}=Y(await e.io.readFile(e.file.absolutePath)),r=await N(t,e.file.path,J(e));return{value:{label:Z(n)??B(r.source)??Q(e.args.filePath)},entityDeps:r.entityDeps}});function J(e){return{config:e.config,contentDir:e.contentDir,entities:e.entities,file:e.file,io:e.io,logger:e.logger,markdown:e.markdown,plugin:e.plugin}}const ye=e({id:`internal.markdoc`,version:`3.46.0`,content:{filter:{match:e=>e.toLowerCase().endsWith(`.md`)&&!ne(e)},extractFile(e,t){if(pe(e.path)||A(e.path,t.config))return{routes:[]};if(!u(t.config,`markdown`))return{routes:[],problems:[se(`Markdown pages`)]};let{banner:n,...r}=e.manifest,i=Fe(e,t),a=me(r.slug),o=K.withArgs({filePath:e.path}),s=q.withArgs({filePath:e.path});return{routes:a.length>0?a.map(e=>({deps:{[p]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:e,slugHint:null,template:i})):[{deps:{[p]:o},metadata:r,routeId:`page`,sidebarSubtree:s,slug:null,slugHint:le(e.path),template:i}],entities:[o]}}},loaders:[K,q],templates:{[U]:i(n(`./client/template.tsx`,import.meta.url))}});function Y(e){let t=e.match(j);if(!t)return{content:e,frontmatter:{}};let n=t[1]??``;try{let r=_e.load(n);return{content:e.slice(t[0].length),frontmatter:d(r)?r:{}}}catch(n){let r=n instanceof Error?n.message:String(n);return{content:e.slice(t[0].length),frontmatter:{},frontmatterError:r}}}function be(){return(x()??[]).map(e=>({kind:`file`,path:e}))}function xe(e,t,n,r,i){if(r.length===0&&i===void 0)return[];let a=he(e),o=r.map(e=>Ce(e,a,n,t));if(i!==void 0){let e={start:{line:1},end:{line:n}};o.push({code:`markdown/frontmatter-parse`,message:i,location:{filePath:t,range:e,snippet:H(a,e)}})}return o}function Se(e,t){let{ids:n,exhaustive:r}=R(e,t);return{kind:`anchor`,exhaustive:r,targets:n}}function Ce(e,t,n,r){let i=e.location?.range;if(!i)return e;let a=D(i,n);return{...e,location:{filePath:r,range:a,snippet:H(t,a)}}}function we(e,t,n){let r=d(t.markdown)?t.markdown:{},i={...e.markdown?.editPage,...d(r.editPage)?r.editPage:{}};if(i.hide!==!0&&typeof i.baseUrl==`string`&&i.baseUrl!==``)return{to:`${i.baseUrl.replace(/(?<!\/)\/+$/,``)}/${n}`}}async function Te(e,t){if(!d(e)||typeof e.image!=`string`)return{seo:e,entityDeps:[],assetUsages:[]};let n=await t.markdown.resolveImageReference(e.image,t.file.path);return n.result.kind===`assetRef`?{seo:{...e,image:n.result.url},entityDeps:n.entityDeps,assetUsages:n.assetUsages}:{seo:e,entityDeps:n.entityDeps,assetUsages:[]}}function Ee(e){let t=/* @__PURE__ */ new Map;if(!u(e,`customMarkdocTags`))for(let e of te())t.set(e,`Custom Markdoc tags are not in this project's plan, so \`${e}\` is ignored.`);if(!u(e,`codeWalkthrough`))for(let e of _)t.set(e,`\`${e}\` is not in this project's plan and is ignored.`);return t}function De(e,t,n){let r=[];if(n.size===0)return r;for(let i of w(e,{getExtraNodes:g})){let e=i.type===`tag`&&i.tag!==void 0?n.get(i.tag):void 0;e!==void 0&&(r.push({code:`configuration/ignored`,message:e,location:{filePath:t,range:m(i)??{start:{line:1},end:{line:1}}}}),h(i,e))}return r}const Oe=[`image`,`links`];async function ke(e,t){let n=t.config.markdown?.frontMatterKeysToResolve??Oe,r={...e},i=[],a=[];for(let o of n){let n=e[o];if(typeof n!=`string`)continue;let s=await t.markdown.resolveLocalReference(n,t.file.path);i.push(...s.entityDeps),a.push(...s.assetUsages),s.result.kind!==`passthrough`&&(r[o]=s.result.url)}return{frontmatter:r,entityDeps:i,assetUsages:a}}async function Ae(e,t){let n=[],r=[];if(!d(e))return{value:e,entityDeps:n,linkRefs:r};let i={...e};for(let a of[`nextButton`,`previousButton`]){let o=e[a];if(!d(o)||typeof o.page!=`string`)continue;let{page:s,...c}=o,l=O(E(s),t.file.path);l!==null&&r.push({kind:`link`,raw:s,...l});let u=await je(s,t);n.push(...u.entityDeps),i[a]={...c,label:typeof c.label==`string`?c.label:u.route&&await X(u.route,t),link:u.link}}return{value:i,entityDeps:n,linkRefs:r}}async function X(e,t){let n=await fe(t.entities,e);if(n!==void 0)return n;let r=t.routes.get(e.slug)?.metadata.seo;return d(r)&&typeof r.title==`string`&&r.title.trim()!==``?r.title:e.slug}async function je(e,t){let n=e.trim(),{path:r,suffix:i}=S(n);if(de(r)){let e=t.routes.bySlug(f(r));return{link:e&&`${e.slug}${i}`,route:e,entityDeps:[]}}let a=await t.markdown.resolveLocalReference(n,t.file.path);if(a.result.kind!==`pageUrl`)return{entityDeps:a.entityDeps};let o=a.result.url;return{link:o,route:t.routes.bySlug(S(o).path)??a.entityDeps.map(e=>e.kind===`file`?t.routes.byFilePath(e.path):void 0).reverse().find(e=>e!==void 0),entityDeps:a.entityDeps}}function Me(e){let t=/* @__PURE__ */ new Map;for(let n of w(e)){if(n.type!==`tag`||n.tag===void 0||v[n.tag]?.attributes?.__idx===void 0)continue;let e=(t.get(n.tag)??0)+1;t.set(n.tag,e),n.attributes.__idx=e}}function Ne(e,t,n){if(e.banner===void 0)return;let{value:r,problems:i}=oe(ae,{banner:e.banner});for(let e of i)n?.warn(`${t}: ${e.message}`);return r.banner}function Pe(e,t){return Z(e)??T(t)??void 0}function Z(e){let t=d(e.seo)?e.seo.title:void 0;return typeof t==`string`&&t.trim()!==``?t:void 0}function Q(e){let t=(e.split(`/`).pop()??e).replace(/\.[^.]+$/,``);return t===``?e:t}function Fe(e,t){let n=e.manifest.template;if(typeof n==`string`&&n.trim()!==``)return $(n,e.path,t.logger);let r=ce(e.path,t.config.markdown?.template);return typeof r==`string`&&r.trim()!==``?$(r,`redocly.yaml`,t.logger):U}function $(e,t,n){if(!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.startsWith(`/`))return e;let r=ie(e,t);return r===null?(n.warn(`Template reference "${e}" in ${t} escapes the content root; falling back to ${U}.`),U):`${re}${r}`}export{W as MARKDOC_DOCUMENT_LOADER_ID,ve as MARKDOC_SEARCH_GROUP,G as MARKDOC_SIDEBAR_ITEM_LOADER_ID,U as MARKDOC_TEMPLATE_ID,ye as markdocContentPlugin};
@@ -1 +1 @@
1
- import{compareStrings as e}from"../../../../shared/utils/compare-strings.js";import{delocalizeRouteSlug as t,l10nDirOf as n}from"../../../../shared/utils/l10n.js";import{compileContentGlob as r}from"../../utils/glob.js";import{toPublicVersionedSlug as i}from"../../../../shared/constants/versions.js";import{MCP_IGNORED_ROUTES_ENTITY_KEY as a}from"../../../../shared/constants/mcp.js";const o=/* @__PURE__ */ new Set;function s(e,r){let i=n(r);return(i===void 0?e:t(e,i)??e).replace(/^\/+/,``)}function c(t,n,i,a){if(n.length===0)return[];let o=r(n),c=/* @__PURE__ */ new Set,u=new Set(t.map(e=>e.slug)),d=e=>{let t=l(e,i),n=t!==void 0&&!u.has(t);for(let r of n?[e.slug,t]:[e.slug])if(c.add(r),e.locale===``&&a!==void 0)for(let e of a.locales)c.add(a.toL10nSlug(r,e))};for(let e of t){let t=s(e.slug,e.originFilePath??``);(e.originFilePath!==null&&o(e.originFilePath)||o(t))&&d(e)}return[...c].sort(e)}function l(e,t){if(e.versionGroup&&e.version&&t.get(e.versionGroup)?.defaultVersion===e.version)return i(e.slug,e.versionGroup,e.version,!0)}async function u(e){if(!await e.get(`mcp:ignored-routes`))return o;let t=await e.load(a);return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):o}export{a as MCP_IGNORED_ROUTES_ENTITY_KEY,s as canonicalSlugPath,c as collectIgnoredRouteSlugs,u as readIgnoredRouteSlugs};
1
+ import{compareStrings as e}from"../../../../shared/utils/compare-strings.js";import{delocalizeRouteSlug as t,l10nDirOf as n}from"../../../../shared/utils/l10n.js";import{toPublicVersionedSlug as r}from"../../../../shared/constants/versions.js";import{compileContentGlob as i}from"../../utils/glob.js";import{MCP_IGNORED_ROUTES_ENTITY_KEY as a}from"../../../../shared/constants/mcp.js";const o=/* @__PURE__ */ new Set;function s(e,r){let i=n(r);return(i===void 0?e:t(e,i)??e).replace(/^\/+/,``)}function c(t,n,r,a){if(n.length===0)return[];let o=i(n),c=/* @__PURE__ */ new Set,u=new Set(t.map(e=>e.slug)),d=e=>{let t=l(e,r),n=t!==void 0&&!u.has(t);for(let r of n?[e.slug,t]:[e.slug])if(c.add(r),e.locale===``&&a!==void 0)for(let e of a.locales)c.add(a.toL10nSlug(r,e))};for(let e of t){let t=s(e.slug,e.originFilePath??``);(e.originFilePath!==null&&o(e.originFilePath)||o(t))&&d(e)}return[...c].sort(e)}function l(e,t){if(e.versionGroup&&e.version&&t.get(e.versionGroup)?.defaultVersion===e.version)return r(e.slug,e.versionGroup,e.version,!0)}async function u(e){if(!await e.get(`mcp:ignored-routes`))return o;let t=await e.load(a);return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):o}export{a as MCP_IGNORED_ROUTES_ENTITY_KEY,s as canonicalSlugPath,c as collectIgnoredRouteSlugs,u as readIgnoredRouteSlugs};
@@ -1 +1 @@
1
- import{A2A_ROUTE as e,MCP_ROUTE as t,MCP_SERVER_CARD_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as i,skillMarkdownPath as a}from"../../../utils/skill-paths.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{isEntityScopeVisible as u}from"../../../../../shared/rbac/entity-scope.js";import{notFoundResponse as d}from"../../../../../server/plugin-context.js";import{publicBaseUrl as f}from"../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as p,MCP_AUTH_SCHEMES as m}from"./oauth/constants.js";import"./auth.js";const h=[`text/plain`],g=[`text/plain`],_={streaming:!1,pushNotifications:!1},v={"Cache-Control":`no-store`};async function y(e,t){let n=!!e.request.viewer?.isAuthenticated;return o(c(e.config))&&!n?[]:(await e.entities.list({type:l})).flatMap(n=>{let{slug:i,title:o,description:s}=n.metadata??{};return typeof i!=`string`||!u(n,e.request.teams,t=>e.logger?.warn(t))?[]:[{id:i,name:o??i,description:s??``,tags:[],url:`${t}${r(a(i))}`}]})}async function b(n,i){if(s(i.config)||i.config.skills?.hide===!0)return d();n.set(`realmCacheControlOwned`,!0);let a=f(i.config,i.request),l=o(c(i.config)),u=i.config.seo;return n.json({name:u?.title||u?.projectTitle||`Developer Documentation`,description:u?.description||`Documentation agent card announcing this site's agent skills and MCP server.`,url:`${a}${r(e)}`,documentationUrl:`${a}${r(`/`)}`,version:`0.0.1`,protocolVersion:`0.3.0`,preferredTransport:`HTTP+JSON`,capabilities:{..._,extensions:[{uri:`https://modelcontextprotocol.io`,description:`Model Context Protocol server exposing the documentation tools and skills.`,params:{url:`${a}${r(t)}`,...l?{authentication:{required:!0,schemes:[...m]}}:{}}}]},defaultInputModes:h,defaultOutputModes:g,skills:await y(i,a)},200,{...v,...p})}function x(e,t){if(s(t.config))return d();let a=[`<${r(n)}>; rel="mcp-server-card"`];return t.config.skills?.hide!==!0&&a.push(`<${r(i)}>; rel="agent-skills"`),e.json({error:{code:`405`,message:`Method not allowed`}},405,{Link:a.join(`, `),...p,"Access-Control-Expose-Headers":`Link`})}export{x as a2a,b as agentCard};
1
+ import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as t,skillMarkdownPath as n}from"../../../utils/skill-paths.js";import{A2A_ROUTE as r,MCP_ROUTE as i,MCP_SERVER_CARD_ROUTE as a}from"../constants.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{isEntityScopeVisible as u}from"../../../../../shared/rbac/entity-scope.js";import{notFoundResponse as d}from"../../../../../server/plugin-context.js";import{publicBaseUrl as f}from"../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as p,MCP_AUTH_SCHEMES as m}from"./oauth/constants.js";import"./auth.js";const h=[`text/plain`],g=[`text/plain`],_={streaming:!1,pushNotifications:!1},v={"Cache-Control":`no-store`};async function y(t,r){let i=!!t.request.viewer?.isAuthenticated;return o(c(t.config))&&!i?[]:(await t.entities.list({type:l})).flatMap(i=>{let{slug:a,title:o,description:s}=i.metadata??{};return typeof a!=`string`||!u(i,t.request.teams,e=>t.logger?.warn(e))?[]:[{id:a,name:o??a,description:s??``,tags:[],url:`${r}${e(n(a))}`}]})}async function b(t,n){if(s(n.config)||n.config.skills?.hide===!0)return d();t.set(`realmCacheControlOwned`,!0);let a=f(n.config,n.request),l=o(c(n.config)),u=n.config.seo;return t.json({name:u?.title||u?.projectTitle||`Developer Documentation`,description:u?.description||`Documentation agent card announcing this site's agent skills and MCP server.`,url:`${a}${e(r)}`,documentationUrl:`${a}${e(`/`)}`,version:`0.0.1`,protocolVersion:`0.3.0`,preferredTransport:`HTTP+JSON`,capabilities:{..._,extensions:[{uri:`https://modelcontextprotocol.io`,description:`Model Context Protocol server exposing the documentation tools and skills.`,params:{url:`${a}${e(i)}`,...l?{authentication:{required:!0,schemes:[...m]}}:{}}}]},defaultInputModes:h,defaultOutputModes:g,skills:await y(n,a)},200,{...v,...p})}function x(n,r){if(s(r.config))return d();let i=[`<${e(a)}>; rel="mcp-server-card"`];return r.config.skills?.hide!==!0&&i.push(`<${e(t)}>; rel="agent-skills"`),n.json({error:{code:`405`,message:`Method not allowed`}},405,{Link:i.join(`, `),...p,"Access-Control-Expose-Headers":`Link`})}export{x as a2a,b as agentCard};
@@ -1 +1 @@
1
- import"../constants.js";import{isObject as e}from"../../../../../shared/utils/is-object.js";import{thrownErrorClass as t}from"./tool-errors.js";import{maskCodeCredentials as n}from"./code-credentials.js";import{redactSecretsFromString as r}from"./gateway/fetch/redact.js";import{redactSecretShapes as i}from"./secret-patterns.js";import{createHash as a}from"node:crypto";function o(e){return{client:e.client,clientVersion:e.clientVersion,requestId:e.requestId,messageId:e.messageId,callerSubject:e.callerSubject,clientIp:e.request.ip??void 0}}const s=`[mcp-audit]`,c=4096;function l(e){return a(`sha256`).update(e,`utf8`).digest(`hex`)}function u(e){if(e.length<=4096)return e;let t=e.slice(0,c),n=t.search(/\s\S*$/),r=n>0?t.slice(0,n):t;return`${r}…[truncated: kept ${r.length} of ${e.length} chars]`}function d(e,t=[]){return i(r(u(e),t))}const f=/(?<=^|[\s('"])(?:file:\/\/\/?|\/)(?:[^\s()/:'"]+\/)+/gm;function p(e){return d(e.replace(f,``))}function m(e){return{sha256:l(e),bytes:Buffer.byteLength(e,`utf8`)}}function h(e){return Object.keys(e??{}).map(e=>e.toLowerCase()).sort().join(`,`)}const g=/* @__PURE__ */ new Set([`access_token`,`api-key`,`api_key`,`apikey`,`assertion`,`auth`,`client_secret`,`code`,`code_verifier`,`id_token`,`id_token_hint`,`key`,`password`,`refresh_token`,`samlresponse`,`secret`,`session`,`sig`,`signature`,`token`,`x-amz-credential`,`x-amz-security-token`,`x-amz-signature`]);function _(e,t=[],n=[]){let r;try{r=new URL(e)}catch{return d(e,t)}let i=new Set(n.map(e=>e.toLowerCase()));for(let e of[...r.searchParams.keys()]){let t=e.toLowerCase();(g.has(t)||i.has(t))&&r.searchParams.set(e,`redacted`)}return r.username=``,r.password=``,d(r.href,t)}function v(e,t,n){let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0&&e!==``));try{e?.info(`${s} ${t}`,r)}catch{}}const y=/(169\.254\.169\.254|metadata\.google\.internal|\.consul\b|\.internal\b|localhost|127\.0\.0\.1|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|\b192\.168\.\d{1,3}\.\d{1,3}\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b)/i,b=/(process\s*(?:\.\s*env\b|\[)|globalThis|require\s*\(|__proto__)/;function x(e){let t=[];return b.test(e)&&t.push(`env_probe`),y.test(e)&&t.push(`internal_target`),{sha256:l(e),length:e.length,flags:t.sort().join(`,`)}}function S(e){try{return JSON.stringify(e)??String(e)}catch{return`«[unserializable]»`}}function C(e,{tool:t,mode:n,args:r,result:i,errorClass:a,client:o,clientVersion:s,requestId:c,messageId:u,callerSubject:f,clientIp:p}){if(t===`execute`)return;let h=S(r),g=i===void 0?void 0:m(i),_=r?.sessionHandle,y=typeof _==`string`&&_!==``?_:void 0,b=f??y;v(e,`Record MCP tool call`,{tool:t,mode:n,server_type:`docs`,error_class:a,client:o,client_version:s,request_id:c,message_id:u,subject_sha256:b?l(b):void 0,client_ip:p,args_sha256:l(h),args:d(h,y?[y]:[]),result_sha256:g?.sha256,result_bytes:g?.bytes})}async function w(e,n,r,i){let a={tool:n,mode:e.mcpMode,args:r,...o(e)},s=Date.now(),c;try{c=await i()}catch(r){throw C(e.logger,{...a,errorClass:t(r)}),e.telemetry?.toolThrew(n,Date.now()-s,r),await e.telemetry?.flush(),r}let l=E(c)&&c.isError===!0;return C(e.logger,{...a,result:k(c),errorClass:l?`tool_error`:void 0}),e.telemetry?.toolReturned(n,Date.now()-s,c),await e.telemetry?.flush(),c}const T=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function E(t){return e(t)&&Array.isArray(t.content)&&t.content.every(t=>e(t)&&T.has(t.type))}function D(t){return e(t)&&t.resultType===`input_required`}function O(e,t=``){return e.content.map(e=>e.type===`text`?e.text:``).join(t)}function k(e){if(typeof e==`string`)return e;if(E(e))return O(e);if(D(e))return``;try{return JSON.stringify(e)??``}catch{return``}}function A(e,{audit:t,code:r,description:i,sessionHandle:a,toolNames:o,fetchBudget:s,fetchCapable:c,requestId:u,messageId:f,callerSubject:p,clientIp:m}){let h=p??a;v(e,`Record code execution input`,{code_sha256:t.sha256,code_length:t.length,request_id:u,message_id:f,flags:t.flags,subject_sha256:h?l(h):void 0,client_ip:m,description:d(i),tools:[...o].sort().join(`,`),fetch_capable:c,fetch_budget:s,code:d(n(r))})}function j(e,{rawUrl:t,method:n,host:r,outcome:i,durationMs:a,injectedSecretValues:o,credentialQueryParams:s,path:c,api:u,status:f,injectedScheme:p,requestHeaders:g,requestBody:y,responseHeaders:b,responseBody:x,caller:S={}}){let{requestId:C,callerSubject:w,clientIp:T}=S,E=x===void 0?void 0:m(x);v(e,`Record gateway fetch`,{url_sha256:l(t),host:r,method:n,path:c,api:u,outcome:i,status:f,injected_scheme:p,duration_ms:a,request_id:C,subject_sha256:w?l(w):void 0,client_ip:T,url:_(t,o,s),request_header_names:h(g),request_body:y===void 0?void 0:d(y,o),response_header_names:h(b),response_sha256:E?.sha256,response_bytes:E?.bytes})}export{c as AUDIT_FIELD_MAX_CHARS,s as AUDIT_LOG_PREFIX,x as auditCode,h as auditHeaderNames,d as auditInput,l as auditSha256,p as auditStack,w as auditToolCall,_ as auditUrl,o as callAttribution,E as isCallToolResult,v as logAuditRecord,A as logCodeExecutionAudit,j as logGatewayFetchAudit,C as logMcpToolCallAudit,k as toolOutputText,O as toolResultText,u as truncateAuditField};
1
+ import{isObject as e}from"../../../../../shared/utils/is-object.js";import"../constants.js";import{thrownErrorClass as t}from"./tool-errors.js";import{maskCodeCredentials as n}from"./code-credentials.js";import{redactSecretsFromString as r}from"./gateway/fetch/redact.js";import{redactSecretShapes as i}from"./secret-patterns.js";import{createHash as a}from"node:crypto";function o(e){return{client:e.client,clientVersion:e.clientVersion,requestId:e.requestId,messageId:e.messageId,callerSubject:e.callerSubject,clientIp:e.request.ip??void 0}}const s=`[mcp-audit]`,c=4096;function l(e){return a(`sha256`).update(e,`utf8`).digest(`hex`)}function u(e){if(e.length<=4096)return e;let t=e.slice(0,c),n=t.search(/\s\S*$/),r=n>0?t.slice(0,n):t;return`${r}…[truncated: kept ${r.length} of ${e.length} chars]`}function d(e,t=[]){return i(r(u(e),t))}const f=/(?<=^|[\s('"])(?:file:\/\/\/?|\/)(?:[^\s()/:'"]+\/)+/gm;function p(e){return d(e.replace(f,``))}function m(e){return{sha256:l(e),bytes:Buffer.byteLength(e,`utf8`)}}function h(e){return Object.keys(e??{}).map(e=>e.toLowerCase()).sort().join(`,`)}const g=/* @__PURE__ */ new Set([`access_token`,`api-key`,`api_key`,`apikey`,`assertion`,`auth`,`client_secret`,`code`,`code_verifier`,`id_token`,`id_token_hint`,`key`,`password`,`refresh_token`,`samlresponse`,`secret`,`session`,`sig`,`signature`,`token`,`x-amz-credential`,`x-amz-security-token`,`x-amz-signature`]);function _(e,t=[],n=[]){let r;try{r=new URL(e)}catch{return d(e,t)}let i=new Set(n.map(e=>e.toLowerCase()));for(let e of[...r.searchParams.keys()]){let t=e.toLowerCase();(g.has(t)||i.has(t))&&r.searchParams.set(e,`redacted`)}return r.username=``,r.password=``,d(r.href,t)}function v(e,t,n){let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0&&e!==``));try{e?.info(`${s} ${t}`,r)}catch{}}const y=/(169\.254\.169\.254|metadata\.google\.internal|\.consul\b|\.internal\b|localhost|127\.0\.0\.1|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|\b192\.168\.\d{1,3}\.\d{1,3}\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b)/i,b=/(process\s*(?:\.\s*env\b|\[)|globalThis|require\s*\(|__proto__)/;function x(e){let t=[];return b.test(e)&&t.push(`env_probe`),y.test(e)&&t.push(`internal_target`),{sha256:l(e),length:e.length,flags:t.sort().join(`,`)}}function S(e){try{return JSON.stringify(e)??String(e)}catch{return`«[unserializable]»`}}function C(e,{tool:t,mode:n,args:r,result:i,errorClass:a,client:o,clientVersion:s,requestId:c,messageId:u,callerSubject:f,clientIp:p}){if(t===`execute`)return;let h=S(r),g=i===void 0?void 0:m(i),_=r?.sessionHandle,y=typeof _==`string`&&_!==``?_:void 0,b=f??y;v(e,`Record MCP tool call`,{tool:t,mode:n,server_type:`docs`,error_class:a,client:o,client_version:s,request_id:c,message_id:u,subject_sha256:b?l(b):void 0,client_ip:p,args_sha256:l(h),args:d(h,y?[y]:[]),result_sha256:g?.sha256,result_bytes:g?.bytes})}async function w(e,n,r,i){let a={tool:n,mode:e.mcpMode,args:r,...o(e)},s=Date.now(),c;try{c=await i()}catch(r){throw C(e.logger,{...a,errorClass:t(r)}),e.telemetry?.toolThrew(n,Date.now()-s,r),await e.telemetry?.flush(),r}let l=E(c)&&c.isError===!0;return C(e.logger,{...a,result:k(c),errorClass:l?`tool_error`:void 0}),e.telemetry?.toolReturned(n,Date.now()-s,c),await e.telemetry?.flush(),c}const T=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function E(t){return e(t)&&Array.isArray(t.content)&&t.content.every(t=>e(t)&&T.has(t.type))}function D(t){return e(t)&&t.resultType===`input_required`}function O(e,t=``){return e.content.map(e=>e.type===`text`?e.text:``).join(t)}function k(e){if(typeof e==`string`)return e;if(E(e))return O(e);if(D(e))return``;try{return JSON.stringify(e)??``}catch{return``}}function A(e,{audit:t,code:r,description:i,sessionHandle:a,toolNames:o,fetchBudget:s,fetchCapable:c,requestId:u,messageId:f,callerSubject:p,clientIp:m}){let h=p??a;v(e,`Record code execution input`,{code_sha256:t.sha256,code_length:t.length,request_id:u,message_id:f,flags:t.flags,subject_sha256:h?l(h):void 0,client_ip:m,description:d(i),tools:[...o].sort().join(`,`),fetch_capable:c,fetch_budget:s,code:d(n(r))})}function j(e,{rawUrl:t,method:n,host:r,outcome:i,durationMs:a,injectedSecretValues:o,credentialQueryParams:s,path:c,api:u,status:f,injectedScheme:p,requestHeaders:g,requestBody:y,responseHeaders:b,responseBody:x,caller:S={}}){let{requestId:C,callerSubject:w,clientIp:T}=S,E=x===void 0?void 0:m(x);v(e,`Record gateway fetch`,{url_sha256:l(t),host:r,method:n,path:c,api:u,outcome:i,status:f,injected_scheme:p,duration_ms:a,request_id:C,subject_sha256:w?l(w):void 0,client_ip:T,url:_(t,o,s),request_header_names:h(g),request_body:y===void 0?void 0:d(y,o),response_header_names:h(b),response_sha256:E?.sha256,response_bytes:E?.bytes})}export{c as AUDIT_FIELD_MAX_CHARS,s as AUDIT_LOG_PREFIX,x as auditCode,h as auditHeaderNames,d as auditInput,l as auditSha256,p as auditStack,w as auditToolCall,_ as auditUrl,o as callAttribution,E as isCallToolResult,v as logAuditRecord,A as logCodeExecutionAudit,j as logGatewayFetchAudit,C as logMcpToolCallAudit,k as toolOutputText,O as toolResultText,u as truncateAuditField};
@@ -1 +1 @@
1
- import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_PROTECTED_RESOURCE_ROUTE as t,PUBLIC_MCP_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{getBearerVerifier as l,getSessionIssuer as u}from"../../../../../server/auth/middleware.js";import{publicOrigin as d}from"../../../utils/request-origin.js";import{isAssistantAnonymousToken as f}from"../../../../../server/ask-ai/assistant-anonymous-token.js";import{CORS_ANY_ORIGIN as p,CORS_EXPOSE_CHALLENGE as m,SUPPORTED_MCP_SCOPES as h}from"./oauth/constants.js";function g(e){let t=/^Bearer\s+(\S+)$/i.exec((e??``).trim());return t?t[1]:null}function _(n,i){let a=i?[`error="${i.code}"`,`error_description="${i.description}"`]:[];return a.push(`resource_metadata="${n}${r(t)}"`,`scope="${h.join(` `)}"`,`authorization_uri="${n}${r(e)}"`),`Bearer ${a.join(`, `)}`}function v(e,t){return t?`${e}. A public endpoint that serves anonymous-accessible content is available at ${t}.`:e}function y(e,t,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,...n}})}function b(e,t){return y(401,{error:`unauthorized`,message:v(`Authentication required`,t)},{"WWW-Authenticate":_(e),...m})}function x(e,t){return y(401,{error:`invalid_token`,message:v(`Invalid or expired token`,t)},{"WWW-Authenticate":_(e,{code:`invalid_token`,description:`Invalid or expired token`}),...m})}function S(){return y(403,{error:`forbidden`,message:`You do not have access to this MCP server`},{...p})}async function C(e){let{c:t,ctx:p}=e,m=e=>p.logger?.warn(e),h=c(p.config),_=o(h);if(e.forceAnonymous){let e=await p.withViewer(i);return a(h,e.request.teams,!1,m)?{kind:`allow`,ctx:e,isProtected:_}:{kind:`deny`,response:S()}}let v=e=>{let t=d(p.request);return{kind:`deny`,response:e(t,s(p.config,h)?`${t}${r(n)}`:void 0)}},y=p.request.viewer??i,C,w,T=p,E=g(t.req.header(`authorization`)),D=u(t)?.artifactSecret,O=E!==null&&D!==void 0&&await f(E,D);if(!_)w=O||E===null?void 0:E;else if(O)y=i,T=await p.withViewer(i);else if(E!==null){let e=await l(t)?.(E);if(!e)return v(x);y=e.viewer,C=e.claims,w=E,T=await p.withViewer(y)}else if(!y.isAuthenticated)return v(b);return a(h,T.request.teams,y.isAuthenticated,m)?{kind:`allow`,ctx:T,isProtected:_,accessToken:w,claims:C}:{kind:`deny`,response:S()}}export{C as authorizeMcpRequest,o as isMcpContentProtected,s as isPublicEndpointServed,g as readBearerToken,c as resolveMcpAccess};
1
+ import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{MCP_AUTHORIZATION_SERVER_ROUTE as t,MCP_PROTECTED_RESOURCE_ROUTE as n,PUBLIC_MCP_ROUTE as r}from"../constants.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{getBearerVerifier as l,getSessionIssuer as u}from"../../../../../server/auth/middleware.js";import{publicOrigin as d}from"../../../utils/request-origin.js";import{isAssistantAnonymousToken as f}from"../../../../../server/ask-ai/assistant-anonymous-token.js";import{CORS_ANY_ORIGIN as p,CORS_EXPOSE_CHALLENGE as m,SUPPORTED_MCP_SCOPES as h}from"./oauth/constants.js";function g(e){let t=/^Bearer\s+(\S+)$/i.exec((e??``).trim());return t?t[1]:null}function _(r,i){let a=i?[`error="${i.code}"`,`error_description="${i.description}"`]:[];return a.push(`resource_metadata="${r}${e(n)}"`,`scope="${h.join(` `)}"`,`authorization_uri="${r}${e(t)}"`),`Bearer ${a.join(`, `)}`}function v(e,t){return t?`${e}. A public endpoint that serves anonymous-accessible content is available at ${t}.`:e}function y(e,t,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,...n}})}function b(e,t){return y(401,{error:`unauthorized`,message:v(`Authentication required`,t)},{"WWW-Authenticate":_(e),...m})}function x(e,t){return y(401,{error:`invalid_token`,message:v(`Invalid or expired token`,t)},{"WWW-Authenticate":_(e,{code:`invalid_token`,description:`Invalid or expired token`}),...m})}function S(){return y(403,{error:`forbidden`,message:`You do not have access to this MCP server`},{...p})}async function C(t){let{c:n,ctx:p}=t,m=e=>p.logger?.warn(e),h=c(p.config),_=o(h);if(t.forceAnonymous){let e=await p.withViewer(i);return a(h,e.request.teams,!1,m)?{kind:`allow`,ctx:e,isProtected:_}:{kind:`deny`,response:S()}}let v=t=>{let n=d(p.request);return{kind:`deny`,response:t(n,s(p.config,h)?`${n}${e(r)}`:void 0)}},y=p.request.viewer??i,C,w,T=p,E=g(n.req.header(`authorization`)),D=u(n)?.artifactSecret,O=E!==null&&D!==void 0&&await f(E,D);if(!_)w=O||E===null?void 0:E;else if(O)y=i,T=await p.withViewer(i);else if(E!==null){let e=await l(n)?.(E);if(!e)return v(x);y=e.viewer,C=e.claims,w=E,T=await p.withViewer(y)}else if(!y.isAuthenticated)return v(b);return a(h,T.request.teams,y.isAuthenticated,m)?{kind:`allow`,ctx:T,isProtected:_,accessToken:w,claims:C}:{kind:`deny`,response:S()}}export{C as authorizeMcpRequest,o as isMcpContentProtected,s as isPublicEndpointServed,g as readBearerToken,c as resolveMcpAccess};
@@ -1,4 +1,4 @@
1
- import{MCP_CREDENTIALS_ROUTE as e}from"../../../constants.js";import{withPathPrefix as t}from"../../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{credentialSchemesOf as i,schemeFieldName as a}from"./form-contract.js";import{ELICITATION_TTL_MS as o}from"../secret-store.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:a,target:c,token:p,error:m}=r,h=t(e),y=i(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-o)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
1
+ import{withPathPrefix as e}from"../../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../../constants.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{credentialSchemesOf as i,schemeFieldName as a}from"./form-contract.js";import{ELICITATION_TTL_MS as o}from"../secret-store.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:a,target:c,token:p,error:m}=r,h=e(t),y=i(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-o)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
2
2
  <main class="card">
3
3
  ${u(a)}
4
4
  <h1>${S?`Update`:`Add`} credentials for ${l(d(c))}</h1>
@@ -1 +1 @@
1
- import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{parseSrcSet as t}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as n}from"../../../../../../../shared/constants/mcp.js";import{toAppData as r}from"../../../../../../../shared/utils/app-data.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(t){let a=r(await t.entities.load(e)),s=o({seo:t.config.seo,logo:a.theme?.logo,colorMode:t.config.colorMode}),c=await t.entities.get(`mcp:credentials-theme`)?await t.entities.load(n):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(t.request)).host}}function o({seo:e,logo:n,colorMode:r}){let i={},a=e?.title||e?.projectTitle||n?.altText;a&&(i.name=a);let o=new Map((n?.srcSet?t(n.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??n?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
1
+ import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{toAppData as t}from"../../../../../../../shared/utils/app-data.js";import{parseSrcSet as n}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as r}from"../../../../../../../shared/constants/mcp.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(n){let a=t(await n.entities.load(e)),s=o({seo:n.config.seo,logo:a.theme?.logo,colorMode:n.config.colorMode}),c=await n.entities.get(`mcp:credentials-theme`)?await n.entities.load(r):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(n.request)).host}}function o({seo:e,logo:t,colorMode:r}){let i={},a=e?.title||e?.projectTitle||t?.altText;a&&(i.name=a);let o=new Map((t?.srcSet?n(t.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??t?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
@@ -1 +1 @@
1
- import{SystemRoute as e}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{SecretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t,i=new s(t.gatewaySecretSeed);if(e.req.method===`GET`){let n=await h(t),a=e.req.query(`token`)??``,o=await i.peekElicitation(r,a);return o?R(o,t,n)??M({secretStore:i,kv:r,site:n,token:a,target:o},{},200):L(n)}if(e.req.method===`POST`){let o=await h(t),s=await e.req.formData(),c=F(s,`token`),l=await i.peekElicitation(r,c);if(!l)return L(o);let u=R(l,t,o);if(u)return u;let d={secretStore:i,kv:r,site:o,token:c,target:l,form:s,ctx:t};switch(F(s,`action`)){case n.remove:return O(d,k(l,F(s,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{secretStore:n,kv:r,target:i}=e,a=await n.getStoredSchemes(r,i.subject,i.api),o=t.filter(e=>a[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return o.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,o)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({secretStore:e,kv:t,site:n,token:r}){return await e.consumeElicitation(t,r)?I(n,u(),200):L(n)}async function j({secretStore:e,kv:t,site:n,token:r},i){let a=await e.consumeElicitation(t,r);if(!a)return L(n);for(let n of i)n.kind===`remove`?await e.deleteSecret(t,a.subject,a.api,n.scheme):await e.setSecret(t,a.subject,a.api,n.scheme,n.secret);let o=await e.getStoredSchemes(t,a.subject,a.api),s={action:i.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:i.map(e=>e.scheme),stored:Object.keys(o).sort()};return I(n,p(a,s),200)}async function M({secretStore:e,kv:t,site:n,token:r,target:i},a,o){let s=await e.getStoredSchemes(t,i.subject,i.api);return I(n,l({site:n,target:i,token:r,stored:s,...a}),o)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${t(e.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{SecretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t,i=new s(t.gatewaySecretSeed);if(e.req.method===`GET`){let n=await h(t),a=e.req.query(`token`)??``,o=await i.peekElicitation(r,a);return o?R(o,t,n)??M({secretStore:i,kv:r,site:n,token:a,target:o},{},200):L(n)}if(e.req.method===`POST`){let o=await h(t),s=await e.req.formData(),c=F(s,`token`),l=await i.peekElicitation(r,c);if(!l)return L(o);let u=R(l,t,o);if(u)return u;let d={secretStore:i,kv:r,site:o,token:c,target:l,form:s,ctx:t};switch(F(s,`action`)){case n.remove:return O(d,k(l,F(s,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{secretStore:n,kv:r,target:i}=e,a=await n.getStoredSchemes(r,i.subject,i.api),o=t.filter(e=>a[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return o.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,o)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({secretStore:e,kv:t,site:n,token:r}){return await e.consumeElicitation(t,r)?I(n,u(),200):L(n)}async function j({secretStore:e,kv:t,site:n,token:r},i){let a=await e.consumeElicitation(t,r);if(!a)return L(n);for(let n of i)n.kind===`remove`?await e.deleteSecret(t,a.subject,a.api,n.scheme):await e.setSecret(t,a.subject,a.api,n.scheme,n.secret);let o=await e.getStoredSchemes(t,a.subject,a.api),s={action:i.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:i.map(e=>e.scheme),stored:Object.keys(o).sort()};return I(n,p(a,s),200)}async function M({secretStore:e,kv:t,site:n,token:r,target:i},a,o){let s=await e.getStoredSchemes(t,i.subject,i.api);return I(n,l({site:n,target:i,token:r,stored:s,...a}),o)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${e(t.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
@@ -1,7 +1,7 @@
1
- import{MANAGE_API_CREDENTIALS_TOOL_NAME as e,MCP_CREDENTIALS_ROUTE as t}from"../../constants.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as o,inputRequired as s,inputResponse as c}from"@modelcontextprotocol/server";const l=`credentials`,u=/* @__PURE__ */ new Map;function d(e,t){let n=u.get(e);if(n)return n;let r=t().finally(()=>{u.delete(e)});return u.set(e,r),r}function f(e){return!!(e.envelope?.[o])?.elicitation?.url}function p(e){return e.envelope!==void 0}function m(e){let t=c(e,l);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function h(t,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${t}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${e}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
- `)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:k(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return A(e,t,T(e.subject))}function b(t,{schemeLabel:n,canManageCredentials:r}){let i=S(t);if(!t.sentScheme&&(t.status===401||!t.schemes))return[`The "${t.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,t.unsupportedSchemes?`Do not replace them. This operation accepts only ${t.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
- `);if(t.status===403&&t.sentScheme)return[`The "${t.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...x(t),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${e}\` with api: "${t.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
- `);let a=t.status===401?`The "${t.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${t.name}" API rejected the request with ${i}.`;if(!r)return[a,``,t.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
- `);let o=n?`api: "${t.api}" and scheme: "${n}"`:`api: "${t.api}"`;return[a,``,...x(t),`Do not retry the same call. Call \`${e}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
- `)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:k(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e,r){let i=new URL(n(t),e);return i.searchParams.set(`token`,r),i.toString()}function A({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as o,inputRequired as s,inputResponse as c}from"@modelcontextprotocol/server";const l=`credentials`,u=/* @__PURE__ */ new Map;function d(e,t){let n=u.get(e);if(n)return n;let r=t().finally(()=>{u.delete(e)});return u.set(e,r),r}function f(e){return!!(e.envelope?.[o])?.elicitation?.url}function p(e){return e.envelope!==void 0}function m(e){let t=c(e,l);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function h(e,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${t}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
+ `)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:k(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return A(e,t,T(e.subject))}function b(e,{schemeLabel:n,canManageCredentials:r}){let i=S(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
+ `);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...x(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${t}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
+ `);let a=e.status===401?`The "${e.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${e.name}" API rejected the request with ${i}.`;if(!r)return[a,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
+ `);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"`;return[a,``,...x(e),`Do not retry the same call. Call \`${t}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
+ `)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:k(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(t,r){let i=new URL(e(n),t);return i.searchParams.set(`token`,r),i.toString()}function A({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
7
7
  `)}export{l as CREDENTIALS_INPUT_REQUEST_KEY,g as acceptedCredentialsLink,h as buildCredentialsAcceptedHint,b as buildCredentialsToolHint,y as buildUpstreamCredentialFallback,v as buildUpstreamCredentialInputRequired,m as credentialElicitationAnswer,d as dedupeElicitation,p as isStatelessRequest,_ as schemeLabelOf,f as supportsUrlElicitation};
@@ -1,5 +1,5 @@
1
- import{MANAGE_API_CREDENTIALS_TOOL_NAME as e}from"../../constants.js";import{isObject as t}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{SecretStore as p}from"./secret-store.js";import{buildAllowedOriginMatchers as m}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as h}from"./fetch/fetch-errors.js";import{buildFetchBridge as g}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as _,orderedSchemesOf as v,resolveUpstreamApiAuth as y}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as b,buildCredentialsAcceptedHint as x,buildCredentialsToolHint as S,buildUpstreamCredentialFallback as C,buildUpstreamCredentialInputRequired as w,credentialElicitationAnswer as T,dedupeElicitation as E,isStatelessRequest as D,schemeLabelOf as O,supportsUrlElicitation as k}from"./elicitation.js";import{applyFetchCount as A}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as j,upstreamAuthKey as M}from"./upstream-auth.js";import{createAnonymousSessionTool as N,manageApiCredentialsTool as P,removeApiCredentialsTool as F}from"./tools.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[N,P,F]}function R(e){return new Map(e.map(e=>[e.relativePath,y(e)]))}function z(e,t,n,r,a,o,s){return g({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:m(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:_(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:v(i.schemes),operations:f(t.fullDefinition,t.definition,t.servers,u(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:i(e),allowedHttpMethods:d(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=i(e),r={subject:t,ip:n&&c(n)};return async()=>{let t=await A(e.kv,r,o,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new h(t.message)}}async function V(e,t){if(t)try{return await new p(e.gatewaySecretSeed).getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${r(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:t,sessionHandle:n,serverContext:r,run:i},o){let c=s(t,n);if(c.kind===`invalid`)return{content:[{type:`text`,text:c.message}],isError:!0};let u=c.kind===`resolved`?c.subject:void 0,[d,f]=await Promise.all([l(t),V(t,u)]),p=R(d),m=[],h=new AbortController,g=await i(z(t,d,p,f,e=>m.push(e),o,h.signal)).finally(()=>h.abort());if(m.length===0)return g;let _=j(m).map(e=>q(e,p));if(c.kind===`anonymous`)return _.some(e=>e.schemes)?K(g,[{type:`text`,text:c.message}]):K(g,[{type:`text`,text:Z(_,{plans:p,canManageCredentials:!1})},...g.content]);let v=D(r.mcpReq);t.logger?.info(`gateway mcp credentials prompt: era=${v?`2026-07-28`:`2025`} urlElicitation=${k(r.mcpReq)}`);let y={ctx:t,serverContext:r,subject:c.subject,stored:J(f),plans:p,canManageCredentials:!a(e,t.metadata)},b=v?await $(y,_,!o.some(W)):await ee(y,_);switch(b.kind){case`inputRequired`:return b.result;case`prependText`:return K(g,[{type:`text`,text:b.text},...g.content]);case`none`:return g}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(e,n){if(!e.isError||n.length===0)return e;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
1
+ import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t}from"../../constants.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{SecretStore as p}from"./secret-store.js";import{buildAllowedOriginMatchers as m}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as h}from"./fetch/fetch-errors.js";import{buildFetchBridge as g}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as _,orderedSchemesOf as v,resolveUpstreamApiAuth as y}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as b,buildCredentialsAcceptedHint as x,buildCredentialsToolHint as S,buildUpstreamCredentialFallback as C,buildUpstreamCredentialInputRequired as w,credentialElicitationAnswer as T,dedupeElicitation as E,isStatelessRequest as D,schemeLabelOf as O,supportsUrlElicitation as k}from"./elicitation.js";import{applyFetchCount as A}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as j,upstreamAuthKey as M}from"./upstream-auth.js";import{createAnonymousSessionTool as N,manageApiCredentialsTool as P,removeApiCredentialsTool as F}from"./tools.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[N,P,F]}function R(e){return new Map(e.map(e=>[e.relativePath,y(e)]))}function z(e,t,n,r,a,o,s){return g({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:m(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:_(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:v(i.schemes),operations:f(t.fullDefinition,t.definition,t.servers,u(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:i(e),allowedHttpMethods:d(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=i(e),r={subject:t,ip:n&&c(n)};return async()=>{let t=await A(e.kv,r,o,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new h(t.message)}}async function V(e,t){if(t)try{return await new p(e.gatewaySecretSeed).getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${r(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:n,serverContext:r,run:i},o){let c=s(e,n);if(c.kind===`invalid`)return{content:[{type:`text`,text:c.message}],isError:!0};let u=c.kind===`resolved`?c.subject:void 0,[d,f]=await Promise.all([l(e),V(e,u)]),p=R(d),m=[],h=new AbortController,g=await i(z(e,d,p,f,e=>m.push(e),o,h.signal)).finally(()=>h.abort());if(m.length===0)return g;let _=j(m).map(e=>q(e,p));if(c.kind===`anonymous`)return _.some(e=>e.schemes)?K(g,[{type:`text`,text:c.message}]):K(g,[{type:`text`,text:Z(_,{plans:p,canManageCredentials:!1})},...g.content]);let v=D(r.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${v?`2026-07-28`:`2025`} urlElicitation=${k(r.mcpReq)}`);let y={ctx:e,serverContext:r,subject:c.subject,stored:J(f),plans:p,canManageCredentials:!a(t,e.metadata)},b=v?await $(y,_,!o.some(W)):await ee(y,_);switch(b.kind){case`inputRequired`:return b.result;case`prependText`:return K(g,[{type:`text`,text:b.text},...g.content]);case`none`:return g}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
2
2
  `+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
3
- `);return{...e,content:[...e.content.slice(0,-1),{type:`text`,text:i},...e.content.slice(-1)],structuredContent:{...t(e.structuredContent)?e.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
3
+ `);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
4
4
 
5
5
  `)}function Q({ctx:e,subject:t,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:t,baseUrl:n(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,secretStore:new p(e.gatewaySecretSeed),kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,t,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=T(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=t.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(t,e)};if(l===`accepted`){let e=await b(a.mcpReq.requestState(),{secretStore:new p(i.gatewaySecretSeed),kv:i.kv,subject:o,baseUrl:n(i.request),apis:u.map(e=>e.api)}),t=e?.apiName??u[0].name;return{kind:`prependText`,text:x(t,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!k(a.mcpReq)?{kind:`prependText`,text:await C(d)}:{kind:`inputRequired`,result:await w(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await E(`${e.subject}:${M(n[0])}`,()=>C(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
@@ -1 +1 @@
1
- import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,DISCOVER_TOOL_NAME as t,EXECUTE_TOOL_NAME as n}from"../constants.js";import{isObject as r}from"../../../../../shared/utils/is-object.js";import{formatError as i}from"./tool-errors.js";import{auditToolCall as a,callAttribution as o}from"./audit.js";import{CODE_MODE_TOOL_NAMES as s,FETCH_TOOL_NAME as c}from"./codemode/constants.js";import{resolveMcpMode as l,resolveRequestMcpMode as u}from"./mode.js";import{sendMcpRequestError as d}from"./mcp-telemetry.js";import{availableTools as f,isToolAvailable as p,normalizeToolDisplayName as m}from"./tool-registry.js";import{mcpJsonSchemaValidator as h}from"./json-schema-validator.js";import{toToolListEntries as g}from"./codemode/tool-list.js";import{buildCodeModeInstructions as _,buildExecuteDescription as v,buildToolsModeInstructions as y}from"./codemode/prompts.js";import{composeExecuteAnnotations as b,getActiveCapabilities as x}from"./codemode/capabilities.js";import{discover as S,discoverSchema as C}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as w,executeOutputSchema as T,executeToolTitle as E}from"./codemode/execute-schema.js";import{runCodeMode as D}from"./codemode/index.js";import{docsServerInfo as O}from"./server-info.js";import{loadSkillResources as k}from"./skills-resources.js";import{randomUUID as A}from"node:crypto";import{McpServer as j,createMcpHandler as M,fromJsonSchema as N,isCallToolResult as P,isInputRequiredResult as F}from"@modelcontextprotocol/server";const I=`text/markdown`,L={listChanged:!1};function R(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a}=m(e);return{title:t,description:n,inputSchema:N(r,h),outputSchema:i?N(i,h):void 0,annotations:a}}function z(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function B(e,t){if(P(e)||F(e))return e;let n=[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e)}];return t===`code`&&r(e)?{content:n,structuredContent:e}:{content:n}}function V(e,t){return(n,r)=>a(e,t.schema.name,n,async()=>B(await t.execute(n,e,r),e.mcpMode))}function H(e,t){return new j(e,{capabilities:{logging:{},tools:L},maxToolInputElements:1e4,instructions:t})}async function U(r,i,o){let[l,u]=await Promise.all([f(o,i),x(i)]),d=u.some(e=>e.id===c),m=l.filter(e=>!s.has(e.schema.name)).map(e=>e.schema),h=l.filter(({schema:e})=>s.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),y=i.instructionsStyle!==`brief`,O=y?g(m,u):[],k=h.some(t=>t.schema.name===e),A=H(r,_(d,O,r.websiteUrl)),j=b(m,u,i.config.mcp);A.registerTool(n,R({...z(k,w),title:E(j),description:v(d,O,r.websiteUrl),outputSchema:T(d),annotations:j}),async(e,t)=>{let r=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,s=t=>a(i,n,e,()=>D({code:e.code,description:e.description,sessionHandle:r,fetchBudget:50,registry:o,ctx:i,hostFetch:t}));if(!d)return s();let{runExecuteWithGateway:c}=await import(`./gateway/index.js`);return c({ctx:i,sessionHandle:r,serverContext:t,run:s})});let M=S(m,async e=>{let t=o.get(e);return t!==void 0&&await p(t,i)},u,i);A.registerTool(t,R(C(m,u,y)),e=>a(i,t,e,()=>M(e)));for(let e of h)A.registerTool(e.schema.name,R(z(k,e.schema)),V(i,e));return A}async function W(e,t,n){let r=new Map((await f(n,t)).map(e=>[e.schema.name,e])),i=H(e,y(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,R({...n.schema,outputSchema:void 0}),V(t,n));r.has(n.schema.name)||a.disable()}return i}async function G(e,t,n){let r=O(e.config,e.request),i=e.mcpMode===`code`?await U(r,e,t):await W(r,e,t);n.length>0&&i.server.registerCapabilities({resources:L});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:I},async()=>({contents:[{uri:e.uri,mimeType:I,text:await e.read()}]}));return i}function K(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function q(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function J(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await k(n),i=await G(n,e.registry,r),a=M(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),K(o)}catch(r){if(e.onError)await e.onError(r);else{let a=n?o(n):{requestId:A()};e.logger?.error(`MCP request failed: ${i(r)}`,{request_id:a.requestId}),await d(r,u(t.url,l()),{logger:e.logger,caller:a})}return q()}}}export{J as createMcpRequestHandler,R as toRegisterToolConfig};
1
+ import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r}from"../constants.js";import{formatError as i}from"./tool-errors.js";import{auditToolCall as a,callAttribution as o}from"./audit.js";import{CODE_MODE_TOOL_NAMES as s,FETCH_TOOL_NAME as c}from"./codemode/constants.js";import{resolveMcpMode as l,resolveRequestMcpMode as u}from"./mode.js";import{sendMcpRequestError as d}from"./mcp-telemetry.js";import{availableTools as f,isToolAvailable as p,normalizeToolDisplayName as m}from"./tool-registry.js";import{mcpJsonSchemaValidator as h}from"./json-schema-validator.js";import{toToolListEntries as g}from"./codemode/tool-list.js";import{buildCodeModeInstructions as _,buildExecuteDescription as v,buildToolsModeInstructions as y}from"./codemode/prompts.js";import{composeExecuteAnnotations as b,getActiveCapabilities as x}from"./codemode/capabilities.js";import{discover as S,discoverSchema as C}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as w,executeOutputSchema as T,executeToolTitle as E}from"./codemode/execute-schema.js";import{runCodeMode as D}from"./codemode/index.js";import{docsServerInfo as O}from"./server-info.js";import{loadSkillResources as k}from"./skills-resources.js";import{randomUUID as A}from"node:crypto";import{McpServer as j,createMcpHandler as M,fromJsonSchema as N,isCallToolResult as P,isInputRequiredResult as F}from"@modelcontextprotocol/server";const I=`text/markdown`,L={listChanged:!1};function R(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a}=m(e);return{title:t,description:n,inputSchema:N(r,h),outputSchema:i?N(i,h):void 0,annotations:a}}function z(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function B(t,n){if(P(t)||F(t))return t;let r=[{type:`text`,text:typeof t==`string`?t:JSON.stringify(t)}];return n===`code`&&e(t)?{content:r,structuredContent:t}:{content:r}}function V(e,t){return(n,r)=>a(e,t.schema.name,n,async()=>B(await t.execute(n,e,r),e.mcpMode))}function H(e,t){return new j(e,{capabilities:{logging:{},tools:L},maxToolInputElements:1e4,instructions:t})}async function U(e,i,o){let[l,u]=await Promise.all([f(o,i),x(i)]),d=u.some(e=>e.id===c),m=l.filter(e=>!s.has(e.schema.name)).map(e=>e.schema),h=l.filter(({schema:e})=>s.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),y=i.instructionsStyle!==`brief`,O=y?g(m,u):[],k=h.some(e=>e.schema.name===t),A=H(e,_(d,O,e.websiteUrl)),j=b(m,u,i.config.mcp);A.registerTool(r,R({...z(k,w),title:E(j),description:v(d,O,e.websiteUrl),outputSchema:T(d),annotations:j}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,s=t=>a(i,r,e,()=>D({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:o,ctx:i,hostFetch:t}));if(!d)return s();let{runExecuteWithGateway:c}=await import(`./gateway/index.js`);return c({ctx:i,sessionHandle:n,serverContext:t,run:s})});let M=S(m,async e=>{let t=o.get(e);return t!==void 0&&await p(t,i)},u,i);A.registerTool(n,R(C(m,u,y)),e=>a(i,n,e,()=>M(e)));for(let e of h)A.registerTool(e.schema.name,R(z(k,e.schema)),V(i,e));return A}async function W(e,t,n){let r=new Map((await f(n,t)).map(e=>[e.schema.name,e])),i=H(e,y(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,R({...n.schema,outputSchema:void 0}),V(t,n));r.has(n.schema.name)||a.disable()}return i}async function G(e,t,n){let r=O(e.config,e.request),i=e.mcpMode===`code`?await U(r,e,t):await W(r,e,t);n.length>0&&i.server.registerCapabilities({resources:L});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:I},async()=>({contents:[{uri:e.uri,mimeType:I,text:await e.read()}]}));return i}function K(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function q(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function J(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await k(n),i=await G(n,e.registry,r),a=M(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),K(o)}catch(r){if(e.onError)await e.onError(r);else{let a=n?o(n):{requestId:A()};e.logger?.error(`MCP request failed: ${i(r)}`,{request_id:a.requestId}),await d(r,u(t.url,l()),{logger:e.logger,caller:a})}return q()}}}export{J as createMcpRequestHandler,R as toRegisterToolConfig};
@@ -1 +1 @@
1
- import{MCP_CALLBACK_ROUTE as e}from"../../constants.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{getSessionIssuer as o}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as s}from"../../../../../../server/plugin-context.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(i(p.config)||!r(a(p.config)))return s();let m=o(f);if(!m)return s();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);await l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${e}/${O}`});return f.redirect(`${n(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MCP_CALLBACK_ROUTE as t}from"../../constants.js";import{SystemRoute as n}from"../../../../../../shared/constants/system-routes.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{getSessionIssuer as o}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as s}from"../../../../../../server/plugin-context.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(i(p.config)||!r(a(p.config)))return s();let m=o(f);if(!m)return s();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);await l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${t}/${O}`});return f.redirect(`${e(n.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
@@ -1 +1 @@
1
- import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_AUTHORIZE_ROUTE as t,MCP_REGISTER_ROUTE as n,MCP_ROUTE as r,MCP_TOKEN_ROUTE as i}from"../../constants.js";import{withPathPrefix as a}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"../config-gate.js";import{notFoundResponse as l}from"../../../../../../server/plugin-context.js";import{publicOrigin as u}from"../../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!s(e.config)&&o(c(e.config))}function h(t,n){if(!m(n))return l();let i=u(n.request);return t.json({resource:`${i}${a(r)}`,authorization_servers:[i],bearer_methods_supported:[`header`],resource_documentation:`${i}${a(e)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(e,r){if(!m(r))return l();let o=u(r.request);return e.json({issuer:o,authorization_endpoint:`${o}${a(t)}`,token_endpoint:`${o}${a(i)}`,scopes_supported:[...p],registration_endpoint:`${o}${a(n)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MCP_AUTHORIZATION_SERVER_ROUTE as t,MCP_AUTHORIZE_ROUTE as n,MCP_REGISTER_ROUTE as r,MCP_ROUTE as i,MCP_TOKEN_ROUTE as a}from"../../constants.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"../config-gate.js";import{notFoundResponse as l}from"../../../../../../server/plugin-context.js";import{publicOrigin as u}from"../../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!s(e.config)&&o(c(e.config))}function h(n,r){if(!m(r))return l();let a=u(r.request);return n.json({resource:`${a}${e(i)}`,authorization_servers:[a],bearer_methods_supported:[`header`],resource_documentation:`${a}${e(t)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(t,i){if(!m(i))return l();let o=u(i.request);return t.json({issuer:o,authorization_endpoint:`${o}${e(n)}`,token_endpoint:`${o}${e(a)}`,scopes_supported:[...p],registration_endpoint:`${o}${e(r)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
@@ -1 +1 @@
1
- import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{notFoundResponse as o}from"../../../../../server/plugin-context.js";import{publicBaseUrl as s,publicOrigin as c}from"../../../utils/request-origin.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{sendMcpServerCardServed as p}from"./mcp-telemetry.js";import{applyMcpRateLimit as m}from"./rate-limit.js";import{createServedMcpRequestHandler as h}from"./handler.js";import{docsServerInfo as g}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as _,CLIENT_INFO_META_KEY as v,LATEST_PROTOCOL_VERSION as y,PROTOCOL_VERSION_META_KEY as b}from"@modelcontextprotocol/server";const x=`2026-07-28`,S=[`dynamic`],C={capabilities:{},tools:S};async function w(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":x,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[b]:x,[v]:{name:`server-card`,version:`1.0`},[_]:{}}}})}));if(r.ok)return(await r.json()).result}function T(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function E(r,i){let a=await r.withViewer(n),o=await h(a,{isProtected:i},Date.now()+f,{onError:e=>T(r,e)}),s=new URL(t(e),c(r.request)).href,[l,u]=await Promise.all([w(o,s,`server/discover`),i?void 0:w(o,s,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:S};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i})=>({name:e,title:t,description:n,inputSchema:r,annotations:i}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:S}}async function D(n,c){if(i(c.config))return o();n.set(`realmCacheControlOwned`,!0);let l=await m({kv:c.kv,ip:c.request.ip,bucket:`card`,headers:u,logger:c.logger});if(l)return l;let f=g(c.config,c.request),h=r(a(c.config)),_=await E(c,h).catch(e=>{T(c,e)}),{capabilities:v,instructions:b,tools:x}=_??C;return await p({logger:c.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:y,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:s(c.config,c.request),transport:{type:`streamable-http`,endpoint:t(e)},capabilities:v,authentication:h?{required:!0,schemes:[...d]}:void 0,instructions:b,tools:x},200,{...u,"Cache-Control":_?`public, max-age=3600`:`no-store`})}export{D as mcpServerCard};
1
+ import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{MCP_ROUTE as t}from"../constants.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{notFoundResponse as o}from"../../../../../server/plugin-context.js";import{publicBaseUrl as s,publicOrigin as c}from"../../../utils/request-origin.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{sendMcpServerCardServed as p}from"./mcp-telemetry.js";import{applyMcpRateLimit as m}from"./rate-limit.js";import{createServedMcpRequestHandler as h}from"./handler.js";import{docsServerInfo as g}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as _,CLIENT_INFO_META_KEY as v,LATEST_PROTOCOL_VERSION as y,PROTOCOL_VERSION_META_KEY as b}from"@modelcontextprotocol/server";const x=`2026-07-28`,S=[`dynamic`],C={capabilities:{},tools:S};async function w(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":x,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[b]:x,[v]:{name:`server-card`,version:`1.0`},[_]:{}}}})}));if(r.ok)return(await r.json()).result}function T(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function E(r,i){let a=await r.withViewer(n),o=await h(a,{isProtected:i},Date.now()+f,{onError:e=>T(r,e)}),s=new URL(e(t),c(r.request)).href,[l,u]=await Promise.all([w(o,s,`server/discover`),i?void 0:w(o,s,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:S};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i})=>({name:e,title:t,description:n,inputSchema:r,annotations:i}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:S}}async function D(n,c){if(i(c.config))return o();n.set(`realmCacheControlOwned`,!0);let l=await m({kv:c.kv,ip:c.request.ip,bucket:`card`,headers:u,logger:c.logger});if(l)return l;let f=g(c.config,c.request),h=r(a(c.config)),_=await E(c,h).catch(e=>{T(c,e)}),{capabilities:v,instructions:b,tools:x}=_??C;return await p({logger:c.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:y,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:s(c.config,c.request),transport:{type:`streamable-http`,endpoint:e(t)},capabilities:v,authentication:h?{required:!0,schemes:[...d]}:void 0,instructions:b,tools:x},200,{...u,"Cache-Control":_?`public, max-age=3600`:`no-store`})}export{D as mcpServerCard};
@@ -1 +1 @@
1
- import{PLACEHOLDER_MCP_SERVER_NAMES as e}from"../constants.js";import{realmPlusVersion as t}from"../../../../../shared/realm-plus-version.js";import{publicOrigin as n}from"../../../utils/request-origin.js";import{resolveDocsSiteUrl as r}from"./docs-site-url.js";import{docsSiteSentence as i}from"./codemode/prompts.js";function a(t){let n=t.mcp?.name?.trim();return n&&!e.includes(n)?n:void 0}function o(e,o){let s=r(e.seo?.siteUrl,n(o));return{name:a(e)||new URL(s).host,version:t(),description:i(s),websiteUrl:s}}export{o as docsServerInfo};
1
+ import{realmPlusVersion as e}from"../../../../../shared/realm-plus-version.js";import{PLACEHOLDER_MCP_SERVER_NAMES as t}from"../constants.js";import{publicOrigin as n}from"../../../utils/request-origin.js";import{resolveDocsSiteUrl as r}from"./docs-site-url.js";import{docsSiteSentence as i}from"./codemode/prompts.js";function a(e){let n=e.mcp?.name?.trim();return n&&!t.includes(n)?n:void 0}function o(t,o){let s=r(t.seo?.siteUrl,n(o));return{name:a(t)||new URL(s).host,version:e(),description:i(s),websiteUrl:s}}export{o as docsServerInfo};
@@ -1 +1 @@
1
- import{normalizeRouteSlug as e}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{normalizeRoutePath as t}from"../../../../../../shared/utils/routes/normalize-route-path.js";import"../../../../../../shared/constants/app-data.js";import{filterRbacAnnotatedValue as n}from"../../../../../../shared/rbac/filter.js";import{stripPathPrefix as r,withPathPrefix as i}from"../../../../../../shared/path-prefix.js";import{FOLDER_SIDEBAR_FILENAME_REGEX as a,SIDEBAR_AGGREGATOR_LOADER_ID as o,SIDEBAR_PLUGIN_ID as s,isTabbedSidebar as c}from"../../../sidebar/index.js";import{readIgnoredRouteSlugs as l}from"../../ignored-routes.js";import{toAppData as u}from"../../../../../../shared/utils/app-data.js";import{posix as d}from"node:path";const f=/* @__PURE__ */ new Set,p=/(?:\/index(?:\.html\.md|\.html|\.md)|\.md|\.html)$/;async function m(e){let[t,n]=await Promise.all([l(e.entities),e.pageMarkdown.listPages()]);return{pages:n.filter(e=>!t.has(e.slug)),isVisible:n=>!t.has(n)&&e.isSlugVisible(n)}}async function h(t){let[{pages:r,isVisible:i},a,o]=await Promise.all([m(t),w(t),T(t)]),s=o.filter(t=>typeof t.link==`string`&&t.external!==!0&&i(e(t.link))),c=new Map(r.map(e=>[e.slug,e.title])),l=/* @__PURE__ */ new Set,u=[],d=g(a.map(({path:e})=>e)),p=a.map(({path:e,value:t},n)=>({path:e,value:t,id:d[n],links:M(k(t))})),h=D(p.flatMap(({links:e})=>e.slice(0,1)));for(let{path:e,value:r,id:a,links:o}of p){for(let e of o)l.add(e);let d=N(k(n(r,t.request.teams)),e=>i(e)&&c.has(e));if(d.length===0)continue;let p=a===`/`,m=p?t.config.seo?.title||`Documentation`:a,g=O(e,d,s,c,p?f:h)||m;u.push({id:a,title:g,nodes:d})}u.sort((e,t)=>Number(t.id===`/`)-Number(e.id===`/`));let _=r.filter(e=>!l.has(e.slug)).map(e=>({type:`page`,label:e.title,link:e.slug,items:[]}));return _.length>0&&u.push({id:`other-pages`,title:`Other pages`,nodes:_}),{sections:u,pages:r}}function g(e){let t=e.map(e=>{let t=d.dirname(e);return t===`.`?`/`:t}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);return e.map((e,r)=>{let i=t[r],o=!a.test(e),s=(n.get(i)??0)>1;return o&&s?e:i})}function _(e){let t=(e,n)=>n.flatMap(n=>{if(n.type!==`section`)return[];let r=v(e,n.label);return[{id:r,title:n.label,link:n.link,nodes:n.items},...t(r,n.items)]});return e.flatMap(e=>[e,...t(e.id,e.nodes)])}function v(e,t){return`${e} > ${t}`}function y(e,t,n){let r=_(e),i=t.trim().toLowerCase(),a=r.find(e=>e.id.toLowerCase()===i);if(a)return a;let o=C(t,n),s=r.find(e=>e.link!==void 0&&e.link===o);if(s)return s;let c=r.filter(e=>e.title.toLowerCase()===i);return c.find(e=>c.every(t=>t===e||t.id.startsWith(`${e.id} > `)))}function b(e){return e.flatMap(e=>[...e.link?[e.link]:[],...b(e.items)])}function x(e){return e.reduce((e,t)=>e+(t.type===`page`?1:x(t.items)),0)}function S(e,t){return`${t}${i(e)}`}function C(e,n){let i;try{i=new URL(e.trim(),n).pathname}catch{return null}let a=r(i)??i;return t(a.replace(p,``))}async function w(e){let t=(await e.entities.list({pluginId:s})).flatMap(e=>{let t=e.metadata?.sourcePath;return e.loaderId===o&&typeof t==`string`?[{path:t,key:e.key}]:[]});return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),Promise.all(t.map(async({path:t,key:n})=>({path:t,value:await e.entities.load(n)})))}async function T(e){if(!await e.entities.get(`app-data`))return[];let t=u(await e.entities.load(`app-data`)).theme?.navbar?.items??[];return E(n(t,e.request.teams)??[])}function E(e){return e.flatMap(e=>[e,...E(e.items??[])])}function D(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}function O(e,t,n,r,i){let a=n.find(t=>Array.isArray(t.linkedSidebars)&&t.linkedSidebars.includes(e));if(typeof a?.label==`string`&&a.label!==``)return a.label;let o=t.find(e=>!e.link||!i.has(e.link));if(o)return o.link?r.get(o.link):o.label}function k(e){return e===null?[]:c(e)?e.tabs.map(A):e}function A(e){return{label:e.label,link:e.link,items:e.menu??e.items??[]}}function j(e){return e.link!==void 0&&e.external!==!0}function M(t){return t.flatMap(t=>[...j(t)&&t.link?[e(t.link)]:[],...M(t.items??[])])}function N(t,n){return t.flatMap(t=>{let r=j(t)&&t.link?e(t.link):void 0,i=r!==void 0&&n(r)?r:void 0;if(t.items){let e=N(t.items,n);return e.length===0&&!i?[]:[{type:`section`,label:t.label??``,...i?{link:i}:{},items:e}]}return i?[{type:`page`,label:t.label??i,link:i,items:[]}]:[]})}export{b as collectNodeLinks,x as countPages,y as findSection,_ as flattenSections,h as loadPageNavigation,m as loadVisiblePages,C as toPageSlug,S as toPublicUrl,v as toSectionId};
1
+ import{stripPathPrefix as e,withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import"../../../../../../shared/constants/app-data.js";import{toAppData as n}from"../../../../../../shared/utils/app-data.js";import{normalizeRouteSlug as r}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{normalizeRoutePath as i}from"../../../../../../shared/utils/routes/normalize-route-path.js";import{filterRbacAnnotatedValue as a}from"../../../../../../shared/rbac/filter.js";import{FOLDER_SIDEBAR_FILENAME_REGEX as o,SIDEBAR_AGGREGATOR_LOADER_ID as s,SIDEBAR_PLUGIN_ID as c,isTabbedSidebar as l}from"../../../sidebar/index.js";import{readIgnoredRouteSlugs as u}from"../../ignored-routes.js";import{posix as d}from"node:path";const f=/* @__PURE__ */ new Set,p=/(?:\/index(?:\.html\.md|\.html|\.md)|\.md|\.html)$/;async function m(e){let[t,n]=await Promise.all([u(e.entities),e.pageMarkdown.listPages()]);return{pages:n.filter(e=>!t.has(e.slug)),isVisible:n=>!t.has(n)&&e.isSlugVisible(n)}}async function h(e){let[{pages:t,isVisible:n},i,o]=await Promise.all([m(e),w(e),T(e)]),s=o.filter(e=>typeof e.link==`string`&&e.external!==!0&&n(r(e.link))),c=new Map(t.map(e=>[e.slug,e.title])),l=/* @__PURE__ */ new Set,u=[],d=g(i.map(({path:e})=>e)),p=i.map(({path:e,value:t},n)=>({path:e,value:t,id:d[n],links:M(k(t))})),h=D(p.flatMap(({links:e})=>e.slice(0,1)));for(let{path:t,value:r,id:i,links:o}of p){for(let e of o)l.add(e);let d=N(k(a(r,e.request.teams)),e=>n(e)&&c.has(e));if(d.length===0)continue;let p=i===`/`,m=p?e.config.seo?.title||`Documentation`:i,g=O(t,d,s,c,p?f:h)||m;u.push({id:i,title:g,nodes:d})}u.sort((e,t)=>Number(t.id===`/`)-Number(e.id===`/`));let _=t.filter(e=>!l.has(e.slug)).map(e=>({type:`page`,label:e.title,link:e.slug,items:[]}));return _.length>0&&u.push({id:`other-pages`,title:`Other pages`,nodes:_}),{sections:u,pages:t}}function g(e){let t=e.map(e=>{let t=d.dirname(e);return t===`.`?`/`:t}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);return e.map((e,r)=>{let i=t[r],a=!o.test(e),s=(n.get(i)??0)>1;return a&&s?e:i})}function _(e){let t=(e,n)=>n.flatMap(n=>{if(n.type!==`section`)return[];let r=v(e,n.label);return[{id:r,title:n.label,link:n.link,nodes:n.items},...t(r,n.items)]});return e.flatMap(e=>[e,...t(e.id,e.nodes)])}function v(e,t){return`${e} > ${t}`}function y(e,t,n){let r=_(e),i=t.trim().toLowerCase(),a=r.find(e=>e.id.toLowerCase()===i);if(a)return a;let o=C(t,n),s=r.find(e=>e.link!==void 0&&e.link===o);if(s)return s;let c=r.filter(e=>e.title.toLowerCase()===i);return c.find(e=>c.every(t=>t===e||t.id.startsWith(`${e.id} > `)))}function b(e){return e.flatMap(e=>[...e.link?[e.link]:[],...b(e.items)])}function x(e){return e.reduce((e,t)=>e+(t.type===`page`?1:x(t.items)),0)}function S(e,n){return`${n}${t(e)}`}function C(t,n){let r;try{r=new URL(t.trim(),n).pathname}catch{return null}let a=e(r)??r;return i(a.replace(p,``))}async function w(e){let t=(await e.entities.list({pluginId:c})).flatMap(e=>{let t=e.metadata?.sourcePath;return e.loaderId===s&&typeof t==`string`?[{path:t,key:e.key}]:[]});return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),Promise.all(t.map(async({path:t,key:n})=>({path:t,value:await e.entities.load(n)})))}async function T(e){if(!await e.entities.get(`app-data`))return[];let t=n(await e.entities.load(`app-data`)).theme?.navbar?.items??[];return E(a(t,e.request.teams)??[])}function E(e){return e.flatMap(e=>[e,...E(e.items??[])])}function D(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}function O(e,t,n,r,i){let a=n.find(t=>Array.isArray(t.linkedSidebars)&&t.linkedSidebars.includes(e));if(typeof a?.label==`string`&&a.label!==``)return a.label;let o=t.find(e=>!e.link||!i.has(e.link));if(o)return o.link?r.get(o.link):o.label}function k(e){return e===null?[]:l(e)?e.tabs.map(A):e}function A(e){return{label:e.label,link:e.link,items:e.menu??e.items??[]}}function j(e){return e.link!==void 0&&e.external!==!0}function M(e){return e.flatMap(e=>[...j(e)&&e.link?[r(e.link)]:[],...M(e.items??[])])}function N(e,t){return e.flatMap(e=>{let n=j(e)&&e.link?r(e.link):void 0,i=n!==void 0&&t(n)?n:void 0;if(e.items){let n=N(e.items,t);return n.length===0&&!i?[]:[{type:`section`,label:e.label??``,...i?{link:i}:{},items:n}]}return i?[{type:`page`,label:e.label??i,link:i,items:[]}]:[]})}export{b as collectNodeLinks,x as countPages,y as findSection,_ as flattenSections,h as loadPageNavigation,m as loadVisiblePages,C as toPageSlug,S as toPublicUrl,v as toSectionId};
@@ -1,3 +1,3 @@
1
- import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{SEARCH_SCHEMA as c,searchSchema as l}from"./schemas.js";const u=`No results found.`;function d(e,n){let r=e=>{try{return new URL(t(e),n).toString()}catch{return e}};return e.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{normalizeL10nConfig as t}from"../../../../../../shared/utils/l10n.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{SEARCH_SCHEMA as c,searchSchema as l}from"./schemas.js";const u=`No results found.`;function d(t,n){let r=t=>{try{return new URL(e(t),n).toString()}catch{return t}};return t.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
2
2
 
3
- `).trim()}const f=[{schema:c,schemaFor:t=>l(Object.values(t.config.products??{}).map(e=>e.name),e(t.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>i()!==``,async execute(t,i){let{query:c,product:l,locale:f}=t??{},p;try{p=await o({query:c,product:l||void 0,locale:f||e(i.config.l10n).defaultLocale})}catch(e){throw e instanceof a?(i.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let m=await n(i.entities),h=await s(p,async e=>!m.has(e)&&i.isSlugVisible(e)&&await i.hasRoute(e));return h.length===0?u:d(h,r(i.request))||u}}];export{f as searchTools};
3
+ `).trim()}const f=[{schema:c,schemaFor:e=>l(Object.values(e.config.products??{}).map(e=>e.name),t(e.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>i()!==``,async execute(e,i){let{query:c,product:l,locale:f}=e??{},p;try{p=await o({query:c,product:l||void 0,locale:f||t(i.config.l10n).defaultLocale})}catch(e){throw e instanceof a?(i.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let m=await n(i.entities),h=await s(p,async e=>!m.has(e)&&i.isSlugVisible(e)&&await i.hasRoute(e));return h.length===0?u:d(h,r(i.request))||u}}];export{f as searchTools};
@@ -1 +1 @@
1
- import{isPlanFeatureGranted as e}from"../../../../../shared/plan-gates.js";import{isObject as t}from"../../../../../shared/utils/is-object.js";import{filePathToRouteSlug as n}from"../../../../../shared/utils/routes/file-path-to-route-slug.js";import"../../../../../shared/constants/api-spec-kinds.js";import{mockPathPrefix as r}from"../../../types/api-entity.js";import{stripPathPrefix as i}from"../../../../../shared/path-prefix.js";import{notFoundResponse as a}from"../../../../../server/plugin-context.js";const o={"Cache-Control":`no-store`},s=/* @__PURE__ */ new Map;function c(e,n){let r=n.metadata?.mockServer;return{...e,...t(r)?r:{}}}function l(e,t){let{specType:n,routeSlug:i}=e.metadata??{};return n!==`openapi`||typeof i!=`string`||c(t,e).off===!0?null:r(i)}function u(e,t,n=void 0){let r=null,i=-1;for(let a of e){let e=l(a,n);e===null||e.length<=i||d(e,t)&&(r={api:a,path:t.slice(e.length)||`/`},i=e.length)}return r}function d(e,t){return t===e||t.startsWith(`${e}/`)}function f(e,t,{createMockServer:n}){let r=s.get(t.key);if(r&&r.dataHash===t.dataHash)return r.handler;let{strictExamples:i,errorIfForcedExampleNotFound:a}=c(e.config.mockServer,t),o=e.entities.load(t.key).then(e=>n(structuredClone(e),{strictExamples:i,errorIfForcedExampleNotFound:a}));return s.set(t.key,{dataHash:t.dataHash,handler:o}),o.catch(()=>s.delete(t.key)),o}async function p(e,t){let i=await e.entities.list({type:`api`}),a=i.filter(({metadata:e})=>e?.specType!==`openapi`||e.routeSlug!==void 0?!1:d(r(n(String(e.sourcePath))),t));return a.length===0?i:(await Promise.all(a.map(t=>e.entities.load(t.key))),e.entities.list({type:`api`}))}function m(e,t){let n=(e.req.header(`x-http-method-override`)??e.req.method).toUpperCase(),{search:r}=new URL(e.req.url),i;return{path:t,method:n,query:r===``?void 0:r,headers:Object.fromEntries(e.req.raw.headers),getBody:()=>i??=e.req.arrayBuffer().then(e=>e.byteLength>0?Buffer.from(e):void 0)}}function h(e){return(i(new URL(e.req.url).pathname)??``).slice(6)||`/`}async function g(t,n){if(!e(n.config,`mockServer`))return a();let r=h(t),i=u(await p(n,r),r,n.config.mockServer);if(!i||!n.isSlugVisible(String(i.api.metadata?.routeSlug)))return a();let s;try{s=await import(`@redocly/mock-server`)}catch{return new Response(`Mock server is not available on this host`,{status:501})}let c=await(await f(n,i.api,s))(m(t,i.path));return new Response(c.body?new Uint8Array(c.body):null,{status:c.statusCode,headers:{...c.headers,...o}})}export{u as matchMockApi,g as mock,m as toMockRequest};
1
+ import{isPlanFeatureGranted as e}from"../../../../../shared/plan-gates.js";import{stripPathPrefix as t}from"../../../../../shared/path-prefix.js";import{isObject as n}from"../../../../../shared/utils/is-object.js";import{filePathToRouteSlug as r}from"../../../../../shared/utils/routes/file-path-to-route-slug.js";import"../../../../../shared/constants/api-spec-kinds.js";import{mockPathPrefix as i}from"../../../types/api-entity.js";import{notFoundResponse as a}from"../../../../../server/plugin-context.js";import{MOCK_SERVER_HANDLER_ID as o,withMockServerEvent as s}from"../../../../../server/telemetry/mock-server-events.js";const c={"Cache-Control":`no-store`},l=/* @__PURE__ */ new Map;function u(e,t){let r=t.metadata?.mockServer;return{...e,...n(r)?r:{}}}function d(e,t){let{specType:n,routeSlug:r}=e.metadata??{};return n!==`openapi`||typeof r!=`string`||u(t,e).off===!0?null:i(r)}function f(e,t,n=void 0){let r=null,i=-1;for(let a of e){let e=d(a,n);e===null||e.length<=i||p(e,t)&&(r={api:a,path:t.slice(e.length)||`/`},i=e.length)}return r}function p(e,t){return t===e||t.startsWith(`${e}/`)}function m(e,t,{createMockServer:n}){let r=l.get(t.key);if(r&&r.dataHash===t.dataHash)return r.handler;let{strictExamples:i,errorIfForcedExampleNotFound:a}=u(e.config.mockServer,t),o=e.entities.load(t.key).then(e=>n(structuredClone(e),{strictExamples:i,errorIfForcedExampleNotFound:a}));return l.set(t.key,{dataHash:t.dataHash,handler:o}),o.catch(()=>l.delete(t.key)),o}async function h(e,t){let n=await e.entities.list({type:`api`}),a=n.filter(({metadata:e})=>e?.specType!==`openapi`||e.routeSlug!==void 0?!1:p(i(r(String(e.sourcePath))),t));return a.length===0?n:(await Promise.all(a.map(t=>e.entities.load(t.key))),e.entities.list({type:`api`}))}function g(e,t){let n=(e.req.header(`x-http-method-override`)??e.req.method).toUpperCase(),{search:r}=new URL(e.req.url),i;return{path:t,method:n,query:r===``?void 0:r,headers:Object.fromEntries(e.req.raw.headers),getBody:()=>i??=e.req.arrayBuffer().then(e=>e.byteLength>0?Buffer.from(e):void 0)}}function _(e){return(t(new URL(e.req.url).pathname)??``).slice(6)||`/`}async function v(t,n){if(!e(n.config,`mockServer`))return a();let r=_(t),i=f(await h(n,r),r,n.config.mockServer);if(!i||!n.isSlugVisible(String(i.api.metadata?.routeSlug)))return a();let l;try{l=await import(`@redocly/mock-server`)}catch{return new Response(`Mock server is not available on this host`,{status:501})}return s({handler:o,request:t.req.raw,logger:n.logger},async()=>{let e=await(await m(n,i.api,l))(g(t,i.path));return new Response(e.body?new Uint8Array(e.body):null,{status:e.statusCode,headers:{...e.headers,...c}})})}export{f as matchMockApi,v as mock,g as toMockRequest};
@@ -1 +1 @@
1
- import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t,createInlineEntity as n}from"../../../loaders/define.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{SEARCH_GROUP_FACET_FIELD as i}from"../../../../shared/search/facets.js";import{configuredFacetFields as a,extractFacetsFromFrontmatter as o,invalidFacetValueProblems as s,searchCategoryOf as c}from"../../../search/facet-values.js";import{isPlanFeatureGranted as l}from"../../../../shared/plan-gates.js";import{SOURCE_TEMPLATE_PREFIX as u}from"../../../../shared/constants/template-ids.js";import{isObject as d}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as f}from"../../../../shared/utils/routes/normalize-route-slug.js";import{notInPlanProblem as p}from"../../../plan-gates.js";import{filePathToRouteSlug as m}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{isInternalPagePath as h}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as g}from"../../utils/explicit-slugs.js";import{curationKeywordsOf as _}from"../../../search/keywords.js";import{readPageFrontmatter as v}from"./frontmatter.js";const y=[`.page.tsx`,`.page.ts`],b=`internal.react-page`,x=`search`,S=t(r(b,`search`),async e=>({value:e.args}),{searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let{category:n,isInvalid:r}=c(t.route.metadata),{facets:l,invalidFields:u}=o(t.route.metadata,a(t.config)),d={docKey:`page`,routeSlug:t.route.slug,title:e.title,text:e.text,groupKey:n??`Documentation`,facets:l};return e.keywords!==void 0&&(d.keywords=e.keywords),{docs:[d],problems:s([...u,...r?[i]:[]],t.route.originFilePath)}}});function C(e){if(e.excludeFromSearch===!0)return;let t=d(e.search)?e.search:{},n=d(e.seo)?e.seo:{},r=e=>typeof e==`string`?e.trim():``,i=r(t.title)||r(n.title)||r(e.title),a=r(t.description)||r(n.description)||r(e.description);if(i===``&&a===``)return;let o={title:i,text:[a,...Array.isArray(t.keywords)?t.keywords.filter(e=>typeof e==`string`):[]].filter(e=>e!==``).join(` `)},s=_(t.keywords);return s!==void 0&&(o.keywords=s),o}const w=t(r(b,`seo`),async e=>{let{result:t,entityDeps:n,assetUsages:r}=await e.markdown.resolveImageReference(e.args.image,e.file.path);return t.kind===`assetRef`?{value:{image:t.url},entityDeps:n,assetUsages:r}:{value:{image:e.args.image},entityDeps:n}}),T=e({id:b,version:`1.13.0`,loaders:[w,S],content:{filter:{extensions:y},async extractFile(e,t){if(h(e.path))return{routes:[]};if(!l(t.config,`reactPages`))return{routes:[],problems:[p(`React pages`)]};let{frontmatter:r,error:i}=v(await t.io.readFile(e.path));i!==void 0&&t.logger.warn(`Ignoring the frontmatter export of a page component`,{path:e.path,error:i});let a=g(r?.slug),o=d(r?.seo)&&typeof r.seo.image==`string`?r.seo.image:void 0,s=r===null?void 0:C(r),c={};o!==void 0&&(c.seo=w.withArgs({filePath:e.path,image:o})),s!==void 0&&(c[x]=S.withArgs(s,{stableKey:`react-page:search:${e.path}`}));let _=Object.keys(c).length===0?void 0:c,y=`${u}${e.path}`,b=d(r?.seo)?r.seo.title:void 0,T=typeof b==`string`&&b.trim()!==``?n({label:b}):void 0;return{routes:a.length>0?a.map(e=>({routeId:`page`,slug:f(e),template:y,metadata:r??void 0,deps:_,sidebarSubtree:T})):[{routeId:`page`,slugHint:m(e.path,E(e.path)),template:y,metadata:r??void 0,deps:_,sidebarSubtree:T}]}}}});function E(e){return e.toLowerCase().endsWith(`.page.ts`)?`.page.ts`:`.page.tsx`}export{x as REACT_PAGE_SEARCH_LOADER_KEY,T as reactPageContentPlugin};
1
+ import{defineContentPlugin as e}from"../../define.js";import{createEntityLoader as t,createInlineEntity as n}from"../../../loaders/define.js";import{createPluginScopedId as r}from"../../utils/scoped-id.js";import{SEARCH_GROUP_FACET_FIELD as i}from"../../../../shared/search/facets.js";import{configuredFacetFields as a,extractFacetsFromFrontmatter as o,invalidFacetValueProblems as s,searchCategoryOf as c}from"../../../search/facet-values.js";import{isPlanFeatureGranted as l}from"../../../../shared/plan-gates.js";import{isObject as u}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as d}from"../../../../shared/utils/routes/normalize-route-slug.js";import{SOURCE_TEMPLATE_PREFIX as f}from"../../../../shared/constants/template-ids.js";import{notInPlanProblem as p}from"../../../plan-gates.js";import{filePathToRouteSlug as m}from"../../../../shared/utils/routes/file-path-to-route-slug.js";import{isInternalPagePath as h}from"../../utils/internal-page-path.js";import{parseExplicitSlugs as g}from"../../utils/explicit-slugs.js";import{curationKeywordsOf as _}from"../../../search/keywords.js";import{readPageFrontmatter as v}from"./frontmatter.js";const y=[`.page.tsx`,`.page.ts`],b=`internal.react-page`,x=`search`,S=t(r(b,`search`),async e=>({value:e.args}),{searchable(e,t){if(t.route===void 0||t.route.metadata.excludeFromSearch===!0)return{docs:[]};let{category:n,isInvalid:r}=c(t.route.metadata),{facets:l,invalidFields:u}=o(t.route.metadata,a(t.config)),d={docKey:`page`,routeSlug:t.route.slug,title:e.title,text:e.text,groupKey:n??`Documentation`,facets:l};return e.keywords!==void 0&&(d.keywords=e.keywords),{docs:[d],problems:s([...u,...r?[i]:[]],t.route.originFilePath)}}});function C(e){if(e.excludeFromSearch===!0)return;let t=u(e.search)?e.search:{},n=u(e.seo)?e.seo:{},r=e=>typeof e==`string`?e.trim():``,i=r(t.title)||r(n.title)||r(e.title),a=r(t.description)||r(n.description)||r(e.description);if(i===``&&a===``)return;let o={title:i,text:[a,...Array.isArray(t.keywords)?t.keywords.filter(e=>typeof e==`string`):[]].filter(e=>e!==``).join(` `)},s=_(t.keywords);return s!==void 0&&(o.keywords=s),o}const w=t(r(b,`seo`),async e=>{let{result:t,entityDeps:n,assetUsages:r}=await e.markdown.resolveImageReference(e.args.image,e.file.path);return t.kind===`assetRef`?{value:{image:t.url},entityDeps:n,assetUsages:r}:{value:{image:e.args.image},entityDeps:n}}),T=e({id:b,version:`1.13.0`,loaders:[w,S],content:{filter:{extensions:y},async extractFile(e,t){if(h(e.path))return{routes:[]};if(!l(t.config,`reactPages`))return{routes:[],problems:[p(`React pages`)]};let{frontmatter:r,error:i}=v(await t.io.readFile(e.path));i!==void 0&&t.logger.warn(`Ignoring the frontmatter export of a page component`,{path:e.path,error:i});let a=g(r?.slug),o=u(r?.seo)&&typeof r.seo.image==`string`?r.seo.image:void 0,s=r===null?void 0:C(r),c={};o!==void 0&&(c.seo=w.withArgs({filePath:e.path,image:o})),s!==void 0&&(c[x]=S.withArgs(s,{stableKey:`react-page:search:${e.path}`}));let _=Object.keys(c).length===0?void 0:c,y=`${f}${e.path}`,b=u(r?.seo)?r.seo.title:void 0,T=typeof b==`string`&&b.trim()!==``?n({label:b}):void 0;return{routes:a.length>0?a.map(e=>({routeId:`page`,slug:d(e),template:y,metadata:r??void 0,deps:_,sidebarSubtree:T})):[{routeId:`page`,slugHint:m(e.path,E(e.path)),template:y,metadata:r??void 0,deps:_,sidebarSubtree:T}]}}}});function E(e){return e.toLowerCase().endsWith(`.page.ts`)?`.page.ts`:`.page.tsx`}export{x as REACT_PAGE_SEARCH_LOADER_KEY,T as reactPageContentPlugin};
@@ -1 +1 @@
1
- import{defineContentPlugin as e}from"../../define.js";import{toJsonValue as t}from"../../../database/utils/json.js";import{createEntityLoader as n}from"../../../loaders/define.js";import{runtimeFile as r}from"../../utils/runtime-file.js";import{createPluginScopedId as i}from"../../utils/scoped-id.js";import{runtimeTemplate as a}from"../../templates.js";import{toPosixPath as o}from"../../../../shared/utils/to-posix-path.js";import{isObject as s}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as c}from"../../../../shared/utils/routes/normalize-route-slug.js";import{publicLink as l}from"../../../versions/public-link.js";import{createApiEntityKey as u}from"../../utils/api-entity-key.js";import{API_DOCS_INFO_BLOCK_DEP_KEY as d}from"../api-docs/server/shared.js";import{getLoadedProjectPlugins as f}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as p}from"../../../api-outputs.js";import{CATALOG_CLASSIC_DEP_KEY as m}from"../catalog-classic/client/contract.js";import{catalogEntityKey as h}from"../catalog-classic/entity-key.js";import{CATALOG_CARD_METADATA_ENTITY_TYPE as g}from"../catalog-classic/card-metadata.js";import{loadVersionGroups as _}from"../catalog-classic/resolve-items.js";import{NON_CONFORMANT as ee,apiPagePath as v,scorecardDetailsFile as y}from"./client/contract.js";import{findTarget as b,readScorecardSettings as x}from"./config.js";import{API_SCORECARD_ENTITY_TYPE as S,RULES_ENTITY_KEY as C,apiScorecardEntityKey as w,isScoredApi as T,scorecardPageEntityKey as E}from"./entities.js";import{collectRuleNames as te,lintApi as ne,resolveLevelConfigs as D,summarizeRules as O}from"./lint.js";import{gzip as k}from"../../../../shared/utils/gzip.js";import{join as A,posix as j,relative as M}from"node:path";import re from"picomatch";const N=`internal.scorecard-classic`,P=`scorecard-classic`,ie=i(N,`api`),ae=i(N,`rules`),oe=i(N,`page`),se=i(N,`card-metadata`),ce=i(N,`badge`),F=n(ie,async e=>{let t=e.file.path,n=e.args.source??t,r=e.routes.byFilePath(t),i=r&&e.routes.get(r.slug);if(!i)return{value:null,metadata:{sourcePath:t}};let a=async t=>({body:await e.createBlobRef(await k(new TextEncoder().encode(JSON.stringify(t))),{format:`binary`}),contentType:`application/gzip`}),o=x(e.config),s=J(e.contentDir),c=b(o.targets,i.metadata),l=b(o.targets.filter(e=>e.rules!==void 0),i.metadata),u=s.paths,d;try{let t=await D({contentDir:e.contentDir,settings:o,plugins:s.plugins,readFile:e.io.readFile});u=[...t.files,...s.paths];let r=l===void 0?void 0:t.targets[o.targets.indexOf(l)];d=await ne({contentDir:e.contentDir,filePath:n,source:await e.io.readFile(A(e.contentDir,n)),configs:Object.fromEntries(o.levels.map(e=>[e.name,r?.[e.name]??t.levels[e.name]]))})}catch(e){return{value:await a(null),metadata:{sourcePath:t},problems:[{code:`scorecard/lint-failed`,message:`The scorecard could not lint this API: ${e instanceof Error?e.message:String(e)}`,location:{filePath:t}}],entityDeps:Y([n,...u])}}let f={...L(o,d.levels,c?.minimumLevel),title:await I(e.entities,t)??j.basename(n),relativePath:t,levels:d.levels};i.version!==null&&(f.version=i.version);let{levels:p,...m}=f,h={...m,levels:Object.fromEntries(Object.entries(p).map(([e,{problems:t,...n}])=>[e,n])),rules:O(p),sourcePath:t,route:i.slug};return{value:await a(f),metadata:h,entityDeps:Y([n,...d.files,...u])}});async function I(e,t){let n=await e.load(u(t)).catch(()=>void 0),r=s(n)&&s(n.info)?n.info:{};return typeof r.title==`string`?r.title:void 0}function L(e,t,n){let r=e.levels.map(e=>e.name),i=r.findIndex(e=>t[e].errors>0),a=i===-1?r.length:i,o=n??r[0],s=r.indexOf(o),c=`HIGHEST`;return a-1<s?c=`BELOW_MINIMUM`:s<r.length-1&&(c=`MINIMUM`),{scorecardLevel:a===0?ee:r[a-1],scorecardLevelIdx:a,targetLevel:o,status:c}}async function R(e,t){let n=await e.get(t);return n!==null&&(n.status!==`ready`||!T(n.metadata))&&(await e.load(t).catch(()=>void 0),n=await e.get(t)),n!==null&&T(n.metadata)?n.metadata:null}async function z(e){let t=[];for(let n of await e.list({type:S})){let r=await R(e,n.key);r!==null&&t.push(r)}return t}function B({sourcePath:e,route:t,...n}){return n}const V=n(ae,async e=>{let t=x(e.config),{perLevel:n,all:r}=await D({contentDir:e.contentDir,settings:t,plugins:J(e.contentDir).plugins,readFile:e.io.readFile}).then(e=>te(e.levels),()=>({perLevel:{},all:[]}));return{value:{levelNames:t.levels.map(e=>e.name),rules:r,rulesPerLevel:n}}}),H=n(oe,async e=>{let t=await e.entities.load(h(e.args.catalogId)),n=await e.entities.load(C),r=(await z(e.entities)).flatMap(t=>{let n=e.routes.get(t.route);return n?[{route:n,api:t}]:[]}),{versionGroups:i,entityDeps:a}=await _(r,e),o=new Map(r.map(({route:e,api:t})=>[l(e,i),B(t)])),s=[];for(let e of t.items){let t=o.get(e.link);t!==void 0&&s.push({...e,metadata:{...e.metadata,scorecard:t,scorecardLevel:t.scorecardLevel}})}let c={...t,items:s,scorecard:{...n,teamMetadataProperty:x(e.config).teamMetadataProperty}},u=JSON.stringify(c);return{value:u.length>65536?await e.createBlobRef(u,{format:`json`}):c,entityDeps:a}}),U=n(se,async e=>({value:(await z(e.entities)).map(e=>({route:e.route,metadata:{scorecardStatus:e.status,scorecardLevel:e.scorecardLevel,scorecardLevelIdx:e.scorecardLevelIdx,scorecardLevels:G(e)}}))})),W=n(ce,async e=>{let t=await R(e.entities,w(e.args.file)),n=t&&e.routes.get(t.route);if(!t||!n)return{value:null};let{versionGroups:r,entityDeps:i}=await _([{route:n}],e),a=l(n,r),o=q(e.config);if(o.length===0)return{value:null};let s=o[0].slug;if(o.length>1){for(let{catalogId:t,slug:n}of o)if((await e.entities.load(h(t))).items.some(e=>e.link===a)){s=n;break}}return{value:{scorecardLevel:t.scorecardLevel,scorecardLevelIdx:t.scorecardLevelIdx,scorecardLevels:G(t),scoreCardSlug:v(K(s),a)},entityDeps:i}});function G(e){return Object.fromEntries(Object.entries(e.levels).map(([e,t])=>[e,{uniqueErrors:t.uniqueErrors,uniqueWarnings:t.uniqueWarnings}]))}function K(e){return j.join(c(e),`scorecard`)}function q(e){return Object.entries(e.catalogClassic??e.catalog??{}).map(([e,t])=>({catalogId:e,slug:String(t.slug)}))}function J(e){let t=f(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>o(M(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function Y(e){return[...new Set(e)].map(e=>({kind:`file`,path:e}))}function X(e){let t=e=>typeof e==`string`||typeof e==`number`;return t(e.manifest.openapi)||t(e.manifest.swagger)}function Z(e){let t=e.manifest[p];return s(t)&&typeof t.root==`string`?t.root:e.path}function Q(e){let t=Z(e);return F.withArgs(t===e.path?{}:{source:t},{stableKey:w(e.path),type:S,metadata:{sourcePath:e.path}})}function $(e,t){if(!X(e))return!1;let n=(t.scorecardClassic??t.scorecard)?.ignore??[];return n.length===0||!re([...n])(Z(e))}function le(e,t){let n=e.filter(e=>e.status===`BELOW_MINIMUM`).map(e=>e.relativePath);if(n.length===0)return;let r=n.slice(0,15).map(e=>`\n - ${e}`),i=n.length-r.length,a=`Detected OpenAPI definitions with score below minimum level:${r.join(``)}${i>0?`\n ... and ${i} more`:``}`;t.config.platform?.ignoreLint??(t.config.scorecardClassic??t.config.scorecard)?.ignoreNonCompliant?t.logger.warn(a):t.logger.error(a)}const ue=e({id:N,version:`2.3.0`,content:{filter:{extensions:[`.yaml`,`.yml`,`.json`]},extractFile(e,t){return $(e,t.config)?{routes:[],entities:[Q(e)]}:null},extractAll(e){let t=e.config.catalogClassic??e.config.catalog??{};if(!e.files.some(X)&&Object.keys(t).length===0)return{routes:[]};let n=x(e.config),r=[V.withArgs({},{stableKey:C})];n.isDefault||r.push(U.withArgs({},{stableKey:`scorecard-classic:card-metadata`,type:g}));let i=[];for(let[e,n]of Object.entries(t)){let t=K(String(n.slug)),a=H.withArgs({catalogId:e},{stableKey:E(e),metadata:{sourcePath:t}});r.push(a),i.push({deps:{[m]:a},metadata:{title:typeof n.title==`string`?n.title:`API design scorecard`},routeId:e,slug:t,template:P,wildcardPrefix:!0})}return{entities:r,routes:i}}},finalize(e){let t=q(e.config).length>0&&!x(e.config).isDefault,n=[],r=[],i=[];for(let a of e.files){let o=$(a,e.config)?e.routes.byFilePath(a.path):void 0;if(o===void 0||(n.push({path:y(a.path),producer:Q(a),audience:{routeSlug:o.slug}}),!t))continue;let s=W.withArgs({file:a.path},{stableKey:`scorecard-classic:badge:${o.slug}`});r.push(s),i.push({slug:o.slug,deps:{[d]:s}})}return{entities:r,attach:i,staticFiles:n}},async buildMetadata(e){if(await e.entities.get(`scorecard-classic:rules`)===null)return;let n=await e.entities.load(C),r=await z(e.entities),i={};for(let e of r){let{rules:t,...n}=B(e);i[e.relativePath]=n}return le(r,e),{scorecardData:i,...n,reuniteIgnoreLint:t(e.config.platform?.ignoreLint)}},loaders:[F,V,H,U,W],templates:{[P]:a(r(`./client/template.tsx`,import.meta.url))}});export{N as SCORECARD_CLASSIC_PLUGIN_ID,P as SCORECARD_CLASSIC_TEMPLATE_ID,ue as scorecardClassicContentPlugin};
1
+ import{defineContentPlugin as e}from"../../define.js";import{toJsonValue as t}from"../../../database/utils/json.js";import{createEntityLoader as n}from"../../../loaders/define.js";import{runtimeFile as r}from"../../utils/runtime-file.js";import{createPluginScopedId as i}from"../../utils/scoped-id.js";import{runtimeTemplate as a}from"../../templates.js";import{isObject as o}from"../../../../shared/utils/is-object.js";import{normalizeRouteSlug as s}from"../../../../shared/utils/routes/normalize-route-slug.js";import{API_DOCS_INFO_BLOCK_DEP_KEY as c}from"../api-docs/server/shared.js";import{CATALOG_CLASSIC_DEP_KEY as l}from"../catalog-classic/client/contract.js";import{toPosixPath as u}from"../../../../shared/utils/to-posix-path.js";import{publicLink as d}from"../../../versions/public-link.js";import{createApiEntityKey as f}from"../../utils/api-entity-key.js";import{getLoadedProjectPlugins as p}from"../../project/loaded-set.js";import{API_OUTPUT_MANIFEST_KEY as m}from"../../../api-outputs.js";import{catalogEntityKey as h}from"../catalog-classic/entity-key.js";import{CATALOG_CARD_METADATA_ENTITY_TYPE as g}from"../catalog-classic/card-metadata.js";import{loadVersionGroups as _}from"../catalog-classic/resolve-items.js";import{NON_CONFORMANT as ee,apiPagePath as v,scorecardDetailsFile as y}from"./client/contract.js";import{findTarget as b,readScorecardSettings as x}from"./config.js";import{API_SCORECARD_ENTITY_TYPE as S,RULES_ENTITY_KEY as C,apiScorecardEntityKey as w,isScoredApi as T,scorecardPageEntityKey as E}from"./entities.js";import{collectRuleNames as te,lintApi as ne,resolveLevelConfigs as D,summarizeRules as O}from"./lint.js";import{gzip as k}from"../../../../shared/utils/gzip.js";import{join as A,posix as j,relative as M}from"node:path";import re from"picomatch";const N=`internal.scorecard-classic`,P=`scorecard-classic`,ie=i(N,`api`),ae=i(N,`rules`),oe=i(N,`page`),se=i(N,`card-metadata`),ce=i(N,`badge`),F=n(ie,async e=>{let t=e.file.path,n=e.args.source??t,r=e.routes.byFilePath(t),i=r&&e.routes.get(r.slug);if(!i)return{value:null,metadata:{sourcePath:t}};let a=async t=>({body:await e.createBlobRef(await k(new TextEncoder().encode(JSON.stringify(t))),{format:`binary`}),contentType:`application/gzip`}),o=x(e.config),s=J(e.contentDir),c=b(o.targets,i.metadata),l=b(o.targets.filter(e=>e.rules!==void 0),i.metadata),u=s.paths,d;try{let t=await D({contentDir:e.contentDir,settings:o,plugins:s.plugins,readFile:e.io.readFile});u=[...t.files,...s.paths];let r=l===void 0?void 0:t.targets[o.targets.indexOf(l)];d=await ne({contentDir:e.contentDir,filePath:n,source:await e.io.readFile(A(e.contentDir,n)),configs:Object.fromEntries(o.levels.map(e=>[e.name,r?.[e.name]??t.levels[e.name]]))})}catch(e){return{value:await a(null),metadata:{sourcePath:t},problems:[{code:`scorecard/lint-failed`,message:`The scorecard could not lint this API: ${e instanceof Error?e.message:String(e)}`,location:{filePath:t}}],entityDeps:Y([n,...u])}}let f={...L(o,d.levels,c?.minimumLevel),title:await I(e.entities,t)??j.basename(n),relativePath:t,levels:d.levels};i.version!==null&&(f.version=i.version);let{levels:p,...m}=f,h={...m,levels:Object.fromEntries(Object.entries(p).map(([e,{problems:t,...n}])=>[e,n])),rules:O(p),sourcePath:t,route:i.slug};return{value:await a(f),metadata:h,entityDeps:Y([n,...d.files,...u])}});async function I(e,t){let n=await e.load(f(t)).catch(()=>void 0),r=o(n)&&o(n.info)?n.info:{};return typeof r.title==`string`?r.title:void 0}function L(e,t,n){let r=e.levels.map(e=>e.name),i=r.findIndex(e=>t[e].errors>0),a=i===-1?r.length:i,o=n??r[0],s=r.indexOf(o),c=`HIGHEST`;return a-1<s?c=`BELOW_MINIMUM`:s<r.length-1&&(c=`MINIMUM`),{scorecardLevel:a===0?ee:r[a-1],scorecardLevelIdx:a,targetLevel:o,status:c}}async function R(e,t){let n=await e.get(t);return n!==null&&(n.status!==`ready`||!T(n.metadata))&&(await e.load(t).catch(()=>void 0),n=await e.get(t)),n!==null&&T(n.metadata)?n.metadata:null}async function z(e){let t=[];for(let n of await e.list({type:S})){let r=await R(e,n.key);r!==null&&t.push(r)}return t}function B({sourcePath:e,route:t,...n}){return n}const V=n(ae,async e=>{let t=x(e.config),{perLevel:n,all:r}=await D({contentDir:e.contentDir,settings:t,plugins:J(e.contentDir).plugins,readFile:e.io.readFile}).then(e=>te(e.levels),()=>({perLevel:{},all:[]}));return{value:{levelNames:t.levels.map(e=>e.name),rules:r,rulesPerLevel:n}}}),H=n(oe,async e=>{let t=await e.entities.load(h(e.args.catalogId)),n=await e.entities.load(C),r=(await z(e.entities)).flatMap(t=>{let n=e.routes.get(t.route);return n?[{route:n,api:t}]:[]}),{versionGroups:i,entityDeps:a}=await _(r,e),o=new Map(r.map(({route:e,api:t})=>[d(e,i),B(t)])),s=[];for(let e of t.items){let t=o.get(e.link);t!==void 0&&s.push({...e,metadata:{...e.metadata,scorecard:t,scorecardLevel:t.scorecardLevel}})}let c={...t,items:s,scorecard:{...n,teamMetadataProperty:x(e.config).teamMetadataProperty}},l=JSON.stringify(c);return{value:l.length>65536?await e.createBlobRef(l,{format:`json`}):c,entityDeps:a}}),U=n(se,async e=>({value:(await z(e.entities)).map(e=>({route:e.route,metadata:{scorecardStatus:e.status,scorecardLevel:e.scorecardLevel,scorecardLevelIdx:e.scorecardLevelIdx,scorecardLevels:G(e)}}))})),W=n(ce,async e=>{let t=await R(e.entities,w(e.args.file)),n=t&&e.routes.get(t.route);if(!t||!n)return{value:null};let{versionGroups:r,entityDeps:i}=await _([{route:n}],e),a=d(n,r),o=q(e.config);if(o.length===0)return{value:null};let s=o[0].slug;if(o.length>1){for(let{catalogId:t,slug:n}of o)if((await e.entities.load(h(t))).items.some(e=>e.link===a)){s=n;break}}return{value:{scorecardLevel:t.scorecardLevel,scorecardLevelIdx:t.scorecardLevelIdx,scorecardLevels:G(t),scoreCardSlug:v(K(s),a)},entityDeps:i}});function G(e){return Object.fromEntries(Object.entries(e.levels).map(([e,t])=>[e,{uniqueErrors:t.uniqueErrors,uniqueWarnings:t.uniqueWarnings}]))}function K(e){return j.join(s(e),`scorecard`)}function q(e){return Object.entries(e.catalogClassic??e.catalog??{}).map(([e,t])=>({catalogId:e,slug:String(t.slug)}))}function J(e){let t=p(e)?.lintPlugins??[];return{plugins:t,paths:t.map(t=>u(M(e,t.path))).filter(e=>e!==``&&!e.startsWith(`../`))}}function Y(e){return[...new Set(e)].map(e=>({kind:`file`,path:e}))}function X(e){let t=e=>typeof e==`string`||typeof e==`number`;return t(e.manifest.openapi)||t(e.manifest.swagger)}function Z(e){let t=e.manifest[m];return o(t)&&typeof t.root==`string`?t.root:e.path}function Q(e){let t=Z(e);return F.withArgs(t===e.path?{}:{source:t},{stableKey:w(e.path),type:S,metadata:{sourcePath:e.path}})}function $(e,t){if(!X(e))return!1;let n=(t.scorecardClassic??t.scorecard)?.ignore??[];return n.length===0||!re([...n])(Z(e))}function le(e,t){let n=e.filter(e=>e.status===`BELOW_MINIMUM`).map(e=>e.relativePath);if(n.length===0)return;let r=n.slice(0,15).map(e=>`\n - ${e}`),i=n.length-r.length,a=`Detected OpenAPI definitions with score below minimum level:${r.join(``)}${i>0?`\n ... and ${i} more`:``}`;t.config.platform?.ignoreLint??(t.config.scorecardClassic??t.config.scorecard)?.ignoreNonCompliant?t.logger.warn(a):t.logger.error(a)}const ue=e({id:N,version:`2.3.0`,content:{filter:{extensions:[`.yaml`,`.yml`,`.json`]},extractFile(e,t){return $(e,t.config)?{routes:[],entities:[Q(e)]}:null},extractAll(e){let t=e.config.catalogClassic??e.config.catalog??{};if(!e.files.some(X)&&Object.keys(t).length===0)return{routes:[]};let n=x(e.config),r=[V.withArgs({},{stableKey:C})];n.isDefault||r.push(U.withArgs({},{stableKey:`scorecard-classic:card-metadata`,type:g}));let i=[];for(let[e,n]of Object.entries(t)){let t=K(String(n.slug)),a=H.withArgs({catalogId:e},{stableKey:E(e),metadata:{sourcePath:t}});r.push(a),i.push({deps:{[l]:a},metadata:{title:typeof n.title==`string`?n.title:`API design scorecard`},routeId:e,slug:t,template:P,wildcardPrefix:!0})}return{entities:r,routes:i}}},finalize(e){let t=q(e.config).length>0&&!x(e.config).isDefault,n=[],r=[],i=[];for(let a of e.files){let o=$(a,e.config)?e.routes.byFilePath(a.path):void 0;if(o===void 0||(n.push({path:y(a.path),producer:Q(a),audience:{routeSlug:o.slug}}),!t))continue;let s=W.withArgs({file:a.path},{stableKey:`scorecard-classic:badge:${o.slug}`});r.push(s),i.push({slug:o.slug,deps:{[c]:s}})}return{entities:r,attach:i,staticFiles:n}},async buildMetadata(e){if(await e.entities.get(`scorecard-classic:rules`)===null)return;let n=await e.entities.load(C),r=await z(e.entities),i={};for(let e of r){let{rules:t,...n}=B(e);i[e.relativePath]=n}return le(r,e),{scorecardData:i,...n,reuniteIgnoreLint:t(e.config.platform?.ignoreLint)}},loaders:[F,V,H,U,W],templates:{[P]:a(r(`./client/template.tsx`,import.meta.url))}});export{N as SCORECARD_CLASSIC_PLUGIN_ID,P as SCORECARD_CLASSIC_TEMPLATE_ID,ue as scorecardClassicContentPlugin};