@redocly/framework 1.0.0-next.7 → 1.0.0-next.8
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.
- package/dist/bundler/build/output-metadata.js +1 -1
- package/dist/bundler/build/run.js +1 -1
- package/dist/bundler/build/vite-config.js +2 -2
- package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
- package/dist/bundler/dev/routes/source-sync-route.js +1 -1
- package/dist/bundler/dev/run.js +1 -1
- package/dist/bundler/dev/runtime-app.js +1 -1
- package/dist/bundler/dev/vite-chunk-url.js +1 -1
- package/dist/bundler/user-markdoc-schema.js +1 -1
- package/dist/bundler/vite-config.base.js +2 -2
- package/dist/cli/args.js +1 -1
- package/dist/cli/commands/build.js +1 -1
- package/dist/cli/commands/dev.js +1 -1
- package/dist/cli/commands/ingest.js +1 -1
- package/dist/cli/commands/translate.js +2 -2
- package/dist/cli/dev-console/index.js +1 -1
- package/dist/cli/log-output/index.js +1 -1
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/client/ai-search/use-ai-search.js +1 -1
- package/dist/client/analytics-page-view.js +1 -1
- package/dist/client/app.js +2 -7
- package/dist/client/client-entry.js +1 -1
- package/dist/client/contexts.js +1 -1
- package/dist/client/dev-problems/ProblemsBar.js +26 -16
- package/dist/client/feedback.js +1 -1
- package/dist/client/l10n/ssr-l10n.js +1 -1
- package/dist/client/l10n/use-l10n-config.js +1 -1
- package/dist/client/products.js +1 -1
- package/dist/client/review/ReviewBar.js +163 -69
- package/dist/client/review/login-url.js +1 -0
- package/dist/client/review/use-review.js +1 -1
- package/dist/client/sidebar/SidebarDataProvider.js +1 -1
- package/dist/client/sidebar/drilldown.js +1 -1
- package/dist/client/ssr.js +1 -1
- package/dist/client/telemetry/config.js +1 -1
- package/dist/client/theme-logo.js +1 -1
- package/dist/client/use-bar-position.js +1 -0
- package/dist/client/use-entity-revisions.js +1 -1
- package/dist/client/use-page-versions.js +1 -1
- package/dist/client/use-search.js +1 -1
- package/dist/client/webmcp/tools/shared.js +1 -1
- package/dist/client/webmcp/tools/site-tools.js +1 -1
- package/dist/client/webmcp/use-webmcp-tools.js +1 -1
- package/dist/content-layer/api-outputs.js +1 -1
- package/dist/content-layer/config-schema.js +1 -1
- package/dist/content-layer/config.js +1 -1
- package/dist/content-layer/database/files.js +1 -1
- package/dist/content-layer/database/finalize.js +1 -1
- package/dist/content-layer/database/invalidation.js +26 -26
- package/dist/content-layer/database/origins.js +1 -1
- package/dist/content-layer/database/problems.d.ts +2 -0
- package/dist/content-layer/database/problems.js +1 -1
- package/dist/content-layer/database/reset.js +1 -1
- package/dist/content-layer/database/schema.d.ts +17 -0
- package/dist/content-layer/database/schema.js +1 -1
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/hash.js +1 -1
- package/dist/content-layer/ingest/l10n-warnings.js +1 -1
- package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
- package/dist/content-layer/ingest/run.js +1 -1
- package/dist/content-layer/ingest/search-sync.js +1 -1
- package/dist/content-layer/ingest/sync.js +1 -1
- package/dist/content-layer/link-checker/delta.js +1 -1
- package/dist/content-layer/link-checker/fingerprint.js +1 -1
- package/dist/content-layer/link-checker/load-view.js +1 -1
- package/dist/content-layer/link-checker/run-build.js +1 -1
- package/dist/content-layer/link-checker/validate.js +1 -1
- package/dist/content-layer/link-checker/view.js +1 -1
- package/dist/content-layer/loaders/context.js +1 -1
- package/dist/content-layer/loaders/define.d.ts +3 -0
- package/dist/content-layer/markdown/client/JsonSchemaTag.js +1 -1
- package/dist/content-layer/markdown/client/code-highlight-notation.js +3 -3
- package/dist/content-layer/markdown/client/markdoc-components.js +2 -2
- package/dist/content-layer/markdown/client/markdown-text.js +1 -1
- package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
- package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
- package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
- package/dist/content-layer/markdown/nodes/fence.js +1 -1
- package/dist/content-layer/markdown/nodes/heading.js +1 -1
- package/dist/content-layer/markdown/nodes/table.js +1 -1
- package/dist/content-layer/markdown/resolve/audience-tag.d.ts +1 -5
- package/dist/content-layer/markdown/resolve/audience-tag.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
- package/dist/content-layer/markdown/resolve/references.js +1 -1
- package/dist/content-layer/markdown/search/to-markdown.js +2 -2
- package/dist/content-layer/markdown/search/to-sections.d.ts +1 -1
- package/dist/content-layer/markdown/search/to-sections.js +1 -1
- package/dist/content-layer/markdown/server/render.js +1 -1
- package/dist/content-layer/markdown/tags/html.d.ts +2 -2
- package/dist/content-layer/markdown/tags/html.js +1 -1
- package/dist/content-layer/markdown/tags/openapi.js +1 -1
- package/dist/content-layer/markdown/tags/variant.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/materialization/entity.js +1 -1
- package/dist/content-layer/materialization/static-files.js +1 -1
- package/dist/content-layer/plugins/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/event-handlers.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/template.js +11 -3
- package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +21 -11
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-sidebar.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-decorator.d.ts +1 -4
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-decorator.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +13 -13
- package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/access.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.d.ts +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/constants.d.ts +17 -0
- package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/capabilities.js +6 -6
- package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/discover.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
- package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/allowed-http-methods.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/api-call-operations.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/call-api.js +2 -0
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js +10 -10
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/outcome-pages.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -6
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-bridge.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/ssrf-guard.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/upstream-detail.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tool-list.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
- package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/callback.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/token.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/tokens.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/skills-resources.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-catalog.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
- package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
- package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/index.d.ts +2 -1
- package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
- package/dist/content-layer/plugins/internal/sidebar/subtree.js +1 -1
- package/dist/content-layer/plugins/internal/skills/index.js +1 -1
- package/dist/content-layer/plugins/internal/skills/server/routes.js +1 -1
- package/dist/content-layer/plugins/project/load.js +2 -2
- package/dist/content-layer/plugins/types/markdoc.d.ts +2 -0
- package/dist/content-layer/plugins/utils/link-access.js +1 -1
- package/dist/content-layer/plugins/utils/route-index.js +1 -1
- package/dist/content-layer/problems/codes.js +1 -1
- package/dist/content-layer/search/postings/fragment-field.d.ts +2 -0
- package/dist/content-layer/search/postings/fragment-field.js +1 -1
- package/dist/content-layer/search/postings/postings-store.js +1 -1
- package/dist/content-layer/server/database.js +1 -1
- package/dist/content-layer/static/registry.js +1 -1
- package/dist/content-layer/templates/template-set.js +1 -1
- package/dist/content-layer/versions/redirect.js +1 -1
- package/dist/content-layer/versions/resolve.js +1 -1
- package/dist/content-layer/versions/version-groups.d.ts +5 -1
- package/dist/content-layer/versions/version-groups.js +1 -1
- package/dist/server/app.js +3 -3
- package/dist/server/ask-ai/route.js +1 -1
- package/dist/server/auth/access-config.js +1 -1
- package/dist/server/auth/gate.js +1 -1
- package/dist/server/auth/middleware.js +1 -1
- package/dist/server/auth/oidc.js +1 -1
- package/dist/server/auth/request.js +1 -1
- package/dist/server/auth/routes.js +1 -1
- package/dist/server/content.js +12 -12
- package/dist/server/cors-proxy/handler.js +1 -1
- package/dist/server/feedback/route.js +1 -1
- package/dist/server/lambda-entry.js +1 -1
- package/dist/server/manifest-assets.js +4 -4
- package/dist/server/node-entry.js +1 -1
- package/dist/server/page-handlers.js +2 -2
- package/dist/server/plugin-context.js +1 -1
- package/dist/server/review/route.js +1 -1
- package/dist/server/search/route.js +1 -1
- package/dist/server/seo-tags.js +2 -2
- package/dist/server/sitemap.js +1 -1
- package/dist/server/static-files/serve.js +1 -1
- package/dist/server/subprocess/child-entry.js +1 -1
- package/dist/server/subprocess/host.js +1 -1
- package/dist/shared/constants/manifest-version.d.ts +3 -1
- package/dist/shared/constants/openapi-operation-methods.d.ts +2 -0
- package/dist/shared/constants/openapi-operation-methods.js +1 -0
- package/dist/shared/constants/review.d.ts +5 -0
- package/dist/shared/constants/review.js +1 -1
- package/dist/shared/constants/system-routes.js +1 -1
- package/dist/shared/load-dot-env.js +1 -1
- package/dist/shared/rbac/api-docs.d.ts +2 -1
- package/dist/shared/rbac/api-docs.js +1 -1
- package/dist/shared/rbac/engine.d.ts +12 -9
- package/dist/shared/rbac/engine.js +0 -0
- package/dist/shared/rbac/filter.js +1 -1
- package/dist/shared/rbac/l10n-rules.js +1 -1
- package/dist/shared/rbac/route-scope.d.ts +1 -1
- package/dist/shared/rbac/team-templates.js +1 -1
- package/dist/shared/types/auth.d.ts +1 -0
- package/dist/shared/types/config.d.ts +1 -0
- package/dist/shared/utils/l10n.js +1 -1
- package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
- package/drizzle/20261111152552_page_markdown_rbac_scope/migration.sql +1 -0
- package/package.json +6 -5
- package/dist/client/review/use-bar-position.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../constants.js";import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{
|
|
1
|
+
import"../constants.js";import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{innerToolErrorClass as t,thrownErrorClass as n}from"./tool-errors.js";import{isServerTelemetryEnabled as r}from"../../../../../server/telemetry/collector.js";import{sendServerEvent as i,sendServerEvents as a}from"../../../../../server/telemetry/sender.js";import{auditCode as o,auditInput as s,auditSha256 as c,auditStack as l,isCallToolResult as u,toolOutputText as d,toolResultText as f}from"./audit.js";import{SANDBOX_FAILURE as p}from"./codemode/constants.js";import{parseUserAgent as m,readListingSource as h}from"./mcp-client.js";import{randomUUID as g}from"node:crypto";import{ulid as _}from"ulid";const v={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function y(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function b(i){let{mode:c,requestId:g,callerSubject:_,clientIp:b,logger:x}=i,S=i.env??process.env,C=r(S),w=y(_),{client:T,clientVersion:E}=m(i.userAgent),D=i.metadata.messageId,O={client:T,client_version:E,message_id:typeof D==`string`?D:void 0,listing_source:h(i.request)},j=[],M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new WeakSet,P=(e,t)=>{j.push({type:e,data:[t],requestId:g,time:/* @__PURE__ */ new Date,actor:w,clientIp:b})},F=t=>{try{t()}catch(t){x?.warn(`MCP telemetry failed: ${e(t)}`)}},I=(e,t,n)=>P(`com.redocly.mcpServer.toolCalled`,{...v,tool:e,mode:c,output_length:n,duration_ms:t,...O}),L=(e,t,n)=>{n.stack&&x?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:g,stack:n.stack}),P(`com.redocly.mcpServer.error`,{...v,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...O})},R=async(n,r,i)=>{let a=Date.now(),o;try{o=await r()}catch(r){let o=t(r),s=o===`server_error`;throw i.set(e(r),{tool:n,reason:s?`server_error`:`inner_tool_error`}),F(()=>L(n,Date.now()-a,{message:e(r),stack:s&&r instanceof Error?r.stack??``:``,error_class:o})),r}return F(()=>I(n,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){F(()=>{if(!u(n)||n.isError!==!0){I(e,t,d(n).length);return}N.has(n)||L(e,t,{message:f(n,` `),stack:``,error_class:e===`execute`?`sandbox_error`:`tool_error`})})},toolThrew(t,r,i){F(()=>{let a=n(i);L(t,r,{message:e(i),stack:a===`server_error`&&i instanceof Error?i.stack??``:``,error_class:a})})},trackCodeExecution(t,n){let r=Date.now(),i=o(t),a=/* @__PURE__ */ new Map,s=0;return{hostFetch:n&&(t=>(s+=1,n(t).catch(t=>{throw a.set(e(t),{reason:`runtime_error`}),t}))),innerToolCall(e,t){let n=R(e,t,a),r=n.then(()=>void 0,()=>void 0);return M.add(r),r.then(()=>M.delete(r)),n},finish(e,t,n){let o=e.failure===p.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&N.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=k(e.failure,o,n),d=o?.tool;F(()=>P(`com.redocly.mcpServer.codeExecuted`,{...v,code_sha256:i.sha256,code_length:i.length,fetch_count:s,outcome:c,flags:i.flags,duration_ms:l,failure_reason:u,failed_tool:d,...O})),x?.info(`Gateway MCP code executed [${i.sha256.slice(0,12)}] outcome=${c} codeLength=${i.length} fetchCount=${s}`+(i.flags?` flags=${i.flags}`:``)+` durationMs=${l}`+(u?` failureReason=${u}`:``)+(d?` failedTool=${d}`:``))}}},gatewayFetchPerformed({host:e,method:t,outcome:n,durationMs:r,path:i,api:a,status:o,bytes:s,injectedScheme:c}){F(()=>P(`com.redocly.mcpServer.gatewayFetchPerformed`,{...v,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),x?.info(`Gateway MCP fetch [${t} ${e}] outcome=${n}`+(i===void 0?``:` path=${i}`)+(a===void 0?``:` api=${a}`)+(o===void 0?``:` status=${o}`)+(c===void 0?``:` injectedScheme=${c}`)+(s===void 0?``:` bytes=${s}`)+` durationMs=${r}`)},gatewayFetchRateLimited({scope:e,limit:t,retryAfterSeconds:n}){F(()=>P(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...v,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!C){j=[];return}await A(M,300);let e=j;j=[],await a(e,{env:S,fetcher:i.fetcher,logger:x})}}}function x(e,t){let{requestId:n=g(),callerSubject:r,clientIp:a}=t.caller??{};return i({...e,requestId:n,actor:y(r),clientIp:a},t)}function S(e,t,n={}){return x({type:`com.redocly.mcpServer.error`,data:[{...v,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function C({scope:e,retryAfterSeconds:t,limit:n},r={}){return x({type:`com.redocly.mcpServer.rateLimited`,data:[{...v,scope:e,retry_after_seconds:t,limit:n}]},r)}function w(e){let t=e||_(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function T(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.started`,data:[{...w(e),redirect_uri:t}]},n)}function E(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...w(e),redirect_uri:t}]},n)}function D(e,t,n,r,i={}){return x({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...w(e),error:n,error_details:r,error_class:t}]},i)}function O(e={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`},signal:`trace`},e)}function k(e,t,n){return e===p.HostError?t?.reason??p.RuntimeError:e===p.RuntimeError&&n!==void 0?`unknown_tool`:e}async function A(e,t){if(e.size===0)return;let n;await Promise.race([Promise.allSettled(e),new Promise(e=>{n=setTimeout(e,t)})]),clearTimeout(n)}export{b as createMcpTelemetry,E as sendMcpAuthorizationCompleted,D as sendMcpAuthorizationFailed,T as sendMcpAuthorizationStarted,C as sendMcpRateLimited,S as sendMcpRequestError,O as sendMcpServerCardServed};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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{notFoundResponse as o}from"../../../../../../server/plugin-context.js";import{getSessionIssuer as s}from"../../../../../../server/auth/middleware.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 o();let m=s(f);if(!m)return o();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 +1 @@
|
|
|
1
|
-
import{isMcpHidden as e}from"../config-gate.js";import{REALM_SESSION_COOKIE as t}from"../../../../../../server/auth/constants.js";import{
|
|
1
|
+
import{isMcpHidden as e}from"../config-gate.js";import{REALM_SESSION_COOKIE as t}from"../../../../../../server/auth/constants.js";import{notFoundResponse as n}from"../../../../../../server/plugin-context.js";import{getBearerVerifier as r,getSessionIssuer as i}from"../../../../../../server/auth/middleware.js";import{MCP_REFRESH_SESSION_LIFETIME_SEC as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import{auditInput as s}from"../audit.js";import{sendMcpAuthorizationCompleted as c}from"../mcp-telemetry.js";import{loadPageSite as l}from"../gateway/credentials-page/site-branding.js";import{isLoopbackRedirect as u,parseRedirectUri as d}from"./redirect-uri.js";import{isClientMetadataDocumentUrl as f}from"./client-metadata.js";import{reportMcpAuthorizationFailure as p,withMcpFailureReporting as m}from"./error-reporting.js";import{sessionClaimsFromSession as h,sha256Base64Url as g,signMcpArtifact as _,verifyMcpArtifact as v}from"./tokens.js";import{CONSENT_PAGE_HEADERS as y,consentInvalidPage as b,consentPage as x}from"./consent-page.js";import{hasConsent as S,saveConsent as C}from"./store.js";import{getCookie as w}from"hono/cookie";const T={"Cache-Control":`no-store`},E=`Missing context token`;function D(e){let t=e.searchParams.get(`context`);if(t)return t;let n=e.pathname.split(`/`).filter(Boolean).pop();return n&&n!==`callback`?n:null}async function O(e,n){let i=new URL(e.req.url),a=w(e,t),o=a?await r(e)?.(a):null;return{method:e.req.method,path:`${i.pathname}${i.search}`,referer:e.req.header(`referer`)??null,user_agent:n.request.userAgent,has_session_cookie:a!==void 0,has_user_session:!!o&&o?.claims.tokenUse!==`mcp_access_token`}}function k(a){return async(o,c)=>{if(e(c.config))return n();let l=i(o);if(!l)return n();let u=D(new URL(o.req.url));if(!u){let e=await O(o,c);return await p(c,E,{details:s(JSON.stringify(e)),logFields:e}),o.text(E,400,T)}let f,m,h;try{if(f=await v(u,l.artifactSecret,`mcp_context`),h=f.sessionId,o.set(`realmMcpSessionId`,h),m=d(f.redirectUri),!m)throw Error(`Invalid MCP context`)}catch(e){let t=await p(c,e,{sessionId:h,errorClass:`client_error`,logMessage:`MCP callback failed`});return o.text(`Invalid MCP callback: ${t}`,400,T)}let g=w(o,t),_=g?await r(o)?.(g):null;return!g||!_||_.claims.tokenUse===`mcp_access_token`?(await p(c,`Authentication required`,{sessionId:h}),o.text(`Authentication required`,401,T)):a(o,c,{issuer:l,contextToken:u,mcpContext:f,redirectUrl:m,sessionToken:g,session:_})}}async function A(e,t,{issuer:n,mcpContext:r,redirectUrl:i,session:o}){let s=Math.floor(Date.now()/1e3),l=await _({type:`mcp_auth_code`,sessionId:r.sessionId,clientId:r.clientId,redirectUri:r.redirectUri,claims:h(o),sessionExp:s+a,codeChallenge:r.codeChallenge,codeChallengeMethod:r.codeChallengeMethod},n.artifactSecret,s+600),u=new URL(i);return u.searchParams.set(`code`,l),r.state&&u.searchParams.set(`state`,r.state),await c(r.sessionId,r.redirectUri,{logger:t.logger}),e.header(`Cache-Control`,`no-store`),e.redirect(u.toString(),302)}async function j(e,t,{mcpContext:n,redirectUrl:r}){let i=new URL(r);return i.searchParams.set(`error`,`access_denied`),n.state&&i.searchParams.set(`state`,n.state),await p(t,`access_denied`,{sessionId:n.sessionId}),e.header(`Cache-Control`,`no-store`),e.redirect(i.toString(),302)}function M({mcpContext:e,session:t}){return{idpId:t.claims.idpId,subject:t.viewer.sub,clientId:e.clientId,redirectUri:e.redirectUri}}function N({issuer:e,sessionToken:t,contextToken:n}){return _({type:`mcp_consent`,sessionHash:g(t),contextHash:g(n)},e.artifactSecret,Math.floor(Date.now()/1e3)+300)}async function P(e,{issuer:t,sessionToken:n,contextToken:r}){try{let i=await v(e,t.artifactSecret,`mcp_consent`);return i.sessionHash===g(n)&&i.contextHash===g(r)}catch{return!1}}const F=e=>e.text(`MCP authorization could not be completed`,500,T),I=m(k(async(e,t,n)=>{if(u(n.redirectUrl)||await S(t.kv,M(n)))return A(e,t,n);let{clientId:r,clientName:i}=n.mcpContext,{viewer:s}=n.session,c=x({site:await l(t),user:s.email||s.name||s.sub,clientName:i??void 0,clientIdHost:f(r)?new URL(r).host:void 0,redirectUrl:n.redirectUrl,scopes:o,accessLifetimeHours:a/3600,rememberDays:30,consentToken:await N(n)});return e.set(`realmCacheControlOwned`,!0),new Response(c,{status:200,headers:y})}),F),L=m(k(async(e,t,n)=>{let r=await e.req.formData().catch(()=>null),i=r?.get(`consent`);return typeof i!=`string`||!await P(i,n)?new Response(b(await l(t)),{status:403,headers:y}):r?.get(`decision`)===`allow`?(await C(t.kv,M(n)),A(e,t,n)):j(e,t,n)}),F);export{I as mcpCallback,L as mcpConsent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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{publicOrigin as l}from"../../../../utils/request-origin.js";import{notFoundResponse as u}from"../../../../../../server/plugin-context.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 u();let i=l(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 u();let o=l(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 +1 @@
|
|
|
1
|
-
import{isMcpHidden as e}from"../config-gate.js";import{MCP_ACCESS_TOKEN_USE as t}from"../../../../../../server/auth/constants.js";import{
|
|
1
|
+
import{isMcpHidden as e}from"../config-gate.js";import{MCP_ACCESS_TOKEN_USE as t}from"../../../../../../server/auth/constants.js";import{notFoundResponse as n}from"../../../../../../server/plugin-context.js";import{getSessionIssuer as r}from"../../../../../../server/auth/middleware.js";import{MCP_ACCESS_TOKEN_TTL_SEC as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o,TOKEN_RESPONSE_HEADERS as s}from"./constants.js";import{refuseMcpOAuth as c,withMcpFailureReporting as l}from"./error-reporting.js";import{signMcpArtifact as u,verifyMcpArtifact as d,verifyPkce as f}from"./tokens.js";import{redeemAuthorizationCode as p,redeemRefreshToken as m}from"./store.js";async function h(e,n,r,a){e.set(`realmCacheControlOwned`,!0);let l=Math.floor(Date.now()/1e3);if(l>=a.sessionExp)return c(e,n,`invalid_grant`,`Session has expired`);let d=Math.min(i,a.sessionExp-l),[f,p]=await Promise.all([r.mint({...a.claims,tokenUse:t},l+d),u({type:`mcp_refresh_token`,sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp},r.artifactSecret,a.sessionExp)]);return e.json({access_token:f,token_type:`Bearer`,expires_in:d,refresh_token:p,scope:o.join(` `)},200,{...s})}const g=l(_,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500,{...s}));async function _(t,i){if(e(i.config))return n();let o=r(t);if(!o)return n();let s;try{s=await t.req.formData()}catch{return c(t,i,`invalid_request`,`Expected an application/x-www-form-urlencoded body`)}let l=s.get(`grant_type`);return typeof l!=`string`||!a.includes(l)?c(t,i,`invalid_request`,`Invalid grant type`):l===`refresh_token`?y(t,i,o,s):v(t,i,o,s)}async function v(e,t,n,r){let i=r.get(`code`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`Missing authorization code`);let a;try{a=await d(i,n.artifactSecret,`mcp_auth_code`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid authorization code`,`MCP token exchange failed`)}let o=r.get(`redirect_uri`);if(typeof o!=`string`||o!==a.redirectUri)return c(e,t,`invalid_grant`,`redirect_uri mismatch`);let s=r.get(`client_id`);if(typeof s!=`string`||s!==a.clientId)return c(e,t,`invalid_grant`,`Client mismatch`);let l=r.get(`code_verifier`);return typeof l!=`string`||l===``?c(e,t,`invalid_grant`,`code_verifier required`):f(a.codeChallenge,a.codeChallengeMethod,l)?await p(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Authorization code already used`):c(e,t,`invalid_grant`,`code_verifier mismatch`)}async function y(e,t,n,r){let i=r.get(`refresh_token`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`refresh_token is required`);let a;try{a=await d(i,n.artifactSecret,`mcp_refresh_token`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid refresh token`,`MCP refresh token rejected`)}let o=r.get(`client_id`);return typeof o!=`string`||o!==a.clientId?c(e,t,`invalid_grant`,`Client mismatch`):await m(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Refresh token already used`,`MCP refresh rejected: the refresh token was already used`)}export{g as mcpToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SUPPORTED_CODE_CHALLENGE_METHODS as e}from"./constants.js";import{createHash as t,timingSafeEqual as n}from"node:crypto";import{
|
|
1
|
+
import{SUPPORTED_CODE_CHALLENGE_METHODS as e}from"./constants.js";import{createHash as t,timingSafeEqual as n}from"node:crypto";import{sign as r,verify as i}from"hono/jwt";import{ulid as a}from"ulid";const o=`HS256`;async function s(e,t,n){let i=Math.floor(Date.now()/1e3);return r({...e,jti:a(),iat:i,exp:n},t,o)}async function c(e,t,n){let r=await i(e,t,o);if(r.type!==n)throw Error(`Expected a ${n} token.`);return r}function l(e,r,i){if(!e||!u(r))return!1;let a=Buffer.from(t(`sha256`).update(i).digest(`base64url`)),o=Buffer.from(e);return a.length===o.length&&n(a,o)}function u(t){return e.includes(t??``)}function d(e){return t(`sha256`).update(e).digest(`base64url`)}function f({viewer:e,claims:t}){return{sub:e.sub,email:e.email,name:e.name,picture:e.picture,teams:[...e.teams],idpId:t.idpId}}export{u as isSupportedCodeChallengeMethod,f as sessionClaimsFromSession,d as sha256Base64Url,s as signMcpArtifact,c as verifyMcpArtifact,l as verifyPkce};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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{publicBaseUrl as o,publicOrigin as s}from"../../../utils/request-origin.js";import{formatError as c}from"./tool-errors.js";import{notFoundResponse as l}from"../../../../../server/plugin-context.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: ${c(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)}),c=new URL(t(e),s(r.request)).href,[l,u]=await Promise.all([w(o,c,`server/discover`),i?void 0:w(o,c,`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,_meta:a})=>({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:S}}async function D(n,s){if(i(s.config))return l();n.set(`realmCacheControlOwned`,!0);let c=await m({kv:s.kv,ip:s.request.ip,bucket:`card`,headers:u,logger:s.logger});if(c)return c;let f=g(s.config,s.request),h=r(a(s.config)),_=await E(s,h).catch(e=>{T(s,e)}),{capabilities:v,instructions:b,tools:x}=_??C;return await p({logger:s.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:o(s.config,s.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 +1 @@
|
|
|
1
|
-
import{
|
|
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 +1 @@
|
|
|
1
|
-
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as n}from"../../../types/skill-entity.js";import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as n}from"../../../types/skill-entity.js";import{publicOrigin as r}from"../../../utils/request-origin.js";import{isEntityScopeVisible as i}from"../../../../../shared/rbac/entity-scope.js";async function a(a){if(a.config.skills?.hide===!0)return[];let o=await a.entities.list({type:n}),s=r(a.request),c=e=>i(e,a.request.teams,e=>a.logger?.warn(e));return o.flatMap(n=>{let{slug:r,title:i,description:o}=n.metadata??{};return typeof r!=`string`||!c(n)?[]:[{slug:r,title:i??r,description:o??``,uri:`${s}${e(t(r))}`,read:async()=>(await a.entities.load(n.key)).content}]})}export{a as loadSkillResources};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compileContentGlob as e}from"../../../../utils/glob.js";import{SPEC_KIND_OPENAPI as t}from"../../../../../../shared/constants/api-spec-kinds.js";import{
|
|
1
|
+
import{compileContentGlob as e}from"../../../../utils/glob.js";import{SPEC_KIND_OPENAPI as t}from"../../../../../../shared/constants/api-spec-kinds.js";import{OPERATION_METHODS as n}from"../../../../../../shared/constants/openapi-operation-methods.js";import{filterApiDocsByRbac as r}from"../../../../../../shared/rbac/api-docs.js";import{canonicalSlugPath as i}from"../../ignored-routes.js";import{formatError as a}from"../tool-errors.js";import{apiTitleKey as o,compareApiDescriptions as s}from"./api-titles.js";import{absolutePath as c,findDocumentedPath as l,formatCandidates as u,isDefinitionHidden as d,recoveryToolNames as f,visibleMethodsAt as p}from"./openapi-document.js";const m=/* @__PURE__ */ new WeakMap;function h(e,n){let i=m.get(e);i||(i=/* @__PURE__ */ new Map,m.set(e,i));let o=i.get(n);if(o)return o;let s=t=>e.logger?.warn(t),c=e.entities.load(n).then(n=>({full:n,visible:r(n,t,e.request.teams,{warn:s})})).catch(e=>(s(`MCP: skipping api entity "${n}": ${a(e)}`),null));return i.set(n,c),c}const g=new Set(n);function _(e){return Object.values(e.paths??{}).some(e=>typeof e==`object`&&!!e&&Object.keys(e).some(e=>g.has(e.toLowerCase())))}function v(e,t,n){let{title:r=``,version:i=``,description:a}=t.info??{};return{entityKey:e.entityKey,definition:t,fullDefinition:n,relativePath:e.relativePath,name:r,description:typeof a==`string`?a:``,version:String(i),servers:t.servers??[]}}async function y(t){let n=t.config.mcp?.ignore??[],r=n.length>0?e(n):()=>!1;return(await t.entities.list({type:`api`})).flatMap(({key:e,metadata:t})=>{let{specType:n,sourcePath:a,routeSlug:o}=t??{};return n!==`openapi`||typeof a!=`string`||r(a)||typeof o==`string`&&r(i(o,a))?[]:[{entityKey:e,relativePath:a}]})}async function b(e,t){let n=await h(e,t.entityKey);return!n?.visible||!_(n.visible)||d(n.visible.info)?null:v(t,n.visible,n.full)}async function x(e){let t=await y(e);return(await Promise.all(t.map(t=>b(e,t)))).filter(e=>e!==null)}const S=/* @__PURE__ */ new Set([`api`,`apis`,`rest`,`restful`,`openapi`,`graphql`,`spec`,`specification`,`service`,`services`]);function C(e){return e.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean)}function w(e){return new Set(C(e).filter(e=>!S.has(e)))}function T(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function E(e,t,n){let r=w(t);return e.map(e=>{let t=e[n];return{api:e,text:t,score:[...w(t)].filter(e=>r.has(e)).length}}).sort((e,t)=>t.score-e.score||e.text.localeCompare(t.text)).map(({api:e})=>e)}function D(e,t){return u(E(e,t,`name`).map(e=>`"${e.name}" (${e.relativePath})`))}function O(e,t){return u(E(e,t,`relativePath`).map(e=>`"${e.relativePath}"`))}function k(e,t){let n=o(t);if(!n)return{matches:[],isExactTitle:!1};let r=e.map(e=>({api:e,title:o(e.name)})),i=e=>e.map(({api:e})=>e),a=r.filter(({title:e})=>e===n);if(a.length>0)return{matches:i(a),isExactTitle:!0};let s=r.filter(({title:e})=>e.includes(n));if(s.length>0)return{matches:i(s),isExactTitle:!1};let c=w(n);return c.size===0?{matches:[],isExactTitle:!1}:{matches:i(r.filter(({title:e})=>{let t=w(e);return t.size>0&&T(t,c)})),isExactTitle:!1}}function A(e,t,n){let{matches:r,isExactTitle:i}=k(e,t);if(r.length===0)return;if(!i){let e=[...new Set(r.map(({name:e})=>e))];if(e.length>1)throw Error(`"${t}" matches ${e.length} APIs: ${u(e.map(e=>`"${e}"`))}. Pass one of those names exactly, or the "filePath" parameter from list-apis.`)}let a=n?r.filter(e=>e.version===n):r;if(a.length===0){let e=[...new Set(r.map(({version:e})=>e||`(no version)`))];throw Error(`"${r[0].name||t}" has no version "${n}". Available versions: ${u(e)}.`)}let[o,...c]=[...a].sort(s);return{api:o,otherMatches:c.length>0?c:void 0}}function j(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e.filter(({name:e})=>e.toLowerCase().includes(n));return r.length>0?r:e.filter(({description:e})=>e.toLowerCase().includes(n))}function M({version:e,relativePath:t}){return{version:e||void 0,filePath:t}}function N(e,t=[]){return{api:e,otherMatches:t.length>0?t.map(M):void 0}}function P(e){return`Pass \`name\` (the API title, or a unique part of it) or \`filePath\` from ${f(e).listApis}.`}async function F(e,t){let{name:n,version:r,filePath:i}=e;if(!i&&!n)return I(e,t);let a=await y(t),o=i??n,s=a.find(e=>e.relativePath===o),c=s&&await b(t,s);if(c)return N(c);let l=await x(t);if(i){let e=O(l,i);throw Error(`No API found with filePath "${i}". `+(e?`Available file paths: ${e}. `:``)+`File paths come from ${f(t.mcpMode).listApis}.`)}let u=A(l,n??``,r);if(u)return N(u.api,u.otherMatches);let d=D(l,n??``);throw Error(d?`No API found matching "${n}". Available APIs: ${d}. Pass one of those names, or its \`filePath\`.`:`No API found matching "${n}".`)}async function I({path:e,method:t,version:n},r){let i=await x(r);if(i.length===0)throw Error(`This project documents no OpenAPI description.`);if(i.length===1){let[e]=i;if(n&&e.version!==n)throw Error(`"${e.name}" has no version "${n}". Available versions: ${e.version||`(no version)`}.`);return N(e)}if(!e||!t||i.length>10)throw Error(`${P(r.mcpMode)} Available APIs: ${D(i,``)}.`);let a=[],o=/* @__PURE__ */ new Set,d=[],f=t.toUpperCase();for(let t of i){let n=l(t.definition,e);if(!n)continue;let r=p(t.definition,n.path);r.includes(f)?(a.push(t),n.isTemplateMatch&&o.add(t)):r.length>0&&d.push({api:t,methods:r})}if(a.sort(s),a.length===0)throw R(i,d,e,t,r.mcpMode);let m=n?a.filter(e=>e.version===n):a;if(m.length===0){let t=[...new Set(a.map(({version:e})=>e||`(no version)`))];throw Error(`No API documenting "${c(e)}" has version "${n}". Available versions: ${u(t)}.`)}let h=m.filter(e=>!o.has(e));return L(h.length>0?h:m,e,t,r.mcpMode)}function L(e,t,n,r){let i=new Set(e.map(({name:e})=>o(e)));if(i.size>1){let a=[...i].map(t=>{let[n]=e.filter(e=>o(e.name)===t);return`"${n.name}" (${n.relativePath})`});throw Error(`${n.toUpperCase()} ${c(t)} is documented by ${i.size} APIs: ${u(a)}. Pass \`name\` or \`filePath\` from ${f(r).listApis} to pick one.`)}let[a,...s]=e;return N(a,s)}function R(e,t,n,r,i){if(t.length>0){let e=t.map(({api:e,methods:t})=>`"${e.name}" (${e.relativePath}) documents ${u(t)}.`).join(` `);return/* @__PURE__ */ Error(`No API documents ${r.toUpperCase()} ${c(n)}. ${e}`)}let{endpoints:a,search:o}=f(i);return/* @__PURE__ */ Error(`No API in this project documents ${c(n)}. Available APIs: ${D(e,``)}. Call ${a} with one of them, or ${o} with a keyword from the request.`)}export{D as describeAvailableApis,j as filterApisByName,A as findApiByNameAndVersion,x as loadApiCatalog,F as resolveApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{OPERATION_METHODS as e}from"../../../../../../shared/constants/openapi-operation-methods.js";import{toolNameForMode as t}from"../codemode/tool-declarations.js";import{replaceServerVariables as n}from"@redocly/api-docs/server";const r=new Set(e);function i(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function a(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function o(e){if(!(`x-mcp`in e))return e;let{"x-mcp":t,...n}=e;return n}function s(e){return!e||i(e)?[]:Object.entries(e).filter(e=>{let[t,n]=e;return r.has(t.toLowerCase())&&typeof n==`object`&&!!n&&!i(n)})}function c(e){let t=[];for(let[n,r]of Object.entries(e.paths??{}))for(let[e,i]of s(r))t.push({path:n,method:e.toUpperCase(),summary:i.summary,description:i.description,security:i.security});return t}function l(e,t){return s(e.paths?.[t]).map(([e])=>e.toUpperCase()).sort()}function u(e){return Object.keys(e.paths??{}).filter(t=>l(e,t).length>0).sort()}function d(e){let t={};for(let[n,a]of Object.entries(e.paths??{})){if(typeof a!=`object`||!a||i(a))continue;let e=0,s=Object.entries(o(a)).flatMap(([t,n])=>r.has(t.toLowerCase())?i(n)?[]:(e+=1,[[t,typeof n==`object`&&n?o(n):n]]):[[t,n]]);e!==0&&(t[n]=Object.fromEntries(s))}return{...e,info:o(e.info),paths:t}}function f(e){return e.startsWith(`/`)?e:`/${e}`}function p(e){let[t]=e.replace(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*/i,``).split(/[?#]/,1);return f(t)}function m(e){let t=e.length;for(;t>1&&e[t-1]===`/`;)--t;return e.slice(0,t)}function h(e,t){let r=p(t),i=m(r),a=i.toLowerCase(),o=/* @__PURE__ */ new Set([r,i]);for(let t of e.servers??[]){let e=m(p(n(t)));e!==`/`&&a.startsWith(`${e.toLowerCase()}/`)&&o.add(i.slice(e.length))}return[...o]}function g(e){return e.split(`/`).slice(1)}const _=/^\{[^}]+\}$/;function v(e){return e.startsWith(`:`)?e.length>1:_.test(e)}function y(e){let t=[],n=0;for(let r=e.indexOf(`{`);r!==-1;r=e.indexOf(`{`,n)){let i=e.indexOf(`}`,r);if(i===-1)break;t.push(e.slice(n,r)),n=i+1}return t.push(e.slice(n)),t}function b(e,t){let n=y(e);if(n.length===1)return t===n[0];let r=n[0],i=n[n.length-1];if(!t.startsWith(r))return!1;let a=r.length;for(let e of n.slice(1,-1)){let n=t.indexOf(e,a+1);if(n===-1)return!1;a=n+e.length}return t.length-i.length>a&&t.endsWith(i)}function x(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return v(r)?_.test(e):b(e,r)})}function S(e){return e.map(e=>g(e.toLowerCase()))}function C(e,t){let n=g(e.toLowerCase());return t.some(e=>x(n,e))}function w(e,t){let n=f(t);if(e.paths?.[n])return{path:n,isTemplateMatch:!1};let r=h(e,t),i=u(e),a=r.find(e=>i.includes(e));if(a)return{path:a,isTemplateMatch:!1};for(let e of r.map(e=>e.toLowerCase())){let t=i.find(t=>t.toLowerCase()===e);if(t)return{path:t,isTemplateMatch:!1}}for(let e of S(r)){let t=i.filter(t=>C(t,[e]));if(t.length===1)return{path:t[0],isTemplateMatch:!0};if(t.length>1)return}}function T(e,t){return w(e,t)?.path??p(t)}function E(e,t){let n=S(h(e,t)),r=new Set(n.flat());return u(e).map(e=>({path:e,isMatch:C(e,n),sharedSegments:g(e.toLowerCase()).filter(e=>r.has(e)).length})).sort((e,t)=>Number(t.isMatch)-Number(e.isMatch)||t.sharedSegments-e.sharedSegments).map(({path:e})=>e)}const D=15;function O(e){let t=e.slice(0,15),n=e.length-t.length;return n>0?`${t.join(`, `)} (+${n} more)`:t.join(`, `)}function k(e){let n=n=>e===`code`?`site.${t(n,e)}`:n;return{endpoints:n(`get-endpoints`),search:n(`search`),listApis:n(`list-apis`),listPages:n(`list-pages`)}}function A(e,t,n,r){let i=E(e,n);if(i.length===0)return`Endpoint not found`;let{endpoints:a,search:o}=k(r);return`No path "${n}" in "${t}". Documented paths: ${O(i)}. Call ${a} for the full list, or ${o} with a keyword from the request.`}function j(e,t,n,r){let i=l(e,n);return i.length===0?`Endpoint not found`:`"${n}" in "${t}" documents no ${r.toUpperCase()}. Available methods: ${O(i)}.`}export{D as MAX_LISTED_CANDIDATES,f as absolutePath,j as describeMethodMiss,A as describePathMiss,w as findDocumentedPath,O as formatCandidates,a as isDefinitionHidden,i as isEndpointHidden,T as matchDocumentedPath,k as recoveryToolNames,c as visibleEndpoints,l as visibleMethodsAt,s as visibleOperations,u as visiblePaths,d as withVisibleOperationsOnly,o as withoutXMcp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{GET_ENDPOINTS_SCHEMA as e,GET_ENDPOINT_INFO_SCHEMA as t,GET_FULL_API_DESCRIPTION_SCHEMA as n,GET_SECURITY_SCHEMES_SCHEMA as r,LIST_APIS_CALLABLE_SCHEMA as i,LIST_APIS_SCHEMA as a,getEndpointInfoToolSchema as o,getEndpointsToolSchema as s,getFullApiDescriptionToolSchema as c,getSecuritySchemesToolSchema as l}from"./schemas.js";import{apiTitleKey as u,countApiTitles as d,orderSharedTitles as f}from"./api-titles.js";import{describeMethodMiss as p,describePathMiss as m,matchDocumentedPath as h,visibleEndpoints as g,visibleOperations as _,withVisibleOperationsOnly as v,withoutXMcp as y}from"./openapi-document.js";import{filterApisByName as b,loadApiCatalog as x,resolveApi as S}from"./openapi-catalog.js";import{callableApis as C}from"../gateway/eligibility.js";import{inlineOperation as w,resolveOperation as T}from"./openapi-refs.js";import{replaceServerVariables as E}from"@redocly/api-docs/server";const D=8388608,O={apiName:`name`,api:`name`};function k(e){return e.map(e=>({...e,url:E(e)}))}async function A(e){return new Set((await C(e)).map(e=>e.entityKey))}const j=[{schema:a,schemaFor:async e=>(await A(e)).size>0?i:a,async execute(e,t){let n=e??{},{filter:r}=n,i=n.page??1,a=n.limit??300,o=await A(t),s=f(await x(t)),c=d(s),l=r?b(s,r):s,p=(i-1)*a;return{items:l.slice(p,p+a).map(({entityKey:e,relativePath:t,name:n,description:r,version:i,servers:a})=>({filePath:t,name:n,description:r,version:i,servers:k(a),ambiguousTitle:(c.get(u(n))??0)>1||void 0,callable:o.size>0?o.has(e):void 0})),limit:a,total:l.length,page:i,totalPages:Math.ceil(l.length/a)}}},{schema:e,schemaFor:e=>s(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,servers:k(n.servers),endpoints:g(n.definition)}}},{schema:t,schemaFor:e=>o(e.mcpMode),inputAliases:O,async execute(e,t){let n=e??{},{path:r,method:i}=n;if(!r||!i)throw Error(`Both "path" and "method" are required (e.g. path: "/tickets", method: "GET").`);let{api:a,otherMatches:o}=await S(n,t),{definition:s}=a,c=o?` Other definitions share this title: ${o.map(e=>`"${e.filePath}"`).join(`, `)}. Pass "filePath" to check them.`:``,l=h(s,r),u=s.paths?.[l],d=_(u);if(!u||d.length===0)throw Error(m(s,a.name,l,t.mcpMode)+c);let f=d.find(([e])=>e.toLowerCase()===i.toLowerCase())?.[1];if(!f)throw Error(p(s,a.name,l,i)+c);let g={operation:y(f),pathParams:u.parameters??[],definition:s},{operation:v,components:b}=(t.mcpMode===`code`?w(g,1048576):void 0)??T(g),x={api:a.name,version:a.version,filePath:a.relativePath,otherMatches:o,servers:k(a.servers),endpoint:{path:l,method:i.toUpperCase(),...v},globalSecurity:s.security??[],securitySchemes:s.components?.securitySchemes??{},components:b},C=JSON.stringify(x,null,2).length;if(C>D)throw Error(`${i.toUpperCase()} ${l} is ${C} bytes, over the ${D} byte limit.`);return x}},{schema:r,schemaFor:e=>l(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,securitySchemes:n.definition.components?.securitySchemes??{},security:n.definition.security??[]}}},{schema:n,schemaFor:e=>c(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,definition:v(n.definition)}}}];export{j as openApiTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import{readIgnoredRouteSlugs as e}from"../../ignored-routes.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{
|
|
2
|
-
`)}}},S={schema:
|
|
1
|
+
import{readIgnoredRouteSlugs as e}from"../../ignored-routes.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{MAX_PAGE_LINES as n}from"./pages-constants.js";import{GET_PAGE_SCHEMA as r,GREP_PAGES_SCHEMA as i,LIST_PAGES_SCHEMA as a,grepPagesToolSchema as o,listPagesToolSchema as s}from"./schemas.js";import{recoveryToolNames as c}from"./openapi-document.js";import{collectNodeLinks as l,countPages as u,findSection as d,flattenSections as f,loadPageNavigation as p,loadVisiblePages as m,toPageSlug as h,toPublicUrl as g,toSectionId as _}from"./pages-navigation.js";const v=/^(#{1,3}) +(\S.*)$/,y=/^\s*(```|~~~)/,b={schema:a,schemaFor:e=>s(e.mcpMode),async execute(e,n){let{section:r}=e??{},{sections:i}=await p(n),a=t(n.request);if(!r)return{sections:i.map(e=>({id:e.id,title:e.title,items:w(e.id,e.nodes,a)}))};let o=d(i,r,a);if(!o){let e=f(i).slice(0,50).map(({id:e})=>e);throw Error(`No section "${r}". Pass one of these section ids: ${e.join(`; `)}.`)}return{section:{id:o.id,title:o.title},items:w(o.id,o.nodes,a)}}},x={schema:r,async execute(e,r){let{url:i,startLine:a,lines:o}=e??{};if(typeof i!=`string`||i.trim()===``)throw Error(`The "url" parameter is required: a page URL or path.`);let s=t(r.request),l=h(i,s),u=l===null?null:await C(l,r);if(l===null||u===null)throw Error(`No page you can read is at "${i}": it does not exist, or your access does not include it. Do not describe it from other pages. Call ${c(r.mcpMode).listPages} to see the pages you can read.`);let d=D(u.text),f=Math.max(1,Math.floor(a??1));if(f>d.length)throw Error(`Line ${f} is past the end of "${u.title??l}", which has ${d.length} lines.`);let p=T(o,200,n),m=Math.min(d.length,f+p-1);return{url:g(l,s),title:u.title??l,totalLines:d.length,startLine:f,endLine:m,...m<d.length?{nextStartLine:m+1}:{},outline:O(d),content:d.slice(f-1,m).join(`
|
|
2
|
+
`)}}},S={schema:i,schemaFor:e=>o(e.mcpMode),async execute(e,n){let{query:r,section:i,maxMatches:a}=e??{};if(typeof r!=`string`||r===``)throw Error(`The "query" parameter is required: a text to find.`);let o=t(n.request),s,u;if(i){let{sections:e,pages:t}=await p(n),r=d(e,i,o);if(!r)throw Error(`No section "${i}". Call ${c(n.mcpMode).listPages} to see the sections.`);let a=new Set(l(r.nodes));r.link&&a.add(r.link),s=t.filter(e=>a.has(e.slug)),u=r.title}else s=(await m(n)).pages;let f=T(a,20,100),h=r.toLowerCase(),_=s.length,v=[];for(let e of s){let t=(await n.pageMarkdown.readPage(e.slug))?.text??``;if(t.toLowerCase().includes(h))for(let[n,r]of D(t).entries()){let t=r.toLowerCase().indexOf(h);if(t!==-1){if(v.length===f)return{matches:v,searchedPages:_,truncated:!0};v.push({url:g(e.slug,o),title:e.title,line:n+1,text:E(r,t)})}}}return v.length>0?{matches:v,searchedPages:_,truncated:!1}:{matches:v,searchedPages:_,truncated:!1,note:`No page you can read ${u?`in "${u}" contains "${r}". All ${_} pages there were searched.`:`contains "${r}". All ${_} pages were searched. API references are not searched: use ${c(n.mcpMode).listApis} for them.`}`}}};async function C(t,n){return(await e(n.entities)).has(t)?null:n.pageMarkdown.readPage(t)}function w(e,t,n){return t.map(t=>t.type===`page`?{type:`page`,title:t.label,url:g(t.link??``,n)}:{type:`section`,id:_(e,t.label),title:t.label,...t.link?{url:g(t.link,n)}:{},pageCount:u(t.items)})}function T(e,t,n){return Math.min(Math.max(1,Math.floor(e??t)),n)}function E(e,t){let n=Math.max(0,Math.min(t-80,e.length-200));return e.slice(n,n+200).trim()}function D(e){return(e.endsWith(`
|
|
3
3
|
`)?e.slice(0,-1):e).split(`
|
|
4
4
|
`)}function O(e){let t=[],n=!1;return e.forEach((e,r)=>{if(y.test(e)){n=!n;return}let i=n?null:v.exec(e);i&&t.push({line:r+1,level:i[1].length,heading:i[2].trim()})}),t}const k=[b,x,S];export{k as pageTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SUBMIT_FEEDBACK_TOOL_NAME as e}from"../../constants.js";import{toolNameForMode as t}from"../codemode/tool-declarations.js";import{GRAPHQL_LIST_SCOPES as n,GRAPHQL_TYPE_KINDS as r}from"./graphql-constants.js";import{OPERATION_METHODS as i}from"./openapi-document.js";import{MAX_PAGE_LINES as a}from"./pages-constants.js";const o={type:`string`,nullable:!0},s={limit:{type:`number`},total:{type:`number`},page:{type:`number`},totalPages:{type:`number`}},c={codemodeType:`OpenApiServer[]`},l={codemodeType:`OpenApiSecurityRequirement[]`},u={codemodeType:`Record<string, OpenApiSecurityScheme>`},d={codemodeType:`OpenApiDocument`},f={codemodeType:`OpenApiOperation & { path: string; method: string }`},p={codemodeType:`OpenApiComponents`,description:"Components the endpoint references. A `$ref` in `endpoint` resolves against the root of the result."},m={filePath:{type:`string`,description:`API definition file path`},otherMatches:{type:`array`,description:"Other API definitions the lookup also matched. Present only when several matched; pass `filePath` to pick another one",items:{type:`object`,required:[`filePath`],properties:{version:{type:`string`},filePath:{type:`string`}}}}},h="When several definitions match the name, the highest version or the shortest file path is used and the rest are listed in `otherMatches`; tell the user which version or file the answer is based on.",g={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!1};function _(e,t){let n={query:{type:`string`,description:`What to find, as a few words or a short question.`,minLength:1}};return e.length>0&&(n.product={type:`string`,description:`Optional product name to filter search results by specific product.`,enum:[...e,null],nullable:!0}),t.length>0&&(n.locale={type:`string`,description:`Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the site's default locale.`,enum:[...t,null],nullable:!0}),{name:`search`,title:`Search documentation`,description:`Search the documentation. Returns Markdown text: one section per matching page, with its title and URL as a link.`,summary:`Search the documentation.`,schema:{type:`object`,required:[`query`],additionalProperties:!1,properties:n},annotations:g,outputSchema:{type:`string`}}}const v=_([],[]),y={name:`whoami`,title:`Who am I`,description:`Get information about the currently authenticated user`,summary:`Get the signed-in user.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:g,outputSchema:{type:`object`,required:[`authenticated`],properties:{authenticated:{type:`boolean`},email:{type:`string`},name:{type:`string`},subject:{type:`string`},clientId:{type:`string`},scope:{type:`string`},issuedAt:{type:`string`},expiresAt:{type:`string`}}}},b={name:e,title:`Submit feedback`,description:`Report a documentation page that is wrong or incomplete. Use it when the user reports a problem with a page on this site, or agrees to report a problem that you found. Do not use it for product bugs or support questions.`,schema:{type:`object`,required:[`path`,`summary`],additionalProperties:!1,properties:{path:{type:`string`,description:`Path or URL of the documentation page the feedback is about (e.g. /guides/auth)`,minLength:1,maxLength:1e3},summary:{type:`string`,description:`One sentence that names what is wrong with the page`,minLength:1,maxLength:500},details:{type:`string`,description:`Expected versus actual behavior, missing steps, or the snippet that failed`,maxLength:4e3,nullable:!0},targetFeature:{type:`string`,description:`The API or feature the page documents`,maxLength:500,nullable:!0}}},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},outputSchema:{type:`object`,required:[`status`,`page`,`message`],properties:{status:{type:`string`},page:{type:`string`},message:{type:`string`}}}},x={type:`object`,additionalProperties:!1,required:[],properties:{filter:{type:`string`,description:`Matches part of an API name, or of a description when no name matches`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of APIs per page. Default is 300`,minimum:1,default:300,nullable:!0}}};function S(e){return{type:`string`,description:`API definition file path, as returned by \`${t(`list-apis`,e)}\``,nullable:!0}}function C(e){return{type:`object`,required:[],additionalProperties:!1,properties:{name:{type:`string`,description:"API name, or a unique part of it. Required when the project documents more than one API, unless `filePath` is given.",minLength:1,nullable:!0},version:{type:`string`,description:`API version. When omitted and several versions exist, the highest one is used`,nullable:!0},filePath:S(e)}}}function w(e){let{name:t,version:n,filePath:r}=C(e).properties;return{type:`object`,required:[`path`,`method`],additionalProperties:!1,properties:{name:t,path:{type:`string`,description:`Endpoint path (e.g. /api/v1/users)`,minLength:1},method:{type:`string`,description:`HTTP method (GET, POST, PUT, DELETE, etc.)`,enum:[...i.map(e=>e.toUpperCase()),...i],minLength:1},version:n,filePath:r}}}function T(e){let t={name:{type:`string`},description:{type:`string`},version:{type:`string`},servers:c,filePath:{type:`string`,description:`API definition file path`},ambiguousTitle:{type:`boolean`,description:"true = another API shares this title; a lookup picks the highest version, or the shortest file path at the same version, and lists the rest in `otherMatches`. Pass `filePath` to pick another one"}};return e&&(t.callable={type:`boolean`,description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}),{name:`list-apis`,title:`List APIs`,description:`Lists the APIs documented on this site`,summary:`List the available APIs.`,schema:x,annotations:g,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`,`description`,`version`,`servers`,`filePath`],properties:t}},...s}}}}const E=T(!1),D=T(!0);function O(e){return{name:`get-endpoints`,title:`Get endpoints`,description:`Get all endpoints for a specific API. ${h}`,summary:`Get all endpoints for an API.`,schema:C(e),annotations:g,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoints`],properties:{api:{type:`string`},version:{type:`string`},...m,servers:c,endpoints:{type:`array`,items:{type:`object`,required:[`path`,`method`],properties:{path:{type:`string`},method:{type:`string`},summary:o,description:o,security:l}}}}}}}const k=O(`tools`);function A(e){return{name:`get-endpoint-info`,title:`Get endpoint info`,description:`Get comprehensive information about specific endpoint including parameters, security, and examples. A \`$ref\` in \`endpoint\` points into the \`components\` key at the root of the result: read \`#/components/<section>/<name>\` there. ${h}`,summary:`Get the details of an endpoint.`,schema:w(e),annotations:g,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoint`,`globalSecurity`,`securitySchemes`],properties:{api:{type:`string`},version:{type:`string`},...m,servers:c,endpoint:f,globalSecurity:l,securitySchemes:u,components:p}}}}const j=A(`tools`);function M(e){return{name:`get-security-schemes`,title:`Get security schemes`,description:`Get the security schemes for a specific API. ${h}`,summary:`Get the security schemes for an API.`,schema:C(e),annotations:g,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`securitySchemes`,`security`],properties:{api:{type:`string`},version:{type:`string`},...m,securitySchemes:u,security:l}}}}const N=M(`tools`);function P(e){return{name:`get-full-api-description`,title:`Get full API description`,description:`Get the complete OpenAPI description. ${h}`,summary:`Get the complete OpenAPI description.`,schema:C(e),annotations:g,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`definition`],properties:{api:{type:`string`},version:{type:`string`},...m,definition:d}}}}const F=P(`tools`),I={type:`object`,required:[],additionalProperties:!1,properties:{filter:{type:`string`,description:`GraphQL schema name (or part of it)`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},L={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},kind:{type:`string`,description:`Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).`,enum:[...r,null],nullable:!0},scope:{type:`string`,description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions — combine with `filter` to search nested fields anywhere in the schema.',enum:[...n,null],nullable:!0},filter:{type:`string`,description:`Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")`,minLength:1,nullable:!0},referencesType:{type:`string`,description:`Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it — e.g. referencesType "Book" surfaces a search query returning a union that includes Book.`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},R={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},type:{type:`string`,description:`Name of the type, operation, or directive`,minLength:1,nullable:!0},includeReferencedTypes:{type:`boolean`,description:`Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.`,default:!1,nullable:!0}}},z={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1}}},B={name:`list-graphql-apis`,title:`List GraphQL APIs`,description:`Lists available GraphQL schemas with their context and purpose`,summary:`List the available GraphQL schemas.`,schema:I,annotations:g,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`],properties:{name:{type:`string`},description:o}}},...s}}},V={name:`get-graphql-type-list`,title:`Get GraphQL type list`,description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, …) and carries a one-line description; operations also include their return type and argument signature — use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields — not just type names — set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',summary:`List the operations and types in a GraphQL schema.`,schema:L,annotations:g,outputSchema:{type:`object`,required:[`name`,`items`,`limit`,`total`,`page`,`totalPages`],properties:{name:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`kind`,`name`],properties:{kind:{type:`string`,enum:[...r]},name:{type:`string`},description:o,type:{type:`string`},args:{type:`string`},directives:{type:`string`}}}},...s}}};function H(e){return{name:`get-graphql-type`,title:`Get GraphQL type`,description:`Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type's field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively — the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call ${t(`get-graphql-type-list`,e)} with \`referencesType\`.`,summary:`Get the SDL of one GraphQL type or operation.`,schema:R,annotations:g,outputSchema:{type:`string`}}}const U=H(`tools`);function W(e){return{name:`get-graphql-schema`,title:`Get GraphQL schema`,description:`Get the complete GraphQL schema as SDL — the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer ${t(`get-graphql-type-list`,e)} (filter/paginate) plus targeted ${t(`get-graphql-type`,e)} calls, and reach for this only for small schemas or when you truly need the full SDL.`,summary:`Get the complete GraphQL schema.`,schema:z,annotations:g,outputSchema:{type:`string`}}}const G=W(`tools`);function K(e){return`Section id from ${t(`list-pages`,e)} (for example "products/ledger > Integration"), a section title, or a section URL`}function q(e){return{type:`object`,required:[`type`,`title`],properties:{type:{type:`string`,enum:[`page`,`section`]},id:{type:`string`,description:`Section id to pass to ${t(`list-pages`,e)} or ${t(`grep-pages`,e)}`},title:{type:`string`},url:{type:`string`},pageCount:{type:`number`,description:`Pages inside the section`}}}}function J(e){let t=q(e);return{name:`list-pages`,title:`List pages`,description:`Lists the docs navigation, one level per call`,summary:`List the docs navigation, one level per call.`,schema:{type:`object`,additionalProperties:!1,required:[],properties:{section:{type:`string`,nullable:!0,description:`${K(e)}. Omit it to list the top level`}}},annotations:g,outputSchema:{type:`object`,properties:{sections:{type:`array`,description:`Top level, when no section is given`,items:{type:`object`,required:[`id`,`title`,`items`],properties:{id:{type:`string`},title:{type:`string`},items:{type:`array`,items:t}}}},section:{type:`object`,properties:{id:{type:`string`},title:{type:`string`}}},items:{type:`array`,items:t}}}}}const Y=J(`tools`),X={name:`get-page`,title:`Get page`,description:`Reads a docs page as Markdown, in line windows`,summary:`Read a docs page as Markdown, in line windows.`,schema:{type:`object`,additionalProperties:!1,required:[`url`],properties:{url:{type:`string`,minLength:1,description:`Page URL or path, for example "/guides/auth"`},startLine:{type:`integer`,nullable:!0,minimum:1,description:`First line to return (default 1)`},lines:{type:`integer`,nullable:!0,minimum:1,maximum:a,description:`Number of lines to return (default 200)`}}},annotations:g,outputSchema:{type:`object`,required:[`url`,`title`,`totalLines`,`startLine`,`endLine`,`outline`,`content`],properties:{url:{type:`string`},title:{type:`string`},totalLines:{type:`number`},startLine:{type:`number`},endLine:{type:`number`},nextStartLine:{type:`number`,description:`Pass as startLine to read on; absent at the end`},outline:{type:`array`,description:`Headings (levels 1-3) with their line numbers`,items:{type:`object`,required:[`line`,`level`,`heading`],properties:{line:{type:`number`},level:{type:`number`},heading:{type:`string`}}}},content:{type:`string`}}}};function Z(e){return{name:`grep-pages`,title:`Grep pages`,description:`Finds the docs lines that contain a text`,summary:`Find the docs lines that contain a text.`,schema:{type:`object`,additionalProperties:!1,required:[`query`],properties:{query:{type:`string`,minLength:1,description:`Text to find, case-insensitive. Not a regular expression`},section:{type:`string`,nullable:!0,description:`${K(e)}. Omit it to search every page`},maxMatches:{type:`integer`,nullable:!0,minimum:1,maximum:100,description:`Maximum matching lines to return (default 20)`}}},annotations:g,outputSchema:{type:`object`,required:[`matches`,`searchedPages`,`truncated`],properties:{matches:{type:`array`,items:{type:`object`,required:[`url`,`title`,`line`,`text`],properties:{url:{type:`string`},title:{type:`string`},line:{type:`number`},text:{type:`string`}}}},searchedPages:{type:`number`,description:`Pages searched: every page you can read, or every page in the section`},truncated:{type:`boolean`,description:`true = more matches exist; narrow the query or the section`},note:{type:`string`,description:`Present when nothing matches: the docs you can read do not contain the text`}}}}}const Q=Z(`tools`);export{k as GET_ENDPOINTS_SCHEMA,j as GET_ENDPOINT_INFO_SCHEMA,F as GET_FULL_API_DESCRIPTION_SCHEMA,G as GET_GRAPHQL_SCHEMA_SCHEMA,V as GET_GRAPHQL_TYPE_LIST_SCHEMA,U as GET_GRAPHQL_TYPE_SCHEMA,X as GET_PAGE_SCHEMA,N as GET_SECURITY_SCHEMES_SCHEMA,Q as GREP_PAGES_SCHEMA,D as LIST_APIS_CALLABLE_SCHEMA,E as LIST_APIS_SCHEMA,B as LIST_GRAPHQL_APIS_SCHEMA,Y as LIST_PAGES_SCHEMA,g as READ_ONLY_ANNOTATIONS,v as SEARCH_SCHEMA,b as SUBMIT_FEEDBACK_SCHEMA,y as WHOAMI_SCHEMA,A as getEndpointInfoToolSchema,O as getEndpointsToolSchema,P as getFullApiDescriptionToolSchema,W as getGraphqlSchemaToolSchema,H as getGraphqlTypeToolSchema,M as getSecuritySchemesToolSchema,Z as grepPagesToolSchema,J as listPagesToolSchema,_ as searchSchema};
|
|
1
|
+
import{READ_ONLY_ANNOTATIONS as e,SUBMIT_FEEDBACK_TOOL_NAME as t}from"../../constants.js";import{OPERATION_METHODS as n}from"../../../../../../shared/constants/openapi-operation-methods.js";import{toolNameForMode as r}from"../codemode/tool-declarations.js";import{GRAPHQL_LIST_SCOPES as i,GRAPHQL_TYPE_KINDS as a}from"./graphql-constants.js";import{MAX_PAGE_LINES as o}from"./pages-constants.js";const s={type:`string`,nullable:!0},c={limit:{type:`number`},total:{type:`number`},page:{type:`number`},totalPages:{type:`number`}},l={codemodeType:`OpenApiServer[]`},u={codemodeType:`OpenApiSecurityRequirement[]`},d={codemodeType:`Record<string, OpenApiSecurityScheme>`},f={codemodeType:`OpenApiDocument`},p={codemodeType:`OpenApiOperation & { path: string; method: string }`},m={codemodeType:`OpenApiComponents`,description:"Components the endpoint references. A `$ref` in `endpoint` resolves against the root of the result."},h={filePath:{type:`string`,description:`API definition file path`},otherMatches:{type:`array`,description:"Other API definitions the lookup also matched. Present only when several matched; pass `filePath` to pick another one",items:{type:`object`,required:[`filePath`],properties:{version:{type:`string`},filePath:{type:`string`}}}}},g="When several definitions match the name, the highest version or the shortest file path is used and the rest are listed in `otherMatches`; tell the user which version or file the answer is based on.";function _(t,n){let r={query:{type:`string`,description:`What to find, as a few words or a short question.`,minLength:1}};return t.length>0&&(r.product={type:`string`,description:`Optional product name to filter search results by specific product.`,enum:[...t,null],nullable:!0}),n.length>0&&(r.locale={type:`string`,description:`Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the site's default locale.`,enum:[...n,null],nullable:!0}),{name:`search`,title:`Search documentation`,description:`Search the documentation. Returns Markdown text: one section per matching page, with its title and URL as a link.`,summary:`Search the documentation.`,schema:{type:`object`,required:[`query`],additionalProperties:!1,properties:r},annotations:e,outputSchema:{type:`string`}}}const v=_([],[]),y={name:`whoami`,title:`Who am I`,description:`Get information about the currently authenticated user`,summary:`Get the signed-in user.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:e,outputSchema:{type:`object`,required:[`authenticated`],properties:{authenticated:{type:`boolean`},email:{type:`string`},name:{type:`string`},subject:{type:`string`},clientId:{type:`string`},scope:{type:`string`},issuedAt:{type:`string`},expiresAt:{type:`string`}}}},b={name:t,title:`Submit feedback`,description:`Report a documentation page that is wrong or incomplete. Use it when the user reports a problem with a page on this site, or agrees to report a problem that you found. Do not use it for product bugs or support questions.`,schema:{type:`object`,required:[`path`,`summary`],additionalProperties:!1,properties:{path:{type:`string`,description:`Path or URL of the documentation page the feedback is about (e.g. /guides/auth)`,minLength:1,maxLength:1e3},summary:{type:`string`,description:`One sentence that names what is wrong with the page`,minLength:1,maxLength:500},details:{type:`string`,description:`Expected versus actual behavior, missing steps, or the snippet that failed`,maxLength:4e3,nullable:!0},targetFeature:{type:`string`,description:`The API or feature the page documents`,maxLength:500,nullable:!0}}},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},outputSchema:{type:`object`,required:[`status`,`page`,`message`],properties:{status:{type:`string`},page:{type:`string`},message:{type:`string`}}}},x={type:`object`,additionalProperties:!1,required:[],properties:{filter:{type:`string`,description:`Matches part of an API name, or of a description when no name matches`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of APIs per page. Default is 300`,minimum:1,default:300,nullable:!0}}};function S(e){return{type:`string`,description:`API definition file path, as returned by \`${r(`list-apis`,e)}\``,nullable:!0}}function C(e){return{type:`object`,required:[],additionalProperties:!1,properties:{name:{type:`string`,description:"API name, or a unique part of it. Required when the project documents more than one API, unless `filePath` is given.",minLength:1,nullable:!0},version:{type:`string`,description:`API version. When omitted and several versions exist, the highest one is used`,nullable:!0},filePath:S(e)}}}function w(e){let{name:t,version:r,filePath:i}=C(e).properties;return{type:`object`,required:[`path`,`method`],additionalProperties:!1,properties:{name:t,path:{type:`string`,description:`Endpoint path (e.g. /api/v1/users)`,minLength:1},method:{type:`string`,description:`HTTP method (GET, POST, PUT, DELETE, etc.)`,enum:[...n.map(e=>e.toUpperCase()),...n],minLength:1},version:r,filePath:i}}}function T(t){let n={name:{type:`string`},description:{type:`string`},version:{type:`string`},servers:l,filePath:{type:`string`,description:`API definition file path`},ambiguousTitle:{type:`boolean`,description:"true = another API shares this title; a lookup picks the highest version, or the shortest file path at the same version, and lists the rest in `otherMatches`. Pass `filePath` to pick another one"}};return t&&(n.callable={type:`boolean`,description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}),{name:`list-apis`,title:`List APIs`,description:`Lists the APIs documented on this site`,summary:`List the available APIs.`,schema:x,annotations:e,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`,`description`,`version`,`servers`,`filePath`],properties:n}},...c}}}}const E=T(!1),D=T(!0);function O(t){return{name:`get-endpoints`,title:`Get endpoints`,description:`Get all endpoints for a specific API. ${g}`,summary:`Get all endpoints for an API.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoints`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoints:{type:`array`,items:{type:`object`,required:[`path`,`method`],properties:{path:{type:`string`},method:{type:`string`},summary:s,description:s,security:u}}}}}}}const k=O(`tools`);function A(t){return{name:`get-endpoint-info`,title:`Get endpoint info`,description:`Get comprehensive information about specific endpoint including parameters, security, and examples. A \`$ref\` in \`endpoint\` points into the \`components\` key at the root of the result: read \`#/components/<section>/<name>\` there. ${g}`,summary:`Get the details of an endpoint.`,schema:w(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoint`,`globalSecurity`,`securitySchemes`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoint:p,globalSecurity:u,securitySchemes:d,components:m}}}}const j=A(`tools`);function M(t){return{name:`get-security-schemes`,title:`Get security schemes`,description:`Get the security schemes for a specific API. ${g}`,summary:`Get the security schemes for an API.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`securitySchemes`,`security`],properties:{api:{type:`string`},version:{type:`string`},...h,securitySchemes:d,security:u}}}}const N=M(`tools`);function P(t){return{name:`get-full-api-description`,title:`Get full API description`,description:`Get the complete OpenAPI description. ${g}`,summary:`Get the complete OpenAPI description.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`definition`],properties:{api:{type:`string`},version:{type:`string`},...h,definition:f}}}}const F=P(`tools`),I={type:`object`,required:[],additionalProperties:!1,properties:{filter:{type:`string`,description:`GraphQL schema name (or part of it)`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},L={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},kind:{type:`string`,description:`Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).`,enum:[...a,null],nullable:!0},scope:{type:`string`,description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions — combine with `filter` to search nested fields anywhere in the schema.',enum:[...i,null],nullable:!0},filter:{type:`string`,description:`Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")`,minLength:1,nullable:!0},referencesType:{type:`string`,description:`Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it — e.g. referencesType "Book" surfaces a search query returning a union that includes Book.`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},R={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},type:{type:`string`,description:`Name of the type, operation, or directive`,minLength:1,nullable:!0},includeReferencedTypes:{type:`boolean`,description:`Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.`,default:!1,nullable:!0}}},z={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1}}},B={name:`list-graphql-apis`,title:`List GraphQL APIs`,description:`Lists available GraphQL schemas with their context and purpose`,summary:`List the available GraphQL schemas.`,schema:I,annotations:e,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`],properties:{name:{type:`string`},description:s}}},...c}}},V={name:`get-graphql-type-list`,title:`Get GraphQL type list`,description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, …) and carries a one-line description; operations also include their return type and argument signature — use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields — not just type names — set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',summary:`List the operations and types in a GraphQL schema.`,schema:L,annotations:e,outputSchema:{type:`object`,required:[`name`,`items`,`limit`,`total`,`page`,`totalPages`],properties:{name:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`kind`,`name`],properties:{kind:{type:`string`,enum:[...a]},name:{type:`string`},description:s,type:{type:`string`},args:{type:`string`},directives:{type:`string`}}}},...c}}};function H(t){return{name:`get-graphql-type`,title:`Get GraphQL type`,description:`Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type's field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively — the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call ${r(`get-graphql-type-list`,t)} with \`referencesType\`.`,summary:`Get the SDL of one GraphQL type or operation.`,schema:R,annotations:e,outputSchema:{type:`string`}}}const U=H(`tools`);function W(t){return{name:`get-graphql-schema`,title:`Get GraphQL schema`,description:`Get the complete GraphQL schema as SDL — the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer ${r(`get-graphql-type-list`,t)} (filter/paginate) plus targeted ${r(`get-graphql-type`,t)} calls, and reach for this only for small schemas or when you truly need the full SDL.`,summary:`Get the complete GraphQL schema.`,schema:z,annotations:e,outputSchema:{type:`string`}}}const G=W(`tools`);function K(e){return`Section id from ${r(`list-pages`,e)} (for example "products/ledger > Integration"), a section title, or a section URL`}function q(e){return{type:`object`,required:[`type`,`title`],properties:{type:{type:`string`,enum:[`page`,`section`]},id:{type:`string`,description:`Section id to pass to ${r(`list-pages`,e)} or ${r(`grep-pages`,e)}`},title:{type:`string`},url:{type:`string`},pageCount:{type:`number`,description:`Pages inside the section`}}}}function J(t){let n=q(t);return{name:`list-pages`,title:`List pages`,description:`Lists the docs navigation, one level per call`,summary:`List the docs navigation, one level per call.`,schema:{type:`object`,additionalProperties:!1,required:[],properties:{section:{type:`string`,nullable:!0,description:`${K(t)}. Omit it to list the top level`}}},annotations:e,outputSchema:{type:`object`,properties:{sections:{type:`array`,description:`Top level, when no section is given`,items:{type:`object`,required:[`id`,`title`,`items`],properties:{id:{type:`string`},title:{type:`string`},items:{type:`array`,items:n}}}},section:{type:`object`,properties:{id:{type:`string`},title:{type:`string`}}},items:{type:`array`,items:n}}}}}const Y=J(`tools`),X={name:`get-page`,title:`Get page`,description:`Reads a docs page as Markdown, in line windows`,summary:`Read a docs page as Markdown, in line windows.`,schema:{type:`object`,additionalProperties:!1,required:[`url`],properties:{url:{type:`string`,minLength:1,description:`Page URL or path, for example "/guides/auth"`},startLine:{type:`integer`,nullable:!0,minimum:1,description:`First line to return (default 1)`},lines:{type:`integer`,nullable:!0,minimum:1,maximum:o,description:`Number of lines to return (default 200)`}}},annotations:e,outputSchema:{type:`object`,required:[`url`,`title`,`totalLines`,`startLine`,`endLine`,`outline`,`content`],properties:{url:{type:`string`},title:{type:`string`},totalLines:{type:`number`},startLine:{type:`number`},endLine:{type:`number`},nextStartLine:{type:`number`,description:`Pass as startLine to read on; absent at the end`},outline:{type:`array`,description:`Headings (levels 1-3) with their line numbers`,items:{type:`object`,required:[`line`,`level`,`heading`],properties:{line:{type:`number`},level:{type:`number`},heading:{type:`string`}}}},content:{type:`string`}}}};function Z(t){return{name:`grep-pages`,title:`Grep pages`,description:`Finds the docs lines that contain a text`,summary:`Find the docs lines that contain a text.`,schema:{type:`object`,additionalProperties:!1,required:[`query`],properties:{query:{type:`string`,minLength:1,description:`Text to find, case-insensitive. Not a regular expression`},section:{type:`string`,nullable:!0,description:`${K(t)}. Omit it to search every page`},maxMatches:{type:`integer`,nullable:!0,minimum:1,maximum:100,description:`Maximum matching lines to return (default 20)`}}},annotations:e,outputSchema:{type:`object`,required:[`matches`,`searchedPages`,`truncated`],properties:{matches:{type:`array`,items:{type:`object`,required:[`url`,`title`,`line`,`text`],properties:{url:{type:`string`},title:{type:`string`},line:{type:`number`},text:{type:`string`}}}},searchedPages:{type:`number`,description:`Pages searched: every page you can read, or every page in the section`},truncated:{type:`boolean`,description:`true = more matches exist; narrow the query or the section`},note:{type:`string`,description:`Present when nothing matches: the docs you can read do not contain the text`}}}}}const Q=Z(`tools`);export{k as GET_ENDPOINTS_SCHEMA,j as GET_ENDPOINT_INFO_SCHEMA,F as GET_FULL_API_DESCRIPTION_SCHEMA,G as GET_GRAPHQL_SCHEMA_SCHEMA,V as GET_GRAPHQL_TYPE_LIST_SCHEMA,U as GET_GRAPHQL_TYPE_SCHEMA,X as GET_PAGE_SCHEMA,N as GET_SECURITY_SCHEMES_SCHEMA,Q as GREP_PAGES_SCHEMA,D as LIST_APIS_CALLABLE_SCHEMA,E as LIST_APIS_SCHEMA,B as LIST_GRAPHQL_APIS_SCHEMA,Y as LIST_PAGES_SCHEMA,v as SEARCH_SCHEMA,b as SUBMIT_FEEDBACK_SCHEMA,y as WHOAMI_SCHEMA,A as getEndpointInfoToolSchema,O as getEndpointsToolSchema,P as getFullApiDescriptionToolSchema,W as getGraphqlSchemaToolSchema,H as getGraphqlTypeToolSchema,M as getSecuritySchemesToolSchema,Z as grepPagesToolSchema,J as listPagesToolSchema,_ as searchSchema};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
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(`
|
|
2
2
|
|
|
3
|
-
`).trim()}const f=[{schema:c,schemaFor:
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPlanFeatureGranted as e}from"../../../../../shared/plan-gates.js";import{
|
|
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{parseContentVersion as i}from"../../../utils/version-path.js";import{toPublicVersionedSlug as a}from"../../../../../shared/constants/versions.js";import{stripPathPrefix as o}from"../../../../../shared/path-prefix.js";import{notFoundResponse as s}from"../../../../../server/plugin-context.js";import{MOCK_SERVER_HANDLER_ID as c,withMockServerEvent as l}from"../../../../../server/telemetry/mock-server-events.js";const u={"Cache-Control":`no-store`},d=/* @__PURE__ */ new Map;function f(e,n){let r=n.metadata?.mockServer;return{...e,...t(r)?r:{}}}function p(e,t){let{specType:n,routeSlug:i}=e.metadata??{};return n!==`openapi`||typeof i!=`string`||f(t,e).off===!0?null:r(i)}function m(e,t,n=void 0){let r=null,i=-1;for(let a of e){let e=p(a,n);e===null||e.length<=i||h(e,t)&&(r={api:a,path:t.slice(e.length)||`/`},i=e.length)}return r}function h(e,t){return t===e||t.startsWith(`${e}/`)}async function g(e,t,n){let o=null,s=-1;for(let c of t){let t=p(c,e.config.mockServer),l=i(String(c.metadata?.sourcePath));if(t===null||l===null)continue;let u=String(c.metadata?.routeSlug),d=r(a(u,l.versionGroup,l.version,!0));d===t||d.length<=s||!h(d,n)||(await e.versions.counterparts(u))?.group.defaultVersion===l.version&&(o={api:c,path:n.slice(d.length)||`/`},s=d.length)}return o}function _(e,t,{createMockServer:n}){let r=d.get(t.key);if(r&&r.dataHash===t.dataHash)return r.handler;let{strictExamples:i,errorIfForcedExampleNotFound:a}=f(e.config.mockServer,t),o=e.entities.load(t.key).then(e=>n(structuredClone(e),{strictExamples:i,errorIfForcedExampleNotFound:a}));return d.set(t.key,{dataHash:t.dataHash,handler:o}),o.catch(()=>d.delete(t.key)),o}async function v(e,t){let o=await e.entities.list({type:`api`}),s=o.filter(({metadata:e})=>{if(e?.specType!==`openapi`||e.routeSlug!==void 0)return!1;let o=String(e.sourcePath),s=n(o),c=i(o);return(c?[s,a(s,c.versionGroup,c.version,!0)]:[s]).some(e=>h(r(e),t))});return s.length===0?o:(await Promise.all(s.map(t=>e.entities.load(t.key))),e.entities.list({type:`api`}))}function y(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 b(e){return(o(new URL(e.req.url).pathname)??``).slice(6)||`/`}async function x(t,n){if(!e(n.config,`mockServer`))return s();let r=b(t),i=await v(n,r),a=m(i,r,n.config.mockServer)??await g(n,i,r);if(!a||!n.isSlugVisible(String(a.api.metadata?.routeSlug)))return s();let o;try{o=await import(`@redocly/mock-server`)}catch{return new Response(`Mock server is not available on this host`,{status:501})}return l({handler:c,request:t.req.raw,logger:n.logger},async()=>{let e=await(await _(n,a.api,o))(y(t,a.path));return new Response(e.body?new Uint8Array(e.body):null,{status:e.statusCode,headers:{...e.headers,...u}})})}export{m as matchMockApi,x as mock,y 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{
|
|
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 +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{
|
|
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 +1 @@
|
|
|
1
|
-
import{L10N_DIR as e}from"../../../../shared/constants/l10n/defaults.js";import{isObject as t}from"../../../../shared/utils/is-object.js";import"../../../../shared/utils/l10n.js";import{splitUrlSuffix as n}from"../../../../shared/utils/routes/split-url-suffix.js";import{resolveContentPath as r}from"../../../../shared/utils/resolve-content-path.js";import{isLocalImagePath as i}from"../assets/extensions.js";import{toNavItemRbacAnnotation as a}from"../../../../shared/rbac/filter.js";import{resolvePageTarget as o}from"../../../../shared/utils/routes/resolve-page-target.js";import{collectVersionGroups as s,findVersionedDirectories as c}from"../../../versions/version-groups.js";import{joinSrcSet as l,parseSrcSet as u}from"../assets/srcset.js";import{classifyLinkTarget as d}from"../../../link-checker/classify.js";import{posix as f}from"node:path";import p from"js-yaml";function m(e){return typeof e.tab==`string`}function h(e,t,n){e.report?.({code:t,message:n,location:{filePath:e.file.path}})}function g(e,n){let i=p.load(e);if(!Array.isArray(i))return[];let a=[],o=e=>{if(t(e)){if(typeof e.$ref==`string`){let t=r(e.$ref,n);t!==null&&a.push(t)}if(Array.isArray(e.items))for(let t of e.items)o(t);if(m(e)&&Array.isArray(e.menu))for(let t of e.menu)o(t)}};for(let e of i)o(e);return a}async function _(e){let t=p.load(e.source);if(!Array.isArray(t))return[];let n=[];return await v({entries:t,ownerFilePath:e.filePath,currentFilePath:e.filePath,readFile:e.readFile,visitedRefs:/* @__PURE__ */ new Set([e.filePath]),refs:n}),n}async function v(e){let{ownerFilePath:t,currentFilePath:n,readFile:i,refs:a}=e;for(let o of e.entries){let s=K(o);if(s===void 0)continue;if(typeof s.$ref==`string`){let o=r(s.$ref,n);if(o===null||i===void 0||e.visitedRefs.has(o))continue;let c;try{c=await i(o)}catch{continue}let l=p.load(c);if(!Array.isArray(l))continue;let u=new Set(e.visitedRefs);u.add(o),await v({entries:l,ownerFilePath:t,currentFilePath:o,readFile:i,visitedRefs:u,refs:a});continue}let c=typeof s.page==`string`?s.page:s.href;typeof c==`string`&&y(a,c,n,t),Array.isArray(s.items)&&await v({...e,entries:s.items}),m(s)&&Array.isArray(s.menu)&&await v({...e,entries:s.menu})}}function y(e,t,n,r){let i=d(t,n);i!==null&&e.push({kind:`link`,raw:t,...i,...n===r?{}:{filePath:n}})}async function b(e){let t=p.load(e.source);if(!Array.isArray(t))throw Error(`Sidebar "${e.file.path}" must be a YAML sequence at the top level.`);return x({...e,entries:t})}async function x(e){let n=e.entries,r=n.filter(e=>t(e)&&m(e));if(r.length>0&&r.length!==n.length)throw Error(`Sidebar "${e.file.path}": when a sidebar uses navigation tabs, every top-level entry must be a tab (found ${n.length-r.length} other entries).`);let i={file:e.file,routes:e.routes,assignedRouteSlugs:/* @__PURE__ */ new Set,versionedDirectories:/* @__PURE__ */ new Set,report:e.report,readFile:e.readFile,skipRoutes:e.skipRoutes,exists:e.exists,sidebarByDirectory:e.sidebarByDirectory??/* @__PURE__ */ new Map,visitedRefs:/* @__PURE__ */ new Set([e.file.path])},a=[];if(r.length>0){for(let[e,t]of r.entries())a.push(await P({...i,entry:t,tabIndex:e}));L({file:e.file,tabs:a,routes:e.routes})}else for(let e of n)a.push(...await S({...i,entry:e}));return{assignedRouteSlugs:[...i.assignedRouteSlugs].sort(),versionedDirectories:[...i.versionedDirectories].sort(),nodes:a}}async function S(e){let n=await C(e),r=t(e.entry)?e.entry.rbac:void 0;if(r===void 0)return n;let i=I({...e,rbac:r});for(let e of n)Object.assign(e,i);return n}async function C(e){let t=K(e.entry);if(t===void 0)return h(e,`sidebar/invalid-entry`,`Sidebar entry ${G(e.entry)} is not a page reference or a group.`),[];if(m(t))throw Error(`Sidebar "${e.file.path}": "tab" is only allowed at the top level (found nested tab "${t.tab}").`);if(t.menu!==void 0)throw Error(`Sidebar "${e.file.path}": "menu" is only allowed directly on a tab.`);if(typeof t.$ref==`string`)return D({...e,ref:t.$ref});if(typeof t.directory==`string`&&E(t)&&t.items===void 0)return C({...e,entry:{...t,directory:void 0,items:[{directory:t.directory,flatten:t.flatten}]}});if(typeof t.directory==`string`){let n=r(t.directory,e.file.path);if(n===null)return h(e,`sidebar/invalid-entry`,`Sidebar directory "${t.directory}" is outside the content root.`),[];let i=e.routes.inDirectory(n);i.length===0&&h(e,`sidebar/missing-target`,`Sidebar directory "${t.directory}" has no pages.`);let a=await z({...e,directoryPath:n,flatten:t.flatten===!0,pages:i.filter(t=>!e.skipRoutes?.has(t.slug))}),o=J(t.group)??J(t.label);return o===void 0?a:[{type:`group`,...X(t,e),menuStyle:Z(t),items:a.length>0?a:void 0,label:o,labelTranslationKey:T(t)}]}if(typeof t.separator==`string`)return[{type:`separator`,...X(t,e),label:t.separator,labelTranslationKey:J(t.separatorTranslationKey)}];let n=await V(t,e),i=n.route;if(i)for(let t of c([i]))e.versionedDirectories.add(t);let a;if(Array.isArray(t.items)){a=[];for(let n of t.items)a.push(...await S({...e,entry:n}))}let o=J(t.group)??J(t.label)??(i===void 0?J(t.href):void 0)??n.anchor,s=E(t);return[{type:w(t,i,n.linksConnectedHeading===!0),...X(t,e),menuStyle:s?Z(t):void 0,external:t.external===!0||void 0,languageInsensitive:n.languageInsensitive?!0:void 0,items:a&&a.length>0?a:void 0,label:o,labelTranslationKey:T(t),link:n.link,isGroup:s?!0:void 0,version:J(t.version)??i?.version??void 0,versionGroup:i?.versionGroup??void 0}]}function w(e,t,n){if(E(e)&&!n)return`group`;if(t!==void 0||e.href||e.label)return`link`}function T(e){return J(E(e)?e.groupTranslationKey:e.labelTranslationKey)}function E(e){return J(e.group)!==void 0}async function D(e){let{ref:t}=e,n=r(t,e.file.path);if(n===null)return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${t}" is outside the content root.`),[];if(e.readFile===void 0)return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${t}" is not supported here.`),[];if(e.visitedRefs.has(n))return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${n}" includes itself.`),[];let i;try{i=await e.readFile(n)}catch{return h(e,`sidebar/missing-target`,`Sidebar $ref "${n}" could not be read.`),[]}let a=p.load(i);return Array.isArray(a)?O(e,n,a):(h(e,`sidebar/invalid-entry`,`Sidebar $ref "${n}" must be a YAML sequence.`),[])}async function O(e,t,n){let r=/* @__PURE__ */ new Set([...e.visitedRefs,t]),i=[];for(let a of n)i.push(...await S({...e,entry:a,file:{path:t},visitedRefs:r}));return i}async function k(e,t){if(e.readFile===void 0)return[];let n=p.load(await e.readFile(t));return Array.isArray(n)?O({...e,assignedRouteSlugs:/* @__PURE__ */ new Set,report:void 0},t,n.map(A)):[]}function A(e){if(!t(e)||!m(e))return e;let{tab:n,menu:r,...i}=e;return{...i,group:n,items:i.items??r}}function j(e,t){return`${e}-${t.normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|(?<!-)-+$/g,``)||`tab`}`}function M(e){return/* @__PURE__ */ Error(`Sidebar "${e.file.path}": tab "${e.label}" ${e.message}.`)}function N(e){let{file:t,entry:n}=e,r=n.tab,i=n.menu!==void 0;if(i&&n.items!==void 0)throw M({file:t,label:r,message:`cannot have both "menu" and "items"`});if(i&&n.page!==void 0)throw M({file:t,label:r,message:`has "menu" and cannot also have "page"`});if(!i&&n.page===void 0)throw M({file:t,label:r,message:`needs "page" or "menu"`});if(typeof n.page==`string`&&n.page.includes(`#`))throw M({file:t,label:r,message:`page must not contain a heading anchor`});if(i&&!Array.isArray(n.menu))throw M({file:t,label:r,message:`"menu" must be a list of entries`});if(i&&Array.isArray(n.menu)&&n.menu.length===0)throw M({file:t,label:r,message:`has an empty "menu"`});if(n.$ref!==void 0||n.directory!==void 0||n.group!==void 0||n.href!==void 0)throw M({file:t,label:r,message:`accepts only "page", "items", "menu" and "icon"; move "$ref"/"directory"/"group"/"href" into "items"`})}async function P(e){let{entry:t}=e,n=t.tab;N({file:e.file,entry:t});let r=j(e.tabIndex,n);if(t.menu!==void 0){let i=Array.isArray(t.menu)?t.menu:[],a=[];for(let[t,n]of i.entries()){let i=await F({...e,tabId:r,index:t,raw:n});i!==void 0&&a.push(i)}return{tab:!0,tabId:r,label:n,menu:a,...Q(t.icon,e),...I({...e,rbac:t.rbac})}}let[i]=await S({...e,entry:{page:t.page,label:n,items:t.items,rbac:t.rbac}}),a=i?.items??[];return{...i,tab:!0,tabId:r,...Q(t.icon,e),items:a}}async function F(e){let{file:t,entry:n,tabId:r,index:i,raw:a}=e,o=n.tab,s=K(a);if(s===void 0||typeof s.page!=`string`)throw Error(`Sidebar "${t.path}": menu entry ${i+1} of tab "${o}" needs "page".`);if(s.page.includes(`#`))throw Error(`Sidebar "${t.path}": menu entry ${i+1} of tab "${o}" page must not contain a heading anchor.`);let c=`${r}/${i}`,[l]=await S({...e,entry:s});return l?.link===void 0?void 0:{...l,tabId:c,items:l.items??[]}}function I(e){return a(e.rbac,()=>h(e,`sidebar/invalid-entry`,`Sidebar entry has an invalid "rbac" value, so it is hidden.`))}function L(e){let t=/* @__PURE__ */ new Map,n=(n,r)=>{for(let i of r){let r=t.get(i);if(r!==void 0&&r.tabId!==n.tabId)throw Error(`Sidebar "${e.file.path}": route "${i}" is claimed by two navigation tabs, "${r.label}" and "${n.label}". A route can belong to one tab only.`);t.set(i,n)}};for(let t of e.tabs){if(t.menu!==void 0){for(let r of t.menu)r.tabId!==void 0&&n({tabId:r.tabId,label:`${t.label} > ${r.label??r.link}`},R({routes:e.routes,link:r.link,items:r.items}));continue}t.tabId!==void 0&&n({tabId:t.tabId,label:t.label??t.link??``},R({routes:e.routes,link:t.link,items:t.items}))}}function R(e){let t=[],n=n=>{if(n.link===void 0||n.languageInsensitive===!0)return;let r=e.routes.bySlug(n.link);r!==void 0&&r.originFilePath!==null&&t.push(r.slug)};n({link:e.link});let r=e=>{if(e!==void 0)for(let t of e)n(t),r(t.items)};return r(e.items),t}async function z(t){let n=t.directoryPath===``?``:`${t.directoryPath}/`,r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=t.directoryPath.startsWith(`${e}/`),s=t.pages.filter(e=>o||e.locale===``).map(e=>({route:e,relativePath:e.originFilePath?.startsWith(n)?e.originFilePath.slice(n.length):null})).sort((e,t)=>B(e.relativePath??e.route.slug,t.relativePath??t.route.slug));for(let e of s){let n=e.relativePath?.split(`/`).slice(0,-1)??[],r=c(n);if(r!==void 0){if(!a.has(r.path)){a.add(r.path);let e=await k(t,r.path);e.length>0&&u(l(n,r.depth)).push(...e)}continue}U(e.route,t),e.route.version&&t.versionedDirectories.add(t.directoryPath),u(l(n,n.length)).push({type:`link`,link:e.route.slug,version:e.route.version??void 0,versionGroup:e.route.versionGroup??void 0})}return r;function c(e){for(let n=0;n<=e.length;n++){let r=f.join(t.directoryPath,...e.slice(0,n)),i=t.sidebarByDirectory.get(r);if(i!==void 0&&!t.visitedRefs.has(i))return{depth:n,path:i}}}function l(e,n){return t.flatten?[]:e.slice(0,n).filter(e=>!e.startsWith(`@`))}function u(e){let t=r,n=``;for(let r of e){n=n===``?r:`${n}/${r}`;let e=i.get(n);if(e){t=e;continue}let a=[];t.push({type:`group`,items:a,label:r}),i.set(n,a),t=a}return t}}function B(e,t){return e.startsWith(`index.`)?-1:t.startsWith(`index.`)?1:e.localeCompare(t,void 0,{numeric:!0})}async function V(e,t){if(typeof e.page==`string`){let{path:r,suffix:i,anchor:a}=n(e.page.trim()),o=await H(r,t);if(!o)return{};let s=e.disconnect!==!0;return s&&U(o,t),{link:`${o.slug}${i}`,anchor:a,linksConnectedHeading:s&&a!==void 0,route:o}}if(typeof e.href==`string`){let n=e.href;if(n.startsWith(`/`)){let e=t.routes.bySlug(n);return e?{link:e.slug,route:e}:{link:n,languageInsensitive:!0}}return{link:n,languageInsensitive:!0}}return{}}async function H(e,t){let n=o(e,t.file.path,t.routes);if(n.kind===`escaped`){h(t,`sidebar/invalid-entry`,`Sidebar page "${e}" is outside the content root.`);return}if(n.kind===`missing`){let n=r(e,t.file.path);n!==null&&await t.exists?.(n)&&h(t,`sidebar/missing-target`,`Sidebar page "${e}" is a file that makes no page.`);return}return n.value}function U(e,t){t.assignedRouteSlugs.add(e.slug)}async function W(e){if(e.versionedDirectories.length===0)return;let t=await s({io:e.io,routes:e.routes,versionedDirectories:e.versionedDirectories}),n=e=>{for(let r of e){if(r.version!==void 0&&r.versionGroup!==void 0){let e=t.get(r.versionGroup),n=e?.labels.get(r.version);n&&(r.versionLabel=n),e?.defaultVersion===r.version&&(r.isDefaultVersion=!0)}r.items&&n(r.items),r.menu&&n(r.menu)}};n(e.nodes)}function G(e){let t=JSON.stringify(e)??String(e);return t.length>80?`${t.slice(0,79)}…`:t}function K(e){return typeof e==`string`?e.trim()===``?void 0:{page:e}:t(e)?e:void 0}function q(e){if(!Array.isArray(e))return;let n=[];for(let r of e){if(!t(r))continue;let e=J(r.name),i=J(r.icon);(e!==void 0||i!==void 0)&&n.push({name:e??``,color:J(r.color),icon:i,position:r.position===`before`||r.position===`after`?r.position:void 0})}return n.length>0?n:void 0}function J(e){return typeof e==`string`&&e.trim()!==``?e:void 0}function Y(e,t){return t.find(t=>t===e)}function X(e,t){return{badges:q(e.badges),...Q(e.icon,t),expanded:e.expanded===!0?`true`:Y(e.expanded,[`always`]),selectFirstItemOnExpand:e.selectFirstItemOnExpand===!0||void 0,separatorLine:e.separatorLine===!0||void 0,linePosition:Y(e.linePosition,[`top`,`bottom`]),target:J(e.target),sublabel:J(e.sublabel)}}function Z(e){return Y(e.menuStyle,[`drilldown`,`drilldown-header`])}function Q(e,n){let r=t(e)?J(e.srcSet):void 0;if(r!==void 0){let e=u(r);if(e===null)return{srcSet:r};for(let t of e)t.src=$(t.src,n);return{srcSet:l(e)}}let i=J(e);return i===void 0?{}:{icon:$(i,n)}}function $(e,t){if(!i(e))return e;let n=r(e,t.file.path);return n===null?(h(t,`sidebar/invalid-entry`,`Sidebar icon "${e}" is outside the content root.`),e):`/${n}`}export{b as bundleSidebar,x as bundleSidebarEntries,_ as collectSidebarLinkRefs,g as collectSidebarRefTargets,W as stampDefaultVersions};
|
|
1
|
+
import{L10N_DIR as e}from"../../../../shared/constants/l10n/defaults.js";import{isObject as t}from"../../../../shared/utils/is-object.js";import"../../../../shared/utils/l10n.js";import{resolveContentPath as n}from"../../../../shared/utils/resolve-content-path.js";import{isLocalImagePath as r}from"../assets/extensions.js";import{splitUrlSuffix as i}from"../../../../shared/utils/routes/split-url-suffix.js";import{toNavItemRbacAnnotation as a}from"../../../../shared/rbac/filter.js";import{resolvePageTarget as o}from"../../../../shared/utils/routes/resolve-page-target.js";import{collectVersionGroups as s,findVersionedDirectories as c}from"../../../versions/version-groups.js";import{joinSrcSet as l,parseSrcSet as u}from"../assets/srcset.js";import{classifyLinkTarget as d}from"../../../link-checker/classify.js";import{posix as f}from"node:path";import p from"js-yaml";function m(e){return typeof e.tab==`string`}function h(e,t,n){e.report?.({code:t,message:n,location:{filePath:e.file.path}})}function g(e,r){let i=p.load(e);if(!Array.isArray(i))return[];let a=[],o=e=>{if(t(e)){if(typeof e.$ref==`string`){let t=n(e.$ref,r);t!==null&&a.push(t)}if(Array.isArray(e.items))for(let t of e.items)o(t);if(m(e)&&Array.isArray(e.menu))for(let t of e.menu)o(t)}};for(let e of i)o(e);return a}async function _(e){let t=p.load(e.source);if(!Array.isArray(t))return[];let n=[];return await v({entries:t,ownerFilePath:e.filePath,currentFilePath:e.filePath,readFile:e.readFile,visitedRefs:/* @__PURE__ */ new Set([e.filePath]),refs:n}),n}async function v(e){let{ownerFilePath:t,currentFilePath:r,readFile:i,refs:a}=e;for(let o of e.entries){let s=K(o);if(s===void 0)continue;if(typeof s.$ref==`string`){let o=n(s.$ref,r);if(o===null||i===void 0||e.visitedRefs.has(o))continue;let c;try{c=await i(o)}catch{continue}let l=p.load(c);if(!Array.isArray(l))continue;let u=new Set(e.visitedRefs);u.add(o),await v({entries:l,ownerFilePath:t,currentFilePath:o,readFile:i,visitedRefs:u,refs:a});continue}let c=typeof s.page==`string`?s.page:s.href;typeof c==`string`&&y(a,c,r,t),Array.isArray(s.items)&&await v({...e,entries:s.items}),m(s)&&Array.isArray(s.menu)&&await v({...e,entries:s.menu})}}function y(e,t,n,r){let i=d(t,n);i!==null&&e.push({kind:`link`,raw:t,...i,...n===r?{}:{filePath:n}})}async function b(e){let t=p.load(e.source);if(!Array.isArray(t))throw Error(`Sidebar "${e.file.path}" must be a YAML sequence at the top level.`);return x({...e,entries:t})}async function x(e){let n=e.entries,r=n.filter(e=>t(e)&&m(e));if(r.length>0&&r.length!==n.length)throw Error(`Sidebar "${e.file.path}": when a sidebar uses navigation tabs, every top-level entry must be a tab (found ${n.length-r.length} other entries).`);let i={file:e.file,routes:e.routes,assignedRouteSlugs:/* @__PURE__ */ new Set,versionedDirectories:/* @__PURE__ */ new Set,report:e.report,readFile:e.readFile,skipRoutes:e.skipRoutes,exists:e.exists,sidebarByDirectory:e.sidebarByDirectory??/* @__PURE__ */ new Map,visitedRefs:/* @__PURE__ */ new Set([e.file.path])},a=[];if(r.length>0){for(let[e,t]of r.entries())a.push(await P({...i,entry:t,tabIndex:e}));L({file:e.file,tabs:a,routes:e.routes})}else for(let e of n)a.push(...await S({...i,entry:e}));return{assignedRouteSlugs:[...i.assignedRouteSlugs].sort(),versionedDirectories:[...i.versionedDirectories].sort(),nodes:a}}async function S(e){let n=await C(e),r=t(e.entry)?e.entry.rbac:void 0;if(r===void 0)return n;let i=I({...e,rbac:r});for(let e of n)Object.assign(e,i);return n}async function C(e){let t=K(e.entry);if(t===void 0)return h(e,`sidebar/invalid-entry`,`Sidebar entry ${G(e.entry)} is not a page reference or a group.`),[];if(m(t))throw Error(`Sidebar "${e.file.path}": "tab" is only allowed at the top level (found nested tab "${t.tab}").`);if(t.menu!==void 0)throw Error(`Sidebar "${e.file.path}": "menu" is only allowed directly on a tab.`);if(typeof t.$ref==`string`)return D({...e,ref:t.$ref});if(typeof t.directory==`string`&&E(t)&&t.items===void 0)return C({...e,entry:{...t,directory:void 0,items:[{directory:t.directory,flatten:t.flatten}]}});if(typeof t.directory==`string`){let r=n(t.directory,e.file.path);if(r===null)return h(e,`sidebar/invalid-entry`,`Sidebar directory "${t.directory}" is outside the content root.`),[];let i=e.routes.inDirectory(r);i.length===0&&h(e,`sidebar/missing-target`,`Sidebar directory "${t.directory}" has no pages.`);let a=await z({...e,directoryPath:r,flatten:t.flatten===!0,pages:i.filter(t=>!e.skipRoutes?.has(t.slug))}),o=J(t.group)??J(t.label);return o===void 0?a:[{type:`group`,...X(t,e),menuStyle:Z(t),items:a.length>0?a:void 0,label:o,labelTranslationKey:T(t)}]}if(typeof t.separator==`string`)return[{type:`separator`,...X(t,e),label:t.separator,labelTranslationKey:J(t.separatorTranslationKey)}];let r=await V(t,e),i=r.route;if(i)for(let t of c([i]))e.versionedDirectories.add(t);let a;if(Array.isArray(t.items)){a=[];for(let n of t.items)a.push(...await S({...e,entry:n}))}let o=J(t.group)??J(t.label)??(i===void 0?J(t.href):void 0)??r.anchor,s=E(t);return[{type:w(t,i,r.linksConnectedHeading===!0),...X(t,e),menuStyle:s?Z(t):void 0,external:t.external===!0||void 0,languageInsensitive:r.languageInsensitive?!0:void 0,items:a&&a.length>0?a:void 0,label:o,labelTranslationKey:T(t),link:r.link,isGroup:s?!0:void 0,version:J(t.version)??i?.version??void 0,versionGroup:i?.versionGroup??void 0}]}function w(e,t,n){if(E(e)&&!n)return`group`;if(t!==void 0||e.href||e.label)return`link`}function T(e){return J(E(e)?e.groupTranslationKey:e.labelTranslationKey)}function E(e){return J(e.group)!==void 0}async function D(e){let{ref:t}=e,r=n(t,e.file.path);if(r===null)return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${t}" is outside the content root.`),[];if(e.readFile===void 0)return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${t}" is not supported here.`),[];if(e.visitedRefs.has(r))return h(e,`sidebar/invalid-entry`,`Sidebar $ref "${r}" includes itself.`),[];let i;try{i=await e.readFile(r)}catch{return h(e,`sidebar/missing-target`,`Sidebar $ref "${r}" could not be read.`),[]}let a=p.load(i);return Array.isArray(a)?O(e,r,a):(h(e,`sidebar/invalid-entry`,`Sidebar $ref "${r}" must be a YAML sequence.`),[])}async function O(e,t,n){let r=/* @__PURE__ */ new Set([...e.visitedRefs,t]),i=[];for(let a of n)i.push(...await S({...e,entry:a,file:{path:t},visitedRefs:r}));return i}async function k(e,t){if(e.readFile===void 0)return[];let n=p.load(await e.readFile(t));return Array.isArray(n)?O({...e,assignedRouteSlugs:/* @__PURE__ */ new Set,report:void 0},t,n.map(A)):[]}function A(e){if(!t(e)||!m(e))return e;let{tab:n,menu:r,...i}=e;return{...i,group:n,items:i.items??r}}function j(e,t){return`${e}-${t.normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|(?<!-)-+$/g,``)||`tab`}`}function M(e){return/* @__PURE__ */ Error(`Sidebar "${e.file.path}": tab "${e.label}" ${e.message}.`)}function N(e){let{file:t,entry:n}=e,r=n.tab,i=n.menu!==void 0;if(i&&n.items!==void 0)throw M({file:t,label:r,message:`cannot have both "menu" and "items"`});if(i&&n.page!==void 0)throw M({file:t,label:r,message:`has "menu" and cannot also have "page"`});if(!i&&n.page===void 0)throw M({file:t,label:r,message:`needs "page" or "menu"`});if(typeof n.page==`string`&&n.page.includes(`#`))throw M({file:t,label:r,message:`page must not contain a heading anchor`});if(i&&!Array.isArray(n.menu))throw M({file:t,label:r,message:`"menu" must be a list of entries`});if(i&&Array.isArray(n.menu)&&n.menu.length===0)throw M({file:t,label:r,message:`has an empty "menu"`});if(n.$ref!==void 0||n.directory!==void 0||n.group!==void 0||n.href!==void 0)throw M({file:t,label:r,message:`accepts only "page", "items", "menu" and "icon"; move "$ref"/"directory"/"group"/"href" into "items"`})}async function P(e){let{entry:t}=e,n=t.tab;N({file:e.file,entry:t});let r=j(e.tabIndex,n);if(t.menu!==void 0){let i=Array.isArray(t.menu)?t.menu:[],a=[];for(let[t,n]of i.entries()){let i=await F({...e,tabId:r,index:t,raw:n});i!==void 0&&a.push(i)}return{tab:!0,tabId:r,label:n,menu:a,...Q(t.icon,e),...I({...e,rbac:t.rbac})}}let[i]=await S({...e,entry:{page:t.page,label:n,items:t.items,rbac:t.rbac}}),a=i?.items??[];return{...i,tab:!0,tabId:r,...Q(t.icon,e),items:a}}async function F(e){let{file:t,entry:n,tabId:r,index:i,raw:a}=e,o=n.tab,s=K(a);if(s===void 0||typeof s.page!=`string`)throw Error(`Sidebar "${t.path}": menu entry ${i+1} of tab "${o}" needs "page".`);if(s.page.includes(`#`))throw Error(`Sidebar "${t.path}": menu entry ${i+1} of tab "${o}" page must not contain a heading anchor.`);let c=`${r}/${i}`,[l]=await S({...e,entry:s});return l?.link===void 0?void 0:{...l,tabId:c,items:l.items??[]}}function I(e){return a(e.rbac,()=>h(e,`sidebar/invalid-entry`,`Sidebar entry has an invalid "rbac" value, so it is hidden.`))}function L(e){let t=/* @__PURE__ */ new Map,n=(n,r)=>{for(let i of r){let r=t.get(i);if(r!==void 0&&r.tabId!==n.tabId)throw Error(`Sidebar "${e.file.path}": route "${i}" is claimed by two navigation tabs, "${r.label}" and "${n.label}". A route can belong to one tab only.`);t.set(i,n)}};for(let t of e.tabs){if(t.menu!==void 0){for(let r of t.menu)r.tabId!==void 0&&n({tabId:r.tabId,label:`${t.label} > ${r.label??r.link}`},R({routes:e.routes,link:r.link,items:r.items}));continue}t.tabId!==void 0&&n({tabId:t.tabId,label:t.label??t.link??``},R({routes:e.routes,link:t.link,items:t.items}))}}function R(e){let t=[],n=n=>{if(n.link===void 0||n.languageInsensitive===!0)return;let r=e.routes.bySlug(n.link);r!==void 0&&r.originFilePath!==null&&t.push(r.slug)};n({link:e.link});let r=e=>{if(e!==void 0)for(let t of e)n(t),r(t.items)};return r(e.items),t}async function z(t){let n=t.directoryPath===``?``:`${t.directoryPath}/`,r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,o=t.directoryPath.startsWith(`${e}/`),s=t.pages.filter(e=>o||e.locale===``).map(e=>({route:e,relativePath:e.originFilePath?.startsWith(n)?e.originFilePath.slice(n.length):null})).sort((e,t)=>B(e.relativePath??e.route.slug,t.relativePath??t.route.slug));for(let e of s){let n=e.relativePath?.split(`/`).slice(0,-1)??[],r=c(n);if(r!==void 0){if(!a.has(r.path)){a.add(r.path);let e=await k(t,r.path);e.length>0&&u(l(n,r.depth)).push(...e)}continue}U(e.route,t),e.route.version&&t.versionedDirectories.add(t.directoryPath),u(l(n,n.length)).push({type:`link`,link:e.route.slug,version:e.route.version??void 0,versionGroup:e.route.versionGroup??void 0})}return r;function c(e){for(let n=0;n<=e.length;n++){let r=f.join(t.directoryPath,...e.slice(0,n)),i=t.sidebarByDirectory.get(r);if(i!==void 0&&!t.visitedRefs.has(i))return{depth:n,path:i}}}function l(e,n){return t.flatten?[]:e.slice(0,n).filter(e=>!e.startsWith(`@`))}function u(e){let t=r,n=``;for(let r of e){n=n===``?r:`${n}/${r}`;let e=i.get(n);if(e){t=e;continue}let a=[];t.push({type:`group`,items:a,label:r}),i.set(n,a),t=a}return t}}function B(e,t){return e.startsWith(`index.`)?-1:t.startsWith(`index.`)?1:e.localeCompare(t,void 0,{numeric:!0})}async function V(e,t){if(typeof e.page==`string`){let{path:n,suffix:r,anchor:a}=i(e.page.trim()),o=await H(n,t);if(!o)return{};let s=e.disconnect!==!0;return s&&U(o,t),{link:`${o.slug}${r}`,anchor:a,linksConnectedHeading:s&&a!==void 0,route:o}}if(typeof e.href==`string`){let n=e.href;if(n.startsWith(`/`)){let e=t.routes.bySlug(n);return e?{link:e.slug,route:e}:{link:n,languageInsensitive:!0}}return{link:n,languageInsensitive:!0}}return{}}async function H(e,t){let r=o(e,t.file.path,t.routes);if(r.kind===`escaped`){h(t,`sidebar/invalid-entry`,`Sidebar page "${e}" is outside the content root.`);return}if(r.kind===`missing`){let r=n(e,t.file.path);r!==null&&await t.exists?.(r)&&h(t,`sidebar/missing-target`,`Sidebar page "${e}" is a file that makes no page.`);return}return r.value}function U(e,t){t.assignedRouteSlugs.add(e.slug)}async function W(e){if(e.versionedDirectories.length===0)return;let t=await s({io:e.io,routes:e.routes,versionedDirectories:e.versionedDirectories}),n=e=>{for(let r of e){if(r.version!==void 0&&r.versionGroup!==void 0){let e=t.get(r.versionGroup),n=e?.labels.get(r.version);n&&(r.versionLabel=n),e?.defaultVersion===r.version&&(r.isDefaultVersion=!0)}r.items&&n(r.items),r.menu&&n(r.menu)}};n(e.nodes)}function G(e){let t=JSON.stringify(e)??String(e);return t.length>80?`${t.slice(0,79)}…`:t}function K(e){return typeof e==`string`?e.trim()===``?void 0:{page:e}:t(e)?e:void 0}function q(e){if(!Array.isArray(e))return;let n=[];for(let r of e){if(!t(r))continue;let e=J(r.name),i=J(r.icon);(e!==void 0||i!==void 0)&&n.push({name:e??``,color:J(r.color),icon:i,position:r.position===`before`||r.position===`after`?r.position:void 0})}return n.length>0?n:void 0}function J(e){return typeof e==`string`&&e.trim()!==``?e:void 0}function Y(e,t){return t.find(t=>t===e)}function X(e,t){return{badges:q(e.badges),...Q(e.icon,t),expanded:e.expanded===!0?`true`:Y(e.expanded,[`always`]),selectFirstItemOnExpand:e.selectFirstItemOnExpand===!0||void 0,separatorLine:e.separatorLine===!0||void 0,linePosition:Y(e.linePosition,[`top`,`bottom`]),target:J(e.target),sublabel:J(e.sublabel)}}function Z(e){return Y(e.menuStyle,[`drilldown`,`drilldown-header`])}function Q(e,n){let r=t(e)?J(e.srcSet):void 0;if(r!==void 0){let e=u(r);if(e===null)return{srcSet:r};for(let t of e)t.src=$(t.src,n);return{srcSet:l(e)}}let i=J(e);return i===void 0?{}:{icon:$(i,n)}}function $(e,t){if(!r(e))return e;let i=n(e,t.file.path);return i===null?(h(t,`sidebar/invalid-entry`,`Sidebar icon "${e}" is outside the content root.`),e):`/${i}`}export{b as bundleSidebar,x as bundleSidebarEntries,_ as collectSidebarLinkRefs,g as collectSidebarRefTargets,W as stampDefaultVersions};
|