@redocly/framework 1.0.0-next.11 → 1.0.0-next.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/bundler/dev/routes/source-sync-route.js +1 -1
  2. package/dist/bundler/dev/runtime-app.js +1 -1
  3. package/dist/bundler/dev/vite-config.js +1 -1
  4. package/dist/cli/problems-output.js +3 -3
  5. package/dist/client/UnversionedVersionButton.js +1 -1
  6. package/dist/client/VersionPicker.js +343 -0
  7. package/dist/client/ai-search/citations.js +3 -3
  8. package/dist/client/app.js +2 -2
  9. package/dist/client/classic-webview-sync.js +1 -0
  10. package/dist/client/client-entry.js +1 -1
  11. package/dist/client/history-mount.js +6 -5
  12. package/dist/client/page-sync.js +1 -0
  13. package/dist/client/review/ReviewBar.js +31 -31
  14. package/dist/client/review/login-url.js +1 -1
  15. package/dist/client/revisions-history.js +1 -1
  16. package/dist/content-layer/config-schema.js +1 -1
  17. package/dist/content-layer/config.d.ts +8 -0
  18. package/dist/content-layer/config.js +1 -1
  19. package/dist/content-layer/context.d.ts +6 -0
  20. package/dist/content-layer/database/entities.d.ts +2 -0
  21. package/dist/content-layer/database/entities.js +1 -1
  22. package/dist/content-layer/database/origins.d.ts +2 -1
  23. package/dist/content-layer/database/origins.js +1 -1
  24. package/dist/content-layer/database/route-query-deps.d.ts +19 -3
  25. package/dist/content-layer/database/route-query-deps.js +1 -1
  26. package/dist/content-layer/ingest/git-last-modified.d.ts +20 -0
  27. package/dist/content-layer/ingest/git-last-modified.js +5 -4
  28. package/dist/content-layer/ingest/run.js +1 -1
  29. package/dist/content-layer/link-checker/fingerprint.js +1 -1
  30. package/dist/content-layer/link-checker/load-view.js +1 -1
  31. package/dist/content-layer/markdown/client/markdown-text.js +1 -1
  32. package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
  33. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +2 -0
  34. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
  35. package/dist/content-layer/plugins/internal/api-docs/server/markdown-copy.js +11 -9
  36. package/dist/content-layer/plugins/internal/api-docs/server/options.d.ts +1 -1
  37. package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
  38. package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
  39. package/dist/content-layer/plugins/internal/app-data/index.d.ts +1 -1
  40. package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
  41. package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
  42. package/dist/content-layer/plugins/internal/mcp/constants.d.ts +4 -3
  43. package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
  44. package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
  45. package/dist/content-layer/plugins/internal/mcp/index.js +1 -1
  46. package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
  47. package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
  48. package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
  49. package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
  50. package/dist/content-layer/plugins/internal/mcp/server/gateway/subject.js +1 -1
  51. package/dist/content-layer/plugins/internal/mcp/server/gateway/tool-list.js +1 -1
  52. package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +3 -3
  53. package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
  54. package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
  55. package/dist/content-layer/plugins/internal/mcp/server/oauth/callback.js +1 -1
  56. package/dist/content-layer/plugins/internal/mcp/server/oauth/error-reporting.js +1 -1
  57. package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
  58. package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
  59. package/dist/content-layer/plugins/internal/mcp/server/workflows/resolve-workflows.js +1 -1
  60. package/dist/content-layer/plugins/internal/mcp/server/workflows/schemas.js +2 -1
  61. package/dist/content-layer/plugins/internal/mcp/server/workflows/tools.js +1 -1
  62. package/dist/content-layer/plugins/internal/scorecard-classic/client/template.js +1 -1
  63. package/dist/content-layer/plugins/internal/sidebar/index.js +1 -1
  64. package/dist/content-layer/plugins/internal/versions/index.js +1 -1
  65. package/dist/content-layer/plugins/utils/route-index.js +1 -1
  66. package/dist/content-layer/server/database.js +1 -1
  67. package/dist/content-layer/versions/group-info.d.ts +2 -1
  68. package/dist/content-layer/versions/group-info.js +1 -1
  69. package/dist/server/app.js +1 -1
  70. package/dist/server/auth/runtime.js +1 -1
  71. package/dist/server/content.js +7 -7
  72. package/dist/server/lambda-entry.js +1 -1
  73. package/dist/server/node-entry.js +1 -1
  74. package/dist/server/search/route.js +1 -1
  75. package/dist/server/telemetry/mock-server-events.js +1 -1
  76. package/dist/server/telemetry/sender.js +1 -1
  77. package/dist/server/wait-until.js +1 -0
  78. package/dist/shared/constants/review.d.ts +2 -0
  79. package/dist/shared/constants/review.js +1 -1
  80. package/dist/shared/constants/system-routes.d.ts +1 -1
  81. package/dist/shared/constants/system-routes.js +1 -1
  82. package/dist/shared/types/config.d.ts +2 -1
  83. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
- import{CALL_API_WRITE_TOOL_NAME as e}from"../../constants.js";import{buildToolList as t}from"./tool-list.js";const n=2048,r="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",i="Write plain JavaScript: no type annotations, interfaces or `as` casts.";function a(e,r){if(r.length===0)return e;let i=n-e.length-66-3,a=t(r,i);return a?[e,``,"Functions for `execute` scripts (signatures come from `discover`):",a].join(`
2
- `):e}function o(e,t){return[t?`Run plain JavaScript (no TypeScript syntax) in a sandbox against the documentation at ${t}. The script calls the sandbox functions on the global \`site\` object.`:"Run plain JavaScript (no TypeScript syntax) in a sandbox against this documentation site. The script calls the sandbox functions on the global `site` object.",e?"The extra globals are `site`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `site`.":"The only extra global is `site` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `site`.",``,"Workflow - minimize round-trips; one `discover` call plus one `execute` call covers most requests:",`1. Analyze the request and decide which sandbox functions it needs.`,"2. Call `discover` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed function names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain function calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
3
- `)}function s(e,t){let r=e&&t(e);return r&&r.length<=n?r:t()}function c(e,t=[],n){return a(s(n,t=>o(e,t)),t)}function l(e){return e?`Tools for the documentation at ${e}.`:`Tools for this documentation site.`}function u(e){return`${l(e)} Use them to answer questions about the content of these docs.`}function d(e){return s(e,u)}function f(e){return["Get the exact TypeScript signatures of the sandbox functions that `execute` scripts can call.",`Analyze the user request first, then pass \`names\` with only the functions the request needs (${e?`every name is listed in this input schema / description`:`every name is in the enum of this input schema`}); omit \`names\` only when you cannot tell which functions apply.`,"Always call this before your first `execute` and never guess signatures. Request every function the task may need in ONE call instead of calling this repeatedly."].join(`
4
- `)}function p({hasFetch:t,hasCallApiWrite:n,hasWorkflows:r,docsUrl:i}){let a=[u(i),"- `discover` returns the exact TypeScript signatures of the sandbox functions.","- `execute` runs a JavaScript script that calls those functions on the global `site` object.","Workflow: analyze the request, call `discover` once with `names` set to only the functions it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess function signatures."];return t&&a.push("The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `discover` call to get its contract and the list of callable APIs."),n&&a.push(`\`fetch\` sends only safe methods. Send one write request to a documented API with the \`${e}\` tool.`),r&&a.push("This project also ships ready-made multi-step API workflows. When a task needs several API calls, call `listWorkflows` first and run a matching workflow with `runWorkflow` instead of chaining `fetch` calls."),a.join(`
5
- `)}function m(e){return a(s(e.docsUrl,t=>p({...e,docsUrl:t})),e.toolList??[])}const h=[`listApis`,`getEndpoints`],g=[`Example - list the write endpoints of an API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const writes = endpoints.filter((e) => e.method !== 'GET');`,"return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
- `);function _(e){if(h.every(t=>e.includes(t)))return g;let[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,``,"```js",`const result = await site.${t}({ /* the input its signature above declares */ });`,`return result;`,"```"].join(`
7
- `):``}const v=["Types named `OpenApi…` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
8
- `);export{r as EXECUTE_ARGS_NOTE,i as PLAIN_JAVASCRIPT_RULE,v as USAGE_NOTES,m as buildCodeModeInstructions,f as buildDiscoverDescription,c as buildExecuteDescription,_ as buildExecuteExample,d as buildToolsModeInstructions,l as docsSiteSentence};
1
+ import{CALL_API_WRITE_TOOL_NAME as e,RUN_WORKFLOW_WRITE_TOOL_NAME as t}from"../../constants.js";import{buildToolList as n}from"./tool-list.js";const r=2048,i="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",a="Write plain JavaScript: no type annotations, interfaces or `as` casts.";function o(e,t){if(t.length===0)return e;let i=r-e.length-66-3,a=n(t,i);return a?[e,``,"Functions for `execute` scripts (signatures come from `discover`):",a].join(`
2
+ `):e}function s(e,t){return[t?`Run plain JavaScript (no TypeScript syntax) in a sandbox against the documentation at ${t}. The script calls the sandbox functions on the global \`site\` object.`:"Run plain JavaScript (no TypeScript syntax) in a sandbox against this documentation site. The script calls the sandbox functions on the global `site` object.",e?"The extra globals are `site`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `site`.":"The only extra global is `site` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `site`.",``,"Workflow - minimize round-trips; one `discover` call plus one `execute` call covers most requests:",`1. Analyze the request and decide which sandbox functions it needs.`,"2. Call `discover` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed function names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain function calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
3
+ `)}function c(e,t){let n=e&&t(e);return n&&n.length<=r?n:t()}function l(e,t=[],n){return o(c(n,t=>s(e,t)),t)}function u(e){return e?`Tools for the documentation at ${e}.`:`Tools for this documentation site.`}function d(e){return`${u(e)} Use them to answer questions about the content of these docs.`}function f(e){return c(e,d)}function p(e){return["Get the exact TypeScript signatures of the sandbox functions that `execute` scripts can call.",`Analyze the user request first, then pass \`names\` with only the functions the request needs (${e?`every name is listed in this input schema / description`:`every name is in the enum of this input schema`}); omit \`names\` only when you cannot tell which functions apply.`,"Always call this before your first `execute` and never guess signatures. Request every function the task may need in ONE call instead of calling this repeatedly."].join(`
4
+ `)}function m({hasFetch:n,hasCallApiWrite:r,hasWorkflows:i,hasRunWorkflowWrite:a,docsUrl:o}){let s=[d(o),"- `discover` returns the exact TypeScript signatures of the sandbox functions.","- `execute` runs a JavaScript script that calls those functions on the global `site` object.","Workflow: analyze the request, call `discover` once with `names` set to only the functions it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess function signatures."];return n&&s.push("The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `discover` call to get its contract and the list of callable APIs."),r&&s.push(`\`fetch\` sends only safe methods. Send one write request to a documented API with the \`${e}\` tool.`),i&&s.push("This project also ships ready-made multi-step API workflows. When a task needs several API calls, call `listWorkflows` first and run a matching workflow with `runWorkflow` instead of chaining `fetch` calls."),a&&s.push(`\`runWorkflow\` runs only read-only workflows. Run a workflow that writes with the \`${t}\` tool.`),s.join(`
5
+ `)}function h(e){return o(c(e.docsUrl,t=>m({...e,docsUrl:t})),e.toolList??[])}const g=[`listApis`,`getEndpoints`],_=[`Example - list the write endpoints of an API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const writes = endpoints.filter((e) => e.method !== 'GET');`,"return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
+ `);function v(e){if(g.every(t=>e.includes(t)))return _;let[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,``,"```js",`const result = await site.${t}({ /* the input its signature above declares */ });`,`return result;`,"```"].join(`
7
+ `):``}const y=["Types named `OpenApi…` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
8
+ `);export{i as EXECUTE_ARGS_NOTE,a as PLAIN_JAVASCRIPT_RULE,y as USAGE_NOTES,h as buildCodeModeInstructions,p as buildDiscoverDescription,l as buildExecuteDescription,v as buildExecuteExample,f as buildToolsModeInstructions,u as docsSiteSentence};
@@ -1 +1 @@
1
- import"../../constants.js";import{isToolDisabledByCaller as e}from"../disabled-tools.js";import{randomBytes as t}from"node:crypto";const n=/^[A-Za-z0-9_-]{43}$/,r=`anon:`,i=`user:`,a=`This API requires credentials and the caller is anonymous; call createAnonymousSession first, then retry with sessionHandle`,o=`The sessionHandle is not a valid handle; call createAnonymousSession to obtain one`,s=`This API requires credentials, and this client cannot add them for an anonymous caller. Tell the user that the API needs credentials and that, if this site offers sign-in, they can sign in and ask again. Do not retry the call.`;function c(){return t(32).toString(`base64url`)}function l(e){return n.test(e)}function u(e){if(!e?.isAuthenticated)return;let t=e.sub||e.email;if(t)return`${i}${e.idpId||`local`}:${t}`}function d(t,n){let i=u(t.request.viewer);return i?{kind:`resolved`,subject:i}:e(`createAnonymousSession`,t.metadata)?{kind:`anonymous`,message:s}:typeof n==`string`?l(n)?{kind:`resolved`,subject:`${r}${n}`}:{kind:`invalid`,message:o}:{kind:`anonymous`,message:a}}function f(e){return e.startsWith(`anon:`)?86400:604800}export{s as ANONYMOUS_CREDENTIALS_UNAVAILABLE_MESSAGE,r as ANONYMOUS_SUBJECT_PREFIX,o as MALFORMED_SESSION_HANDLE_MESSAGE,a as MISSING_SESSION_HANDLE_MESSAGE,i as USER_SUBJECT_PREFIX,c as createSessionHandle,l as isValidSessionHandle,d as resolveSecretSubject,f as secretTtlSeconds,u as userSubject};
1
+ import"../../constants.js";import{isToolDisabledByCaller as e}from"../disabled-tools.js";import{randomBytes as t}from"node:crypto";const n=/^[A-Za-z0-9_-]{43}$/,r=`anon:`,i=`user:`,a="This API requires credentials and the caller is anonymous; call `create-anonymous-session` first, then retry with sessionHandle",o="The sessionHandle is not a valid handle; call `create-anonymous-session` to obtain one",s=`This API requires credentials, and this client cannot add them for an anonymous caller. Tell the user that the API needs credentials and that, if this site offers sign-in, they can sign in and ask again. Do not retry the call.`;function c(){return t(32).toString(`base64url`)}function l(e){return n.test(e)}function u(e){if(!e?.isAuthenticated)return;let t=e.sub||e.email;if(t)return`${i}${e.idpId||`local`}:${t}`}function d(t,n){let i=u(t.request.viewer);return i?{kind:`resolved`,subject:i}:e(`create-anonymous-session`,t.metadata)?{kind:`anonymous`,message:s}:typeof n==`string`?l(n)?{kind:`resolved`,subject:`${r}${n}`}:{kind:`invalid`,message:o}:{kind:`anonymous`,message:a}}function f(e){return e.startsWith(`anon:`)?86400:604800}export{s as ANONYMOUS_CREDENTIALS_UNAVAILABLE_MESSAGE,r as ANONYMOUS_SUBJECT_PREFIX,o as MALFORMED_SESSION_HANDLE_MESSAGE,a as MISSING_SESSION_HANDLE_MESSAGE,i as USER_SUBJECT_PREFIX,c as createSessionHandle,l as isValidSessionHandle,d as resolveSecretSubject,f as secretTtlSeconds,u as userSubject};
@@ -1 +1 @@
1
- import{createAnonymousSessionTool as e,manageApiCredentialsTool as t,removeApiCredentialsTool as n}from"./tools.js";import{callApiWriteTool as r}from"./call-api.js";import{workflowTools as i}from"../workflows/tools.js";function a(){return[e,t,n,r,...i()]}export{a as gatewayTools};
1
+ import{createAnonymousSessionTool as e,manageApiCredentialsTool as t,removeApiCredentialsTool as n}from"./tools.js";import{callApiWriteTool as r}from"./call-api.js";import{runWorkflowWriteTool as i,workflowTools as a}from"../workflows/tools.js";function o(){return[e,t,n,r,i,...a()]}export{o as gatewayTools};
@@ -1,4 +1,4 @@
1
- import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REMOVE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{publicOrigin as i}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:e,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:n,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`createAnonymousSession`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:`Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.`,minLength:1};function O(e,n,i){return{name:t,title:`Manage API credentials`,description:[i?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,i?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${r}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
2
- `),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,n,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(e,t,n){let r=new f(t.gatewaySecretSeed),a=s(t,e.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(t),e.api);if(`error`in c)return c.error;let{api:l}=c,u=i(t.request),w=v(n?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(n?.mcpReq.requestState(),{secretStore:r,kv:t.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof e.scheme==`string`?e.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:r,kv:t.kv,hasExistingSecret:await r.hasSecret(t.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(n&&b(n.mcpReq)&&S(n.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(r,e.metadata)),isAvailable:async e=>!a(`manageApiCredentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n?.serverContext)};function F(e,n,i){return{name:r,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${i?` To replace a credential, call \`${t}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
1
+ import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REMOVE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{publicOrigin as i}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:e,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:n,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`create-anonymous-session`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:"Handle returned by `create-anonymous-session`. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1};function O(e,n,i){return{name:t,title:`Manage API credentials`,description:[i?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,i?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${r}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
2
+ `),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,n,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(e,t,n){let r=new f(t.gatewaySecretSeed),a=s(t,e.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(t),e.api);if(`error`in c)return c.error;let{api:l}=c,u=i(t.request),w=v(n?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(n?.mcpReq.requestState(),{secretStore:r,kv:t.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof e.scheme==`string`?e.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:r,kv:t.kv,hasExistingSecret:await r.hasSecret(t.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(n&&b(n.mcpReq)&&S(n.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(r,e.metadata)),isAvailable:async e=>!a(`manage-api-credentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n?.serverContext)};function F(e,n,i){return{name:r,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${i?` To replace a credential, call \`${t}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
3
3
  `),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,n,`The API to remove credentials for`),scheme:{type:`string`,description:`Name of the security scheme to remove the credential for, as named in the API description. Needs api. Omit it to remove every credential of the API.`,minLength:1},all:{type:`boolean`,description:`Set to true, without api, to remove the credentials of every API. Use it only when the user asks to remove all their credentials.`},sessionHandle:D}}}}async function I(e,t){let n=new f(t.gatewaySecretSeed),r=s(t,e.sessionHandle);if(r.kind!==`resolved`)return N(r.message);let{subject:i}=r,a=await d(t),o=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return o===void 0?e.all===!0?L(await n.deleteSecrets(t.kv,i),a,`No credentials are stored for this caller, so nothing was removed.`):N(`Name the api to remove credentials for. To remove the credentials of every API, pass all: true instead.`):N(`Pass api together with scheme "${o}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let c=A(a,e.api);if(`error`in c)return c.error;let{api:l}=c;if(o===void 0)return L(await n.deleteSecrets(t.kv,i,l.relativePath),a,`No credentials are stored for the "${l.name}" API, so nothing was removed.`);let u=Object.keys(p(l).schemes);if(!u.includes(o))return j(o,l,u);let m=`No credential is stored for the "${o}" scheme of the "${l.name}" API, so nothing was removed.`;return await n.hasSecret(t.kv,i,l.relativePath,o)?(await n.deleteSecret(t.kv,i,l.relativePath,o),L([{api:l.relativePath,scheme:o}],a,m)):L([],a,m)}function L(e,t,n){if(e.length===0)return{content:[{type:`text`,text:n}],isError:!1};let r=/* @__PURE__ */ new Map;for(let{api:t,scheme:n}of e)r.set(t,[...r.get(t)??[],n]);return{content:[{type:`text`,text:[`Removed the stored credentials:`,...[...r].map(([e,n])=>`- "${t.find(t=>t.relativePath===e)?.name??e}" (${e}): ${n.sort().join(`, `)}`),``,`This server no longer sends them. The next call that an API rejects with HTTP 401 asks the user for new credentials.`].join(`
4
- `)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(t,e.metadata)),isAvailable:async e=>!a(`removeApiCredentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
4
+ `)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(t,e.metadata)),isAvailable:async e=>!a(`remove-api-credentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
@@ -1 +1 @@
1
- import{CALL_API_WRITE_TOOL_NAME as e,CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r,LIST_WORKFLOWS_TOOL_NAME as i}from"../constants.js";import{isObject as a}from"../../../../../shared/utils/is-object.js";import{formatError as o}from"./tool-errors.js";import{auditToolCall as s,callAttribution as c}from"./audit.js";import{CODE_MODE_TOOL_NAMES as l,FETCH_TOOL_NAME as u}from"./codemode/constants.js";import{resolveMcpMode as d,resolveRequestMcpMode as f}from"./mode.js";import{sendMcpRequestError as p}from"./mcp-telemetry.js";import{availableTools as m,isToolAvailable as h,normalizeToolDisplayName as g}from"./tool-registry.js";import{mcpJsonSchemaValidator as _}from"./json-schema-validator.js";import{toToolListEntries as v}from"./codemode/tool-list.js";import{buildCodeModeInstructions as y,buildExecuteDescription as b,buildToolsModeInstructions as x}from"./codemode/prompts.js";import{composeExecuteAnnotations as S,getActiveCapabilities as C}from"./codemode/capabilities.js";import{discover as w,discoverSchema as T}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as E,executeOutputSchema as D,executeToolTitle as O}from"./codemode/execute-schema.js";import{runCodeMode as k}from"./codemode/index.js";import{docsServerInfo as A}from"./server-info.js";import{loadSkillResources as j}from"./skills-resources.js";import{randomUUID as M}from"node:crypto";import{McpServer as N,createMcpHandler as P,fromJsonSchema as F,isCallToolResult as I,isInputRequiredResult as L}from"@modelcontextprotocol/server";const R=`text/markdown`,z={listChanged:!1};function B(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=g(e);return{title:t,description:n,inputSchema:F(r,_),outputSchema:i?F(i,_):void 0,annotations:a,_meta:o}}function V(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function H(e,t){if(I(e)||L(e))return e;let n=[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e)}];return t===`code`&&a(e)?{content:n,structuredContent:e}:{content:n}}function U(e,t){return(n,r)=>s(e,t.schema.name,n,async()=>H(await t.execute(n,e,{serverContext:r}),e.mcpMode))}function W(e,t){return new N(e,{capabilities:{logging:{},tools:z},maxToolInputElements:1e4,instructions:t})}async function G(a,o,c){let[d,f]=await Promise.all([m(c,o),C(o)]),p=f.some(e=>e.id===u),g=d.some(({schema:t})=>t.name===e),_=d.some(({schema:e})=>e.name===i),x=d.filter(e=>!l.has(e.schema.name)).map(e=>e.schema),A=d.filter(({schema:e})=>l.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),j=o.instructionsStyle!==`brief`,M=j?v(x,f):[],N=A.some(e=>e.schema.name===t),P=W(a,y({hasFetch:p,toolList:M,docsUrl:a.websiteUrl,hasCallApiWrite:g,hasWorkflows:_})),F=S(x,f);P.registerTool(r,B({...V(N,E),title:O(F),description:b(p,M,a.websiteUrl),outputSchema:D(p),annotations:F}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,i=t=>s(o,r,e,()=>k({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:c,ctx:o,hostFetch:t}));if(!p)return i();let{runExecuteWithGateway:a}=await import(`./gateway/index.js`);return a({ctx:o,sessionHandle:n,serverContext:t,run:i})});let I=w(x,async e=>{let t=c.get(e);return t!==void 0&&await h(t,o)},f,o);P.registerTool(n,B(T(x,f,j)),e=>s(o,n,e,()=>I(e)));for(let e of A)P.registerTool(e.schema.name,B(V(N,e.schema)),U(o,e));return P}async function K(e,t,n){let r=new Map((await m(n,t)).map(e=>[e.schema.name,e])),i=W(e,x(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,B({...n.schema,outputSchema:void 0}),U(t,n));r.has(n.schema.name)||a.disable()}return i}async function q(e,t,n){let r=A(e.config,e.request),i=e.mcpMode===`code`?await G(r,e,t):await K(r,e,t);n.length>0&&i.server.registerCapabilities({resources:z});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:R},async()=>({contents:[{uri:e.uri,mimeType:R,text:await e.read()}]}));return i}function J(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function Y(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function X(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await j(n),i=await q(n,e.registry,r),a=P(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),J(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?c(n):{requestId:M()};e.logger?.error(`MCP request failed: ${o(r)}`,{request_id:i.requestId}),await p(r,f(t.url,d()),{logger:e.logger,caller:i})}return Y()}}}export{X as createMcpRequestHandler,B as toRegisterToolConfig};
1
+ import{CALL_API_WRITE_TOOL_NAME as e,CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r,LIST_WORKFLOWS_TOOL_NAME as i,RUN_WORKFLOW_WRITE_TOOL_NAME as a}from"../constants.js";import{isObject as o}from"../../../../../shared/utils/is-object.js";import{formatError as s}from"./tool-errors.js";import{auditToolCall as c,callAttribution as l}from"./audit.js";import{CODE_MODE_TOOL_NAMES as u,FETCH_TOOL_NAME as d}from"./codemode/constants.js";import{resolveMcpMode as f,resolveRequestMcpMode as p}from"./mode.js";import{sendMcpRequestError as m}from"./mcp-telemetry.js";import{availableTools as h,isToolAvailable as g,normalizeToolDisplayName as _}from"./tool-registry.js";import{mcpJsonSchemaValidator as v}from"./json-schema-validator.js";import{toToolListEntries as y}from"./codemode/tool-list.js";import{buildCodeModeInstructions as b,buildExecuteDescription as x,buildToolsModeInstructions as S}from"./codemode/prompts.js";import{composeExecuteAnnotations as C,getActiveCapabilities as w}from"./codemode/capabilities.js";import{discover as T,discoverSchema as E}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as D,executeOutputSchema as O,executeToolTitle as k}from"./codemode/execute-schema.js";import{runCodeMode as A}from"./codemode/index.js";import{docsServerInfo as j}from"./server-info.js";import{loadSkillResources as M}from"./skills-resources.js";import{randomUUID as N}from"node:crypto";import{McpServer as P,createMcpHandler as F,fromJsonSchema as I,isCallToolResult as L,isInputRequiredResult as R}from"@modelcontextprotocol/server";const z=`text/markdown`,B={listChanged:!1};function V(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=_(e);return{title:t,description:n,inputSchema:I(r,v),outputSchema:i?I(i,v):void 0,annotations:a,_meta:o}}function H(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function U(e,t){if(L(e)||R(e))return e;let n=[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e)}];return t===`code`&&o(e)?{content:n,structuredContent:e}:{content:n}}function W(e,t){return(n,r)=>c(e,t.schema.name,n,async()=>U(await t.execute(n,e,{serverContext:r}),e.mcpMode))}function G(e,t){return new P(e,{capabilities:{logging:{},tools:B},maxToolInputElements:1e4,instructions:t})}async function K(o,s,l){let[f,p]=await Promise.all([h(l,s),w(s)]),m=p.some(e=>e.id===d),_=f.some(({schema:t})=>t.name===e),v=f.some(({schema:e})=>e.name===i),S=f.some(({schema:e})=>e.name===a),j=f.filter(e=>!u.has(e.schema.name)).map(e=>e.schema),M=f.filter(({schema:e})=>u.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),N=s.instructionsStyle!==`brief`,P=N?y(j,p):[],F=M.some(e=>e.schema.name===t),I=G(o,b({hasFetch:m,toolList:P,docsUrl:o.websiteUrl,hasCallApiWrite:_,hasWorkflows:v,hasRunWorkflowWrite:S})),L=C(j,p);I.registerTool(r,V({...H(F,D),title:k(L),description:x(m,P,o.websiteUrl),outputSchema:O(m),annotations:L}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,i=t=>c(s,r,e,()=>A({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:l,ctx:s,hostFetch:t}));if(!m)return i();let{runExecuteWithGateway:a}=await import(`./gateway/index.js`);return a({ctx:s,sessionHandle:n,serverContext:t,run:i})});let R=T(j,async e=>{let t=l.get(e);return t!==void 0&&await g(t,s)},p,s);I.registerTool(n,V(E(j,p,N)),e=>c(s,n,e,()=>R(e)));for(let e of M)I.registerTool(e.schema.name,V(H(F,e.schema)),W(s,e));return I}async function q(e,t,n){let r=new Map((await h(n,t)).map(e=>[e.schema.name,e])),i=G(e,S(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,V({...n.schema,outputSchema:void 0}),W(t,n));r.has(n.schema.name)||a.disable()}return i}async function J(e,t,n){let r=j(e.config,e.request),i=e.mcpMode===`code`?await K(r,e,t):await q(r,e,t);n.length>0&&i.server.registerCapabilities({resources:B});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:z},async()=>({contents:[{uri:e.uri,mimeType:z,text:await e.read()}]}));return i}function Y(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function X(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function Z(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await M(n),i=await J(n,e.registry,r),a=F(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),Y(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?l(n):{requestId:N()};e.logger?.error(`MCP request failed: ${s(r)}`,{request_id:i.requestId}),m(r,p(t.url,f()),{logger:e.logger,caller:i})}return X()}}}export{Z as createMcpRequestHandler,V as toRegisterToolConfig};
@@ -1 +1 @@
1
- import{MCP_CALLBACK_ROUTE as e}from"../../constants.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{getSessionIssuer as o}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as s}from"../../../../../../server/plugin-context.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(i(p.config)||!r(a(p.config)))return s();let m=o(f);if(!m)return s();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);await l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${e}/${O}`});return f.redirect(`${n(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
1
+ import{MCP_CALLBACK_ROUTE as e}from"../../constants.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{getSessionIssuer as o}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as s}from"../../../../../../server/plugin-context.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(i(p.config)||!r(a(p.config)))return s();let m=o(f);if(!m)return s();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);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{getBearerVerifier as n,getSessionIssuer as r}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as i}from"../../../../../../server/plugin-context.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,r){let i=new URL(e.req.url),a=w(e,t),o=a?await n(e)?.(a):null;return{method:e.req.method,path:`${i.pathname}${i.search}`,referer:e.req.header(`referer`)??null,user_agent:r.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 i();let l=r(o);if(!l)return i();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 n(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
+ import{isMcpHidden as e}from"../config-gate.js";import{REALM_SESSION_COOKIE as t}from"../../../../../../server/auth/constants.js";import{getBearerVerifier as n,getSessionIssuer as r}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as i}from"../../../../../../server/plugin-context.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,r){let i=new URL(e.req.url),a=w(e,t),o=a?await n(e)?.(a):null;return{method:e.req.method,path:`${i.pathname}${i.search}`,referer:e.req.header(`referer`)??null,user_agent:r.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 i();let l=r(o);if(!l)return i();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 n(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),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,2 +1,2 @@
1
1
  import{auditInput as e,auditStack as t}from"../audit.js";import{sendMcpAuthorizationFailed as n}from"../mcp-telemetry.js";import{randomUUID as r}from"node:crypto";function i(e){return e instanceof Error?e.name===`Error`?{message:e.message,details:e.stack?t(e.stack):null}:{message:e.name,details:null}:{message:String(e),details:null}}function a(n){if(!(n instanceof Error))return i(n);let r=e=>e.split(`
2
- `,1)[0],a=n;for(;a.cause instanceof Error;)a=a.cause;let o=r(n.name===`Error`?n.message:`${n.name}: ${n.message}`),s=a===n?``:` (${r(a.message)})`;return{message:e(`${o}${s}`),details:n.stack?t(n.stack):null}}async function o(e,t,a={}){let{sessionId:o,logFields:s}=a,c=r(),l=typeof t==`string`?{message:t,details:null}:i(t),u=a.message??l.message,d=a.details===void 0?l.details:a.details,f=a.errorClass??(typeof t==`string`?`client_error`:`server_error`),p={request_id:c,mcp_session_id:o,...s};return typeof t==`string`?e.logger?.warn(a.logMessage??`MCP authorization refused`,{...p,error:u}):e.logger?.error(a.logMessage??`MCP authorization failed`,{...p,...d===null?{error:u}:{err:t}}),await n(o,f,u,d,{logger:e.logger,caller:{requestId:c,clientIp:e.request.ip??void 0}}),u}async function s(e,t,n,r,i){return await o(t,r,{sessionId:e.get(`realmMcpSessionId`),logMessage:i}),e.json({error:n,error_description:r},400)}function c(e,t){return async(n,r)=>{try{return await e(n,r)}catch(e){if(e instanceof Error&&`getResponse`in e)throw e;return await o(r,e,{...a(e),sessionId:n.get(`realmMcpSessionId`)}),t(n)}}}export{s as refuseMcpOAuth,o as reportMcpAuthorizationFailure,c as withMcpFailureReporting};
2
+ `,1)[0],a=n;for(;a.cause instanceof Error;)a=a.cause;let o=r(n.name===`Error`?n.message:`${n.name}: ${n.message}`),s=a===n?``:` (${r(a.message)})`;return{message:e(`${o}${s}`),details:n.stack?t(n.stack):null}}async function o(e,t,a={}){let{sessionId:o,logFields:s}=a,c=r(),l=typeof t==`string`?{message:t,details:null}:i(t),u=a.message??l.message,d=a.details===void 0?l.details:a.details,f=a.errorClass??(typeof t==`string`?`client_error`:`server_error`),p={request_id:c,mcp_session_id:o,...s};return typeof t==`string`?e.logger?.warn(a.logMessage??`MCP authorization refused`,{...p,error:u}):e.logger?.error(a.logMessage??`MCP authorization failed`,{...p,...d===null?{error:u}:{err:t}}),n(o,f,u,d,{logger:e.logger,caller:{requestId:c,clientIp:e.request.ip??void 0}}),u}async function s(e,t,n,r,i){return await o(t,r,{sessionId:e.get(`realmMcpSessionId`),logMessage:i}),e.json({error:n,error_description:r},400)}function c(e,t){return async(n,r)=>{try{return await e(n,r)}catch(e){if(e instanceof Error&&`getResponse`in e)throw e;return await o(r,e,{...a(e),sessionId:n.get(`realmMcpSessionId`)}),t(n)}}}export{s as refuseMcpOAuth,o as reportMcpAuthorizationFailure,c as withMcpFailureReporting};
@@ -1 +1 @@
1
- import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),await t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),m(a,e.headers??{})}export{h as applyMcpRateLimit,p as checkMcpRateLimit,u as ipRateLimitKey};
1
+ import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),m(a,e.headers??{})}export{h as applyMcpRateLimit,p as checkMcpRateLimit,u as ipRateLimitKey};
@@ -1 +1 @@
1
- import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{notFoundResponse as o}from"../../../../../server/plugin-context.js";import{publicBaseUrl as s,publicOrigin as c}from"../../../utils/request-origin.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(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":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function D(r,i){let a=await r.withViewer(n),o=await g(a,{isProtected:i},Date.now()+f,{onError:e=>E(r,e)}),s=new URL(t(e),c(r.request)).href,[l,u]=await Promise.all([T(o,s,`server/discover`),i?void 0:T(o,s,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:C};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:C}}async function O(n,c){if(i(c.config))return o();n.set(`realmCacheControlOwned`,!0);let l=await h({kv:c.kv,ip:c.request.ip,bucket:`card`,headers:u,logger:c.logger});if(l)return l;let f=_(c.config,c.request),g=r(a(c.config)),v=await D(c,g).catch(e=>{E(c,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return await m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:c.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:s(c.config,c.request),transport:{type:`streamable-http`,endpoint:t(e)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
1
+ import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{notFoundResponse as o}from"../../../../../server/plugin-context.js";import{publicBaseUrl as s,publicOrigin as c}from"../../../utils/request-origin.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(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":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function D(r,i){let a=await r.withViewer(n),o=await g(a,{isProtected:i},Date.now()+f,{onError:e=>E(r,e)}),s=new URL(t(e),c(r.request)).href,[l,u]=await Promise.all([T(o,s,`server/discover`),i?void 0:T(o,s,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:C};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:C}}async function O(n,c){if(i(c.config))return o();n.set(`realmCacheControlOwned`,!0);let l=await h({kv:c.kv,ip:c.request.ip,bucket:`card`,headers:u,logger:c.logger});if(l)return l;let f=_(c.config,c.request),g=r(a(c.config)),v=await D(c,g).catch(e=>{E(c,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:c.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:s(c.config,c.request),transport:{type:`streamable-http`,endpoint:t(e)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{OPERATION_METHODS as t}from"../../../../../../shared/constants/openapi-operation-methods.js";import{withoutTrailingSlashes as n}from"../tools/openapi-document.js";import{operationHttpMethod as r,pathTemplateKey as i}from"../gateway/route-pattern.js";import{findUnresolvedPlaceholders as a}from"../gateway/fetch/url-placeholders.js";import{SOURCE_REFERENCE as o,UnsupportedWorkflowError as s,failureActionsOf as c,localWorkflowId as l,referencedWorkflowIds as u,successActionsOf as d}from"./workflow-references.js";import{definitionForOperations as f}from"./operations-subset.js";import{stepKey as p}from"./types.js";import{posix as m}from"node:path";import{replaceServerVariables as h}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";import{resolveRef as g}from"@redocly/api-docs/lib/utils/inline-openapi-refs.js";const _=/^\{\$sourceDescriptions\.([\w.-]+)\.url\}#(\/.+)$/,v=/^([\w-]+)\.(.+)$/,y=/^[a-z][a-z0-9+.-]*:/i,b=/^https?:\/\//i,x=/\$components\.(\w+)\.([\w.-]+)/g,S=/\b(?:match|search)\s*\(/,C=[`multipart/form-data`,`application/octet-stream`],w=new Set(t);function T(e){let{filePath:t,document:n}=e,r=E(e),i=new Map((n.workflows??[]).map(e=>[e.workflowId,e])),a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let t of i.values())try{if(R(t,n.components))throw new s(`it generates test data with $faker`);for(let n of t.steps??[]){let i=A(n,t,r,e);i&&a.set(p(t.workflowId,n.stepId),i)}for(let e of u(t,n.components))V(e,r)}catch(e){if(!(e instanceof s))throw e;o.set(t.workflowId,e.message)}H(i,o),G(i,n.components,o);let c=/* @__PURE__ */ new Map;for(let e of i.values())o.has(e.workflowId)||c.set(e.workflowId,{workflow:e,inputs:K(e,i),methods:q(e,i,n.components,a)});return{filePath:t,title:n.info?.title??m.basename(t),document:n,sources:D(n,r,[...a.values()]),operations:a,runnable:c,unsupported:o}}function E({filePath:e,document:t,apis:n}){let r=/* @__PURE__ */ new Map;for(let i of t.sourceDescriptions??[]){let t=k(e,i.url);if(t){if(i.type===`arazzo`&&t===e)r.set(i.name,{kind:`self`});else if(i.type===`openapi`&&!i[`x-serverUrl`]){let e=n.find(e=>e.relativePath===t);e&&r.set(i.name,{kind:`api`,api:e})}}}return r}function D(e,t,n){let r=/* @__PURE__ */ new Map;for(let{name:i,type:a}of e.sourceDescriptions??[]){let e=t.get(i);if(e?.kind!==`self`){if(e?.kind===`api`){let{definition:t,servers:a}=e.api,o=n.filter(e=>e.sourceName===i);r.set(i,{...f(t,o),servers:[...a]})}else r.set(i,O(a,i))}}return r}function O(e,t){let n={title:t,version:`0`};return e===`arazzo`?{arazzo:`1.0.1`,info:n,sourceDescriptions:[],workflows:[]}:{openapi:`3.1.0`,info:n,paths:{}}}function k(e,t){if(!(y.test(t)||t.startsWith(`/`)))return m.normalize(m.join(m.dirname(e),t))}function A(e,t,n,a){if(L(e,t,a.document.components),c(e,t,a.document.components).some(B))throw new s(`step "${e.stepId}" waits more than 5 seconds before a retry`);if(e.workflowId)return;let o=j(e,n);if(!o)throw new s(`step "${e.stepId}" calls no operation of a callable API`);let{sourceName:l,api:u,path:d,method:f,operation:p}=o,m=r(f),h=i(d),g=u.operations.find(e=>e.method===m&&i(e.path)===h);if(!g?.callable||!g.visible)throw new s(`step "${e.stepId}" calls ${m} ${d}, which agents cannot call`);if(!a.allowedHttpMethods.includes(m))throw new s(`step "${e.stepId}" sends ${m}, which this project does not allow`);let _=e.requestBody?.contentType??F(p,u.definition);if(e.requestBody&&_&&C.some(e=>_.includes(e)))throw new s(`step "${e.stepId}" sends ${_}, which workflows cannot send`);if(!I(u))throw new s(`step "${e.stepId}" calls an API without an absolute server URL`);return{sourceName:l,method:m,operationKey:f,path:d}}function j(e,t){if(e.operationPath)return M(e.operationPath,t);if(!e.operationId)return;let n=o.exec(e.operationId)??v.exec(e.operationId),r=n?[[n[1],t.get(n[1])]]:[...t],i=n?n[2]:e.operationId,a=r.flatMap(([e,t])=>t?.kind===`api`?N(e,t.api,i):[]);return a.length===1?a[0]:void 0}function M(e,t){let n=_.exec(e),r=n&&t.get(n[1]);if(!n||r?.kind!==`api`)return;let i=n[2].slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`));if(i.length!==3||i[0]!==`paths`)return;let[,a,o]=i,s=P(r.api,a,o);return s&&{sourceName:n[1],api:r.api,path:a,method:o,operation:s}}function N(t,n,r){return Object.entries(n.definition.paths??{}).flatMap(([i,a])=>Object.keys(e(a)?a:{}).flatMap(e=>{let a=P(n,i,e);return a?.operationId===r?[{sourceName:t,api:n,path:i,method:e,operation:a}]:[]}))}function P(t,n,r){if(!w.has(r.toLowerCase()))return;let i=t.definition.paths?.[n],a=e(i)?i[r]:void 0;return e(a)?a:void 0}function F(t,n){let r=t.requestBody,i=r&&`$ref`in r&&r.$ref?g(r.$ref,n):r,a=e(i)?i.content:void 0;return e(a)?Object.keys(a)[0]:void 0}function I(e){let[t]=e.servers;if(!t)return!1;let r=n(h(t));return b.test(r)&&a(r).length===0}function L(e,t,n){let r=[...d(e,t,n),...c(e,t,n)],i=[...e.successCriteria??[],...r.flatMap(e=>e.criteria??[])];for(let{type:t,condition:n}of i){let r=typeof t==`object`?t.type:t;if(r===`xpath`)throw new s(`step "${e.stepId}" checks an XPath criterion, which workflows cannot evaluate`);if(r===`regex`||r===`jsonpath`&&S.test(n))throw new s(`step "${e.stepId}" checks a regex, which workflows cannot evaluate safely`)}}function R(e,t){let n=JSON.stringify(e);return[n,...[...n.matchAll(x)].map(([,e=``,n=``])=>JSON.stringify(z(t,e,n))??``)].some(e=>e.includes(`$faker`))}function z(t,n,r){let i=t,a=e(i)?i[n]:void 0;return e(a)?a[r]:void 0}function B(e){return e.type===`retry`&&(e.retryAfter??0)>5}function V(e,t){let n=o.exec(e);if(n&&t.get(n[1])?.kind!==`self`)throw new s(`it uses workflow "${e}" of another file`)}function H(e,t){for(let n of e.values()){let r=U(n,e);r&&!t.has(n.workflowId)&&t.set(n.workflowId,`it calls itself through workflow "${r}"`)}}function U(e,t){for(let n of W(e)){let r=/* @__PURE__ */ new Set,i=[n];for(;i.length>0;){let a=i.pop();if(a===e.workflowId)return n;if(r.has(a))continue;r.add(a);let o=t.get(a);o&&i.push(...W(o))}}}function W(e){let t=(e.steps??[]).flatMap(e=>e.workflowId?[l(e.workflowId)]:[]);return[...(e.dependsOn??[]).map(l),...t]}function G(e,t,n){let r=!0;for(;r;){r=!1;for(let i of e.values()){if(n.has(i.workflowId))continue;let a=u(i,t).map(l).find(t=>!e.has(t)||n.has(t));a!==void 0&&(n.set(i.workflowId,`it uses workflow "${a}", which cannot run`),r=!0)}}}function K(e,t){let n={},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=e=>{if(!i.has(e.workflowId)){i.add(e.workflowId);for(let[t,r]of Object.entries(e.inputs?.properties??{}))t in n||(n[t]=r);for(let t of e.inputs?.required??[])r.add(t);for(let n of e.dependsOn??[]){let e=t.get(l(n));e&&a(e)}}};return a(e),r.size>0?{type:`object`,properties:n,required:[...r]}:{type:`object`,properties:n}}function q(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[e];for(;o.length>0;){let e=o.pop();if(!a.has(e.workflowId)){a.add(e.workflowId);for(let t of e.steps??[]){let n=r.get(p(e.workflowId,t.stepId))?.method;n&&i.add(n)}for(let r of u(e,n)){let e=t.get(l(r));e&&o.push(e)}}}return[...i].sort()}export{T as resolveArazzoFile,k as sourceDescriptionPath};
1
+ import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{OPERATION_METHODS as t}from"../../../../../../shared/constants/openapi-operation-methods.js";import{withoutTrailingSlashes as n}from"../tools/openapi-document.js";import{operationHttpMethod as r,pathTemplateKey as i}from"../gateway/route-pattern.js";import{findUnresolvedPlaceholders as a}from"../gateway/fetch/url-placeholders.js";import{SOURCE_REFERENCE as o,UnsupportedWorkflowError as s,failureActionsOf as c,localWorkflowId as l,referencedWorkflowIds as u,successActionsOf as d}from"./workflow-references.js";import{definitionForOperations as f}from"./operations-subset.js";import{stepKey as p}from"./types.js";import{posix as m}from"node:path";import{replaceServerVariables as h}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";import{resolveRef as g}from"@redocly/api-docs/lib/utils/inline-openapi-refs.js";const _=/^\{\$sourceDescriptions\.([\w.-]+)\.url\}#(\/.+)$/,v=/^([\w-]+)\.(.+)$/,y=/^[a-z][a-z0-9+.-]*:/i,b=/^https?:\/\//i,x=/\$components\.(\w+)\.([\w.-]+)/g,S=/\b(?:match|search)\s*\(/,C=[`multipart/form-data`,`application/octet-stream`],w=new Set(t);function T(e){let{filePath:t,document:n}=e,r=E(e),i=new Map((n.workflows??[]).map(e=>[e.workflowId,e])),a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let t of i.values())try{if(R(t,n.components))throw new s(`it generates test data with $faker`);for(let n of t.steps??[]){let i=A(n,t,r,e);i&&a.set(p(t.workflowId,n.stepId),i)}for(let e of u(t,n.components))V(e,r)}catch(e){if(!(e instanceof s))throw e;o.set(t.workflowId,e.message)}H(i,o),G(i,n.components,o);let c=/* @__PURE__ */ new Map;for(let e of i.values())o.has(e.workflowId)||c.set(e.workflowId,{workflow:e,inputs:K(e,i),methods:q(e,i,n.components,a)});return{filePath:t,title:n.info?.title??m.basename(t),document:n,sources:D(n,r,[...a.values()]),operations:a,runnable:c,unsupported:o}}function E({filePath:e,document:t,apis:n}){let r=/* @__PURE__ */ new Map;for(let i of t.sourceDescriptions??[]){let t=k(e,i.url);if(t){if(i.type===`arazzo`&&t===e)r.set(i.name,{kind:`self`});else if(i.type===`openapi`&&!i[`x-serverUrl`]){let e=n.find(e=>e.relativePath===t);e&&r.set(i.name,{kind:`api`,api:e})}}}return r}function D(e,t,n){let r=/* @__PURE__ */ new Map;for(let{name:i,type:a}of e.sourceDescriptions??[]){let e=t.get(i);if(e?.kind!==`self`){if(e?.kind===`api`){let{definition:t,servers:a}=e.api,o=n.filter(e=>e.sourceName===i);r.set(i,{...f(t,o),servers:[...a]})}else r.set(i,O(a,i))}}return r}function O(e,t){let n={title:t,version:`0`};return e===`arazzo`?{arazzo:`1.0.1`,info:n,sourceDescriptions:[],workflows:[]}:{openapi:`3.1.0`,info:n,paths:{}}}function k(e,t){if(!(y.test(t)||t.startsWith(`/`)))return m.normalize(m.join(m.dirname(e),t))}function A(e,t,n,a){if(L(e,t,a.document.components),c(e,t,a.document.components).some(B))throw new s(`step "${e.stepId}" waits more than 5 seconds before a retry`);if(e.workflowId)return;if(e[`x-operation`])throw new s(`step "${e.stepId}" calls an x-operation URL, not a documented operation`);let o=j(e,n);if(!o)throw new s(`step "${e.stepId}" calls no operation of a callable API`);let{sourceName:l,api:u,path:d,method:f,operation:p}=o,m=r(f),h=i(d),g=u.operations.find(e=>e.method===m&&i(e.path)===h);if(!g?.callable||!g.visible)throw new s(`step "${e.stepId}" calls ${m} ${d}, which agents cannot call`);if(!a.allowedHttpMethods.includes(m))throw new s(`step "${e.stepId}" sends ${m}, which this project does not allow`);let _=e.requestBody?.contentType??F(p,u.definition);if(e.requestBody&&_&&C.some(e=>_.includes(e)))throw new s(`step "${e.stepId}" sends ${_}, which workflows cannot send`);if(!I(u))throw new s(`step "${e.stepId}" calls an API without an absolute server URL`);return{sourceName:l,method:m,operationKey:f,path:d}}function j(e,t){if(e.operationPath)return M(e.operationPath,t);if(!e.operationId)return;let n=o.exec(e.operationId)??v.exec(e.operationId),r=n?[[n[1],t.get(n[1])]]:[...t],i=n?n[2]:e.operationId,a=r.flatMap(([e,t])=>t?.kind===`api`?N(e,t.api,i):[]);return a.length===1?a[0]:void 0}function M(e,t){let n=_.exec(e),r=n&&t.get(n[1]);if(!n||r?.kind!==`api`)return;let i=n[2].slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`));if(i.length!==3||i[0]!==`paths`)return;let[,a,o]=i,s=P(r.api,a,o);return s&&{sourceName:n[1],api:r.api,path:a,method:o,operation:s}}function N(t,n,r){return Object.entries(n.definition.paths??{}).flatMap(([i,a])=>Object.keys(e(a)?a:{}).flatMap(e=>{let a=P(n,i,e);return a?.operationId===r?[{sourceName:t,api:n,path:i,method:e,operation:a}]:[]}))}function P(t,n,r){if(!w.has(r.toLowerCase()))return;let i=t.definition.paths?.[n],a=e(i)?i[r]:void 0;return e(a)?a:void 0}function F(t,n){let r=t.requestBody,i=r&&`$ref`in r&&r.$ref?g(r.$ref,n):r,a=e(i)?i.content:void 0;return e(a)?Object.keys(a)[0]:void 0}function I(e){let[t]=e.servers;if(!t)return!1;let r=n(h(t));return b.test(r)&&a(r).length===0}function L(e,t,n){let r=[...d(e,t,n),...c(e,t,n)],i=[...e.successCriteria??[],...r.flatMap(e=>e.criteria??[])];for(let{type:t,condition:n}of i){let r=typeof t==`object`?t.type:t;if(r===`xpath`)throw new s(`step "${e.stepId}" checks an XPath criterion, which workflows cannot evaluate`);if(r===`regex`||r===`jsonpath`&&S.test(n))throw new s(`step "${e.stepId}" checks a regex, which workflows cannot evaluate safely`)}}function R(e,t){let n=JSON.stringify(e);return[n,...[...n.matchAll(x)].map(([,e=``,n=``])=>JSON.stringify(z(t,e,n))??``)].some(e=>e.includes(`$faker`))}function z(t,n,r){let i=t,a=e(i)?i[n]:void 0;return e(a)?a[r]:void 0}function B(e){return e.type===`retry`&&(e.retryAfter??0)>5}function V(e,t){let n=o.exec(e);if(n&&t.get(n[1])?.kind!==`self`)throw new s(`it uses workflow "${e}" of another file`)}function H(e,t){for(let n of e.values()){let r=U(n,e);r&&!t.has(n.workflowId)&&t.set(n.workflowId,`it calls itself through workflow "${r}"`)}}function U(e,t){for(let n of W(e)){let r=/* @__PURE__ */ new Set,i=[n];for(;i.length>0;){let a=i.pop();if(a===e.workflowId)return n;if(r.has(a))continue;r.add(a);let o=t.get(a);o&&i.push(...W(o))}}}function W(e){let t=(e.steps??[]).flatMap(e=>e.workflowId?[l(e.workflowId)]:[]);return[...(e.dependsOn??[]).map(l),...t]}function G(e,t,n){let r=!0;for(;r;){r=!1;for(let i of e.values()){if(n.has(i.workflowId))continue;let a=u(i,t).map(l).find(t=>!e.has(t)||n.has(t));a!==void 0&&(n.set(i.workflowId,`it uses workflow "${a}", which cannot run`),r=!0)}}}function K(e,t){let n={},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=e=>{if(!i.has(e.workflowId)){i.add(e.workflowId);for(let[t,r]of Object.entries(e.inputs?.properties??{}))t in n||(n[t]=r);for(let t of e.inputs?.required??[])r.add(t);for(let n of e.dependsOn??[]){let e=t.get(l(n));e&&a(e)}}};return a(e),r.size>0?{type:`object`,properties:n,required:[...r]}:{type:`object`,properties:n}}function q(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[e];for(;o.length>0;){let e=o.pop();if(!a.has(e.workflowId)){a.add(e.workflowId);for(let t of e.steps??[]){let n=r.get(p(e.workflowId,t.stepId))?.method;n&&i.add(n)}for(let r of u(e,n)){let e=t.get(l(r));e&&o.push(e)}}}return[...i].sort()}export{T as resolveArazzoFile,k as sourceDescriptionPath};
@@ -1 +1,2 @@
1
- import{GET_WORKFLOW_TOOL_NAME as e,LIST_WORKFLOWS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,RUN_WORKFLOW_TOOL_NAME as r}from"../../constants.js";const i={type:`string`,nullable:!0},a={workflowId:{type:`string`,description:"The `workflowId` from `listWorkflows`."},filePath:{...i,description:"The `filePath` from `listWorkflows`. Needed only when several files declare the workflow ID."}},o={workflowId:{type:`string`},filePath:{type:`string`,description:`The Arazzo description that declares the workflow.`},summary:i,description:i,writes:{type:`boolean`,description:`True when a step can change data. Confirm with the user before such a run.`},inputs:{type:`object`,description:"The JSON Schema of the `inputs` that `runWorkflow` takes."}},s={name:t,title:`List API workflows`,description:'Lists the workflows that `runWorkflow` can run. Each workflow is a ready-made multi-step API action that the docs authors wrote, such as "log in, then place an order". When a workflow matches the task, run it instead of chaining `fetch` calls: it already knows the order of the calls and how data passes between them.',summary:`List the multi-step API workflows you can run.`,annotations:n,schema:{type:`object`,required:[],additionalProperties:!1,properties:{filter:{...i,description:`Case-insensitive text to find in the workflow ID, summary, or description.`}}},outputSchema:{type:`object`,required:[`items`],properties:{items:{type:`array`,items:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`],properties:o}}}}},c={name:e,title:`Get an API workflow`,description:"Gets one workflow from `listWorkflows`: its inputs, outputs, and the request or sub-workflow of each step. Use it to explain a workflow to the user before you run it. For a workflow that cannot run, the error says why.",summary:`Get the inputs, steps, and outputs of one workflow.`,annotations:n,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:a},outputSchema:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`,`outputs`,`steps`],properties:{...o,outputs:{type:`array`,items:{type:`string`},description:"The names of the `outputs` a successful run returns."},steps:{type:`array`,items:{type:`object`,required:[`stepId`],properties:{stepId:{type:`string`},description:i,request:{...i,description:"The method and the path, such as `POST /orders`."},workflowId:{...i,description:`The sub-workflow the step runs.`}}}}}}},l={name:r,title:`Run an API workflow`,description:'Runs one workflow from `listWorkflows` with its `inputs`, and returns its `outputs` and one `steps` entry per request. Each request goes through `fetch`: the same documented operations, hosts, stored credentials, and limits. A run that fails returns `status: "failed"` with the failed step and its response. The requests in `steps` already reached the API, so do not run a workflow that writes again without asking the user.',summary:`Run a multi-step API workflow with its inputs.`,annotations:{...n,openWorldHint:!0},schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:{...a,inputs:{type:`object`,nullable:!0,description:"The workflow inputs; their JSON Schema is `inputs` in `listWorkflows`."}}},outputSchema:{type:`object`,required:[`workflowId`,`status`,`steps`],properties:{workflowId:{type:`string`},status:{type:`string`,enum:[`succeeded`,`failed`]},outputs:{type:`object`,nullable:!0},steps:{type:`array`,items:{type:`object`,required:[`stepId`,`ms`],properties:{stepId:{type:`string`},workflowId:{...i,description:`Set for a step of a sub-workflow or a dependency.`},request:i,status:{type:`number`,nullable:!0},ms:{type:`number`},error:{...i,description:`Why the request did not reach the API.`}}}},failure:{type:`object`,nullable:!0,required:[`workflowId`,`reason`],properties:{workflowId:{type:`string`},stepId:i,reason:{type:`string`},response:{type:`object`,nullable:!0,required:[`status`,`body`],properties:{status:{type:`number`},body:{type:`string`}}}}}}}};export{c as GET_WORKFLOW_SCHEMA,s as LIST_WORKFLOWS_SCHEMA,l as RUN_WORKFLOW_SCHEMA};
1
+ import{GET_WORKFLOW_TOOL_NAME as e,LIST_WORKFLOWS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REQUIRES_USER_INTERACTION_META as r,RUN_WORKFLOW_TOOL_NAME as i,RUN_WORKFLOW_WRITE_TOOL_NAME as a,WRITE_TOOL_ANNOTATIONS as o}from"../../constants.js";import{SESSION_HANDLE_PROPERTY as s}from"../gateway/tools.js";const c={type:`string`,nullable:!0},l={workflowId:{type:`string`,description:"The `workflowId` from `listWorkflows`."},filePath:{...c,description:"The `filePath` from `listWorkflows`. Needed only when several files declare the workflow ID."}},u={workflowId:{type:`string`},filePath:{type:`string`,description:`The Arazzo description that declares the workflow.`},summary:c,description:c,writes:{type:`boolean`,description:`True when a step can change data. Such a workflow does not run inside \`execute\`; it runs through the \`${a}\` tool.`},inputs:{type:`object`,description:"The JSON Schema of the `inputs` that `runWorkflow` takes."}},d={name:t,title:`List API workflows`,description:'Lists the workflows that `runWorkflow` can run. Each workflow is a ready-made multi-step API action that the docs authors wrote, such as "log in, then place an order". When a workflow matches the task, run it instead of chaining `fetch` calls: it already knows the order of the calls and how data passes between them.',summary:`List the multi-step API workflows you can run.`,annotations:n,schema:{type:`object`,required:[],additionalProperties:!1,properties:{filter:{...c,description:`Case-insensitive text to find in the workflow ID, summary, or description.`}}},outputSchema:{type:`object`,required:[`items`],properties:{items:{type:`array`,items:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`],properties:u}}}}},f={name:e,title:`Get an API workflow`,description:"Gets one workflow from `listWorkflows`: its inputs, outputs, and the request or sub-workflow of each step. Use it to explain a workflow to the user before you run it. For a workflow that cannot run, the error says why.",summary:`Get the inputs, steps, and outputs of one workflow.`,annotations:n,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:l},outputSchema:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`,`outputs`,`steps`],properties:{...u,outputs:{type:`array`,items:{type:`string`},description:"The names of the `outputs` a successful run returns."},steps:{type:`array`,items:{type:`object`,required:[`stepId`],properties:{stepId:{type:`string`},description:c,request:{...c,description:"The method and the path, such as `POST /orders`."},workflowId:{...c,description:`The sub-workflow the step runs.`}}}}}}},p={...l,inputs:{type:`object`,nullable:!0,description:"The workflow inputs; their JSON Schema is `inputs` in `listWorkflows`."}},m={type:`object`,required:[`workflowId`,`status`,`steps`],properties:{workflowId:{type:`string`},status:{type:`string`,enum:[`succeeded`,`failed`]},outputs:{type:`object`,nullable:!0},steps:{type:`array`,items:{type:`object`,required:[`stepId`,`ms`],properties:{stepId:{type:`string`},workflowId:{...c,description:`Set for a step of a sub-workflow or a dependency.`},request:c,status:{type:`number`,nullable:!0},ms:{type:`number`},error:{...c,description:`Why the request did not reach the API.`}}}},failure:{type:`object`,nullable:!0,required:[`workflowId`,`reason`],properties:{workflowId:{type:`string`},stepId:c,reason:{type:`string`},response:{type:`object`,nullable:!0,required:[`status`,`body`],properties:{status:{type:`number`},body:{type:`string`}}}}}}},h={name:i,title:`Run an API workflow`,description:`Runs one workflow from \`listWorkflows\` that does not write (\`writes: false\`) with its \`inputs\`, and returns its \`outputs\` and one \`steps\` entry per request. Each request goes through \`fetch\`: the same documented operations, hosts, stored credentials, and limits. A run that fails returns \`status: "failed"\` with the failed step and its response. Run a workflow with \`writes: true\` with the \`${a}\` tool.`,summary:`Run a read-only multi-step API workflow with its inputs.`,annotations:{...n,openWorldHint:!0},schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:p},outputSchema:m},g={name:a,title:`Run a workflow that writes`,description:["Runs one workflow from `listWorkflows` that has at least one write step (`writes: true`), with its `inputs`.","Read the workflow with `getWorkflow` in `execute` first.",`Run it only when the user asked for the action. A question about what is possible is not a request to run it.`,"It returns the `outputs` and one `steps` entry per request. Do not run it again after a failure without asking the user."].join(`
2
+ `),annotations:o,_meta:r,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:{...p,sessionHandle:s}},outputSchema:m};export{f as GET_WORKFLOW_SCHEMA,d as LIST_WORKFLOWS_SCHEMA,h as RUN_WORKFLOW_SCHEMA,g as RUN_WORKFLOW_WRITE_SCHEMA};
@@ -1 +1 @@
1
- import{formatCandidates as e}from"../tools/openapi-document.js";import{isSafeHttpMethod as t}from"../gateway/allowed-http-methods.js";import{stepKey as n}from"./types.js";import{hasRunnableWorkflows as r,loadWorkflowCatalog as i}from"./catalog.js";import{runWorkflow as a}from"./run-workflow.js";import{GET_WORKFLOW_SCHEMA as o,LIST_WORKFLOWS_SCHEMA as s,RUN_WORKFLOW_SCHEMA as c}from"./schemas.js";import{Ajv as l,AjvJsonSchemaValidator as u}from"@modelcontextprotocol/server/validators/ajv";const d=new u(new l({allErrors:!0,strict:!1,validateFormats:!1}));function f({methods:e}){return e.some(e=>!t(e))}function p({file:e,runnable:t}){let{workflowId:n,summary:r,description:i}=t.workflow;return{workflowId:n,filePath:e.filePath,summary:r,description:i,writes:f(t),inputs:t.inputs}}function m(e){return e.flatMap(e=>Array.from(e.runnable.values(),t=>({file:e,runnable:t})))}function h({workflowId:t,filePath:n},r){let i=n?r.filter(e=>e.filePath===n):r,a=i.flatMap(e=>{let n=e.runnable.get(t);return n?[{file:e,runnable:n}]:[]});if(a.length===1)return a[0];if(a.length>1)throw Error(`Workflow "${t}" is in several files: ${e(a.map(({file:e})=>`"${e.filePath}"`))}. Pass \`filePath\`.`);let o=i.find(e=>e.unsupported.has(t));if(o)throw Error(`Workflow "${t}" in ${o.filePath} cannot run: ${o.unsupported.get(t)}.`);let s=m(r).map(({runnable:e})=>`"${e.workflow.workflowId}"`);throw Error(`No workflow "${t}"`+(n?` in ${n}`:``)+(s.length>0?`. Available workflows: ${e(s)}.`:`.`))}const g={schema:s,isAvailable:r,async execute(e,t){let n=(e??{}).filter?.trim().toLowerCase(),r=m(await i(t)).map(p);return{items:n?r.filter(e=>[e.workflowId,e.summary,e.description].some(e=>e?.toLowerCase().includes(n))):r}}},_={schema:o,isAvailable:r,async execute(e,t){let r=h(e,await i(t)),{workflow:a}=r.runnable;return{...p(r),outputs:Object.keys(a.outputs??{}),steps:(a.steps??[]).map(e=>{let t=r.file.operations.get(n(a.workflowId,e.stepId));return{stepId:e.stepId,description:e.description,request:t&&`${t.method} ${t.path}`,workflowId:e.workflowId}})}}},v={schema:c,isAvailable:r,async execute(e,t,n){let r=e,{file:o,runnable:s}=h(r,await i(t)),c=r.inputs??{},l=d.getValidator(s.inputs)(c);if(!l.valid)throw Error(`The inputs of workflow "${r.workflowId}" are not valid: ${l.errorMessage}`);let u=n?.gatewayFetch;if(!u)throw Error("`runWorkflow` runs only inside an `execute` script.");return a({file:o,workflowId:r.workflowId,inputs:c,fetch:u,deadline:t.executeDeadline})}};function y(){return[g,_,v]}export{y as workflowTools};
1
+ import{RUN_WORKFLOW_WRITE_TOOL_NAME as e}from"../../constants.js";import{isToolDisabledByCaller as t}from"../disabled-tools.js";import{formatCandidates as n}from"../tools/openapi-document.js";import{getAllowedHttpMethods as r,isSafeHttpMethod as i}from"../gateway/allowed-http-methods.js";import{runExecuteWithGateway as a}from"../gateway/index.js";import{stepKey as o}from"./types.js";import{hasRunnableWorkflows as s,loadWorkflowCatalog as c}from"./catalog.js";import{runWorkflow as l}from"./run-workflow.js";import{GET_WORKFLOW_SCHEMA as u,LIST_WORKFLOWS_SCHEMA as d,RUN_WORKFLOW_SCHEMA as f,RUN_WORKFLOW_WRITE_SCHEMA as p}from"./schemas.js";import{Ajv as m,AjvJsonSchemaValidator as h}from"@modelcontextprotocol/server/validators/ajv";const g=new h(new m({allErrors:!0,strict:!1,validateFormats:!1}));function _({methods:e}){return e.some(e=>!i(e))}function v({file:e,runnable:t}){let{workflowId:n,summary:r,description:i}=t.workflow;return{workflowId:n,filePath:e.filePath,summary:r,description:i,writes:_(t),inputs:t.inputs}}function y(e){return e.flatMap(e=>Array.from(e.runnable.values(),t=>({file:e,runnable:t})))}function b({workflowId:e,filePath:t},r){let i=t?r.filter(e=>e.filePath===t):r,a=i.flatMap(t=>{let n=t.runnable.get(e);return n?[{file:t,runnable:n}]:[]});if(a.length===1)return a[0];if(a.length>1)throw Error(`Workflow "${e}" is in several files: ${n(a.map(({file:e})=>`"${e.filePath}"`))}. Pass \`filePath\`.`);let o=i.find(t=>t.unsupported.has(e));if(o)throw Error(`Workflow "${e}" in ${o.filePath} cannot run: ${o.unsupported.get(e)}.`);let s=y(r).map(({runnable:e})=>`"${e.workflow.workflowId}"`);throw Error(`No workflow "${e}"`+(t?` in ${t}`:``)+(s.length>0?`. Available workflows: ${n(s)}.`:`.`))}const x={schema:d,isAvailable:s,async execute(e,t){let n=(e??{}).filter?.trim().toLowerCase(),r=y(await c(t)).map(v);return{items:n?r.filter(e=>[e.workflowId,e.summary,e.description].some(e=>e?.toLowerCase().includes(n))):r}}},S={schema:u,isAvailable:s,async execute(e,t){let n=b(e,await c(t)),{workflow:r}=n.runnable;return{...v(n),outputs:Object.keys(r.outputs??{}),steps:(r.steps??[]).map(e=>{let t=n.file.operations.get(o(r.workflowId,e.stepId));return{stepId:e.stepId,description:e.description,request:t&&`${t.method} ${t.path}`,workflowId:e.workflowId}})}}};async function C(e,t){let n=b(e,await c(t)),r=e.inputs??{},i=g.getValidator(n.runnable.inputs)(r);if(!i.valid)throw Error(`The inputs of workflow "${e.workflowId}" are not valid: ${i.errorMessage}`);return{...n,inputs:r}}const w={schema:f,isAvailable:s,async execute(n,r,i){let a=n,o=await C(a,r);if(_(o.runnable)){let n=t(`run-workflow_write`,r.metadata)?`Explain the workflow to the user instead of running it.`:`Use the \`${e}\` tool.`;throw Error(`Workflow "${a.workflowId}" was not run. This workflow writes. ${n}`)}let s=i?.gatewayFetch;if(!s)throw Error("`runWorkflow` runs only inside an `execute` script.");return l({file:o.file,workflowId:a.workflowId,inputs:o.inputs,fetch:s,deadline:r.executeDeadline})}},T={schema:p,isAvailable:async e=>y(await c(e)).some(({runnable:e})=>_(e)),async execute(t,n,i){let o=t,s=i?.serverContext;if(!s)throw Error(`\`${e}\` runs only as a top-level tool call.`);let c=await C(o,n);if(!_(c.runnable))throw Error(`Workflow "${o.workflowId}" does not write. Run it with \`site.runWorkflow\` inside \`execute\`.`);return a({ctx:n,sessionHandle:o.sessionHandle,serverContext:s,allowedHttpMethods:r(n.config.mcp),run:async e=>{let t=await l({file:c.file,workflowId:o.workflowId,inputs:c.inputs,fetch:e,deadline:n.executeDeadline});return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:t,isError:t.status===`failed`}}})}};function E(){return[x,S,w]}export{T as runWorkflowWriteTool,E as workflowTools};
@@ -1,4 +1,4 @@
1
- import{CATALOG_CLASSIC_DEP_KEY as e}from"../../catalog-classic/client/contract.js";import"./contract.js";import{AppPageWrapper as t,CardRow as n,CardValue as r,CardsWrapper as i,ContentWithDotWrap as a,LevelComplianceCardTitle as o,LinkButton as s,ModeSwitcherTab as c,ModeSwitcherTabs as l,PageDescription as u,ProblemsByStatusCardBody as d,ScoreCardStatusCardBody as f,ScorecardCard as p,ScorecardCardTitle as m,TableWrap as h}from"./styles.js";import{ApiLevel as g,Gauge as _,GaugeValue as v,InstanceStatus as y,LevelStatus as b,StatusByLevelWidget as x,StatusDistribution as S}from"./ScorecardWidgets.js";import{useApiScorecard as C,useScorecard as w}from"./use-scorecard.js";import{ApiListView as T,ApiProblemsView as E,RuleApisView as D,RulesView as ee,TeamsView as O}from"./ScorecardViews.js";import*as k from"react";import A from"styled-components";import{Button as j}from"@redocly/theme/components/Button/Button";import{useLocation as M}from"react-router";import{breakpoints as N,getScorecardColorVariable as P}from"@redocly/theme/core/utils";import{Fragment as F,jsx as I,jsxs as L}from"react/jsx-runtime";import{useModalScrollLock as R}from"@redocly/theme/core/hooks";import{ArrowLeftIcon as z}from"@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon";import{Sidebar as B}from"@redocly/theme/components/Sidebar/Sidebar";import{useLoaderData as V}from"virtual:realm-runtime";import{Link as H}from"@redocly/theme/components/Link/Link";import{CatalogDescription as U,CatalogPageContent as W,CatalogPageDescriptionWrapper as G,CatalogPageWrapper as K,CatalogTitle as q}from"@redocly/theme/components/CatalogClassic/CatalogClassic";import{FilterContent as J}from"@redocly/theme/components/Filter/FilterContent";import{FilterPopover as Y}from"@redocly/theme/components/Filter/FilterPopover";import{HighlightContext as X}from"@redocly/theme/components/CatalogClassic/CatalogClassicHighlight";import{CatalogClassicActions as Z}from"@redocly/theme/components/CatalogClassic/CatalogClassicActions";function Q({page:t}){let n=V(e),{pathname:r}=M();if(!n)return null;let i=t.slug.replace(/\/$/,``),[a,o]=r.slice(i.length).split(`/`).filter(Boolean),s=o===void 0?void 0:decodeURIComponent(o);return/* @__PURE__ */ I(te,{base:i,data:n,view:a===`apis`&&s!==void 0?{kind:`api`,link:`/${s}`}:a===`rules`&&s!==void 0?{kind:`rule`,ruleId:s}:{kind:`dashboard`}})}function te({base:e,data:n,view:r}){let i=w(n);if(r.kind===`api`){let a=i.apis.find(e=>e.link===r.link);return a?/* @__PURE__ */ I(re,{base:e,api:a,scorecard:i,rulesPerLevel:n.scorecard.rulesPerLevel}):/* @__PURE__ */ I(t,{children:`API not found`})}if(r.kind===`rule`){let n=i.problemsByRule.find(e=>e.ruleId===r.ruleId);return n?/* @__PURE__ */ I(ie,{base:e,rule:n,scorecard:i}):/* @__PURE__ */ I(t,{children:`Rule not found`})}return/* @__PURE__ */ I(ne,{base:e,levelNames:n.scorecard.levelNames,scorecard:i})}function ne({base:e,levelNames:t,scorecard:o}){let{summary:u,filters:_,filterTerm:v,setFilterTerm:y,hasTeam:b,teamLabel:x,catalogConfig:C}=o,w={apis:`APIs`,rules:`Rules`};b&&(w.teams=x);let[E,D]=k.useState(!1),[A,j]=k.useState(`apis`),M=k.useCallback(()=>j(`apis`),[]);R(E);let N=o.teams.filter(e=>(e.apis[`Non-conformant`]??0)>0).sort((e,t)=>(t.apis[`Non-conformant`]??0)-(e.apis[`Non-conformant`]??0));return/* @__PURE__ */ I(X.Provider,{value:[v],children:/* @__PURE__ */ L(K,{"data-component-name":`Scorecard/Dashboard`,children:[/* @__PURE__ */ I(ae,{menu:/* @__PURE__ */ I(J,{setFilterTerm:y,filters:_,filterTerm:v,filterValuesCasing:C.filterValuesCasing})}),E&&/* @__PURE__ */ I(Y,{onClose:()=>D(!1),setFilterTerm:y,filterTerm:v,filters:_,filterValuesCasing:C.filterValuesCasing}),/* @__PURE__ */ I(Z,{onOpenFilter:()=>D(!0),filters:_,filterTerm:v}),/* @__PURE__ */ L(W,{children:[/* @__PURE__ */ L(G,{children:[/* @__PURE__ */ I(q,{children:`API design scorecard`}),/* @__PURE__ */ I(U,{children:`See the health of your API designs.`})]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Scorecard status`}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ I(r,{children:u.total}),/* @__PURE__ */ I(`br`,{}),`APIs`]}),/* @__PURE__ */ I(`div`,{children:Object.entries(u.levels).map(([e,t],n)=>/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{style:{width:`40px`,textAlign:`right`},children:t}),/* @__PURE__ */ I(g,{level:e,colorVariable:P(n,Object.values(u.levels).length)})]},e))})]}),/* @__PURE__ */ I(S,{summary:u})]}),b&&/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Non-conformant APIs by ${x}`}),/* @__PURE__ */ L(d,{children:[N.slice(0,4).map(e=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{style:{flex:1,textAlign:`left`},children:e.team}),/* @__PURE__ */ I(r,{children:e.apis[`Non-conformant`]})]},e.team)),o.teams.length>4&&/* @__PURE__ */ L(s,{onClick:()=>j(`teams`),children:[`See all (`,o.teams.length,`)`]})]})]})]}),/* @__PURE__ */ I(l,{"data-component-name":`Scorecard/ModeSwitcherTabs`,children:Object.entries(w).map(([e,t])=>/* @__PURE__ */ I(c,{"data-component-name":`Scorecard/ModeSwitcherTab`,$isActive:A===e,onClick:()=>j(e),children:t},e))}),/* @__PURE__ */ I(h,{$isActive:A===`apis`,children:/* @__PURE__ */ I(T,{base:e,apis:o.apis,levelNames:t,hasTeam:b,hasPublishedAt:o.hasPublishedAt,teamLabel:x})}),/* @__PURE__ */ I(h,{$isActive:A===`rules`,children:/* @__PURE__ */ I(ee,{base:e,rules:o.problemsByRule})}),b&&/* @__PURE__ */ I(h,{$isActive:A===`teams`,children:/* @__PURE__ */ I(O,{teams:o.teams,levelNames:t,filters:_,teamLabel:x,teamProperty:o.teamProperty,onSelectTeam:M})})]})]})})}function $({base:e}){return/* @__PURE__ */ I(j,{icon:/* @__PURE__ */ I(z,{}),iconPosition:`left`,variant:`ghost`,size:`large`,to:e,children:`Back to dashboard`})}function re({base:e,api:n,scorecard:s,rulesPerLevel:d}){let _=C(n.scorecard.relativePath),v=_?.levels??{},y=Object.keys(v),[S,w]=k.useState(),T=S??y[0];return _===void 0?/* @__PURE__ */ I(t,{children:`Loading…`}):_===null?/* @__PURE__ */ I(t,{children:`Scorecard not found`}):/* @__PURE__ */ L(t,{"data-component-name":`Scorecard/ApiPage`,children:[/* @__PURE__ */ I($,{base:e}),/* @__PURE__ */ I(`h1`,{children:n.title}),/* @__PURE__ */ L(u,{children:[n.publishedAt&&/* @__PURE__ */ L(F,{children:[`Published at: `,new Date(n.publishedAt).toLocaleDateString(),/* @__PURE__ */ I(`br`,{})]}),/* @__PURE__ */ I(H,{to:n.link,external:!0,children:`Documentation`})]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ L(o,{children:[/* @__PURE__ */ I(`span`,{children:`Scorecard level`}),/* @__PURE__ */ I(g,{level:_.scorecardLevel,colorVariable:P(_.scorecardLevelIdx,y.length+1)})]}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ I(`div`,{children:`Compliance by level`}),/* @__PURE__ */ I(`div`,{children:Object.entries(v).map(([e,t])=>/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{style:{width:`100px`,textAlign:`right`},children:e}),/* @__PURE__ */ I(b,{errors:t.errors,warnings:t.warnings})]},e))})]})]}),/* @__PURE__ */ I(x,{title:`Rules compliance`,levels:Object.entries(v).map(([e,t])=>({name:e,errors:t.uniqueErrors,warnings:t.uniqueWarnings,total:d[e]?.length??0}))}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:s.teamLabel}),/* @__PURE__ */ I(r,{style:{fontWeight:`normal`},children:n.team})]})]}),/* @__PURE__ */ I(l,{"data-component-name":`Scorecard/ModeSwitcherTabs`,children:y.map(e=>/* @__PURE__ */ I(c,{"data-component-name":`Scorecard/ModeSwitcherTab`,$isActive:T===e,onClick:()=>w(e),children:/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(`span`,{children:e}),/* @__PURE__ */ I(b,{errors:v[e].errors,warnings:v[e].warnings})]})},e))}),y.map(e=>/* @__PURE__ */ I(h,{$isActive:T===e,children:/* @__PURE__ */ I(E,{level:e,problems:v[e].problems})},e))]})}function ie({base:e,rule:o,scorecard:s}){let c=Object.entries(o.teams).sort((e,t)=>t[1]-e[1]),l=o.apis.length;return/* @__PURE__ */ L(t,{"data-component-name":`Scorecard/RulePage`,children:[/* @__PURE__ */ I($,{base:e}),/* @__PURE__ */ L(`h1`,{children:[`Rule `,o.ruleId]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Rule status`}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ I(r,{children:l}),/* @__PURE__ */ I(`br`,{}),`APIs`]}),/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:l-o.warningApisCount-o.errorApisCount}),/* @__PURE__ */ I(y,{severity:`Pass`})]}),/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:o.warningApisCount}),/* @__PURE__ */ I(y,{severity:`Warn`})]}),/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:o.errorApisCount}),/* @__PURE__ */ I(y,{severity:`Error`})]})]})]})]}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Problems by level`}),/* @__PURE__ */ I(d,{children:Object.entries(o.levels).map(([e,t])=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{children:e}),/* @__PURE__ */ I(_,{chunks:[{share:t.errors/o.count*100,colorVariable:`--scorecard-color-error`},{share:t.warnings/o.count*100,colorVariable:`--scorecard-color-warning`}]}),/* @__PURE__ */ I(v,{children:t.errors+t.warnings})]},e))})]}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Problems by ${s.teamLabel}`}),/* @__PURE__ */ I(d,{children:c.slice(0,4).map(([e,t])=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{style:{flex:1,textAlign:`left`},children:e}),/* @__PURE__ */ I(r,{children:t})]},e))})]})]}),/* @__PURE__ */ I(D,{ruleId:o.ruleId,apis:o.apis,hasPublishedAt:s.hasPublishedAt,hasTeam:s.hasTeam,teamLabel:s.teamLabel})]})}const ae=A(B)`
1
+ import{CATALOG_CLASSIC_DEP_KEY as e}from"../../catalog-classic/client/contract.js";import"./contract.js";import{AppPageWrapper as t,CardRow as n,CardValue as r,CardsWrapper as i,ContentWithDotWrap as a,LevelComplianceCardTitle as o,LinkButton as s,ModeSwitcherTab as c,ModeSwitcherTabs as l,PageDescription as u,ProblemsByStatusCardBody as d,ScoreCardStatusCardBody as f,ScorecardCard as p,ScorecardCardTitle as m,TableWrap as h}from"./styles.js";import{ApiLevel as g,Gauge as _,GaugeValue as v,InstanceStatus as y,LevelStatus as b,StatusByLevelWidget as x,StatusDistribution as S}from"./ScorecardWidgets.js";import{useApiScorecard as C,useScorecard as w}from"./use-scorecard.js";import{ApiListView as T,ApiProblemsView as E,RuleApisView as D,RulesView as ee,TeamsView as O}from"./ScorecardViews.js";import*as k from"react";import A from"styled-components";import{Button as j}from"@redocly/theme/components/Button/Button";import{useLocation as M}from"react-router";import{breakpoints as N,getScorecardColorVariable as P}from"@redocly/theme/core/utils";import{Fragment as F,jsx as I,jsxs as L}from"react/jsx-runtime";import{useModalScrollLock as R}from"@redocly/theme/core/hooks";import{Link as z}from"@redocly/theme/components/Link/Link";import{ArrowLeftIcon as B}from"@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon";import{Sidebar as V}from"@redocly/theme/components/Sidebar/Sidebar";import{useLoaderData as H}from"virtual:realm-runtime";import{CatalogDescription as U,CatalogPageContent as W,CatalogPageDescriptionWrapper as G,CatalogPageWrapper as K,CatalogTitle as q}from"@redocly/theme/components/CatalogClassic/CatalogClassic";import{FilterContent as J}from"@redocly/theme/components/Filter/FilterContent";import{FilterPopover as Y}from"@redocly/theme/components/Filter/FilterPopover";import{HighlightContext as X}from"@redocly/theme/components/CatalogClassic/CatalogClassicHighlight";import{CatalogClassicActions as Z}from"@redocly/theme/components/CatalogClassic/CatalogClassicActions";function Q({page:t}){let n=H(e),{pathname:r}=M();if(!n)return null;let i=t.slug.replace(/\/$/,``),[a,o]=r.slice(i.length).split(`/`).filter(Boolean),s=o===void 0?void 0:decodeURIComponent(o);return/* @__PURE__ */ I(te,{base:i,data:n,view:a===`apis`&&s!==void 0?{kind:`api`,link:`/${s}`}:a===`rules`&&s!==void 0?{kind:`rule`,ruleId:s}:{kind:`dashboard`}})}function te({base:e,data:n,view:r}){let i=w(n);if(r.kind===`api`){let a=i.apis.find(e=>e.link===r.link);return a?/* @__PURE__ */ I(re,{base:e,api:a,scorecard:i,rulesPerLevel:n.scorecard.rulesPerLevel}):/* @__PURE__ */ I(t,{children:`API not found`})}if(r.kind===`rule`){let n=i.problemsByRule.find(e=>e.ruleId===r.ruleId);return n?/* @__PURE__ */ I(ie,{base:e,rule:n,scorecard:i}):/* @__PURE__ */ I(t,{children:`Rule not found`})}return/* @__PURE__ */ I(ne,{base:e,levelNames:n.scorecard.levelNames,scorecard:i})}function ne({base:e,levelNames:t,scorecard:o}){let{summary:u,filters:_,filterTerm:v,setFilterTerm:y,hasTeam:b,teamLabel:x,catalogConfig:C}=o,w={apis:`APIs`,rules:`Rules`};b&&(w.teams=x);let[E,D]=k.useState(!1),[A,j]=k.useState(`apis`),M=k.useCallback(()=>j(`apis`),[]);R(E);let N=o.teams.filter(e=>(e.apis[`Non-conformant`]??0)>0).sort((e,t)=>(t.apis[`Non-conformant`]??0)-(e.apis[`Non-conformant`]??0));return/* @__PURE__ */ I(X.Provider,{value:[v],children:/* @__PURE__ */ L(K,{"data-component-name":`Scorecard/Dashboard`,children:[/* @__PURE__ */ I(ae,{menu:/* @__PURE__ */ I(J,{setFilterTerm:y,filters:_,filterTerm:v,filterValuesCasing:C.filterValuesCasing})}),E&&/* @__PURE__ */ I(Y,{onClose:()=>D(!1),setFilterTerm:y,filterTerm:v,filters:_,filterValuesCasing:C.filterValuesCasing}),/* @__PURE__ */ I(Z,{onOpenFilter:()=>D(!0),filters:_,filterTerm:v}),/* @__PURE__ */ L(W,{children:[/* @__PURE__ */ L(G,{children:[/* @__PURE__ */ I(q,{children:`API design scorecard`}),/* @__PURE__ */ I(U,{children:`See the health of your API designs.`})]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Scorecard status`}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ I(r,{children:u.total}),/* @__PURE__ */ I(`br`,{}),`APIs`]}),/* @__PURE__ */ I(`div`,{children:Object.entries(u.levels).map(([e,t],n)=>/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{style:{width:`40px`,textAlign:`right`},children:t}),/* @__PURE__ */ I(g,{level:e,colorVariable:P(n,Object.values(u.levels).length)})]},e))})]}),/* @__PURE__ */ I(S,{summary:u})]}),b&&/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Non-conformant APIs by ${x}`}),/* @__PURE__ */ L(d,{children:[N.slice(0,4).map(e=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{style:{flex:1,textAlign:`left`},children:e.team}),/* @__PURE__ */ I(r,{children:e.apis[`Non-conformant`]})]},e.team)),o.teams.length>4&&/* @__PURE__ */ L(s,{onClick:()=>j(`teams`),children:[`See all (`,o.teams.length,`)`]})]})]})]}),/* @__PURE__ */ I(l,{"data-component-name":`Scorecard/ModeSwitcherTabs`,children:Object.entries(w).map(([e,t])=>/* @__PURE__ */ I(c,{"data-component-name":`Scorecard/ModeSwitcherTab`,$isActive:A===e,onClick:()=>j(e),children:t},e))}),/* @__PURE__ */ I(h,{$isActive:A===`apis`,children:/* @__PURE__ */ I(T,{base:e,apis:o.apis,levelNames:t,hasTeam:b,hasPublishedAt:o.hasPublishedAt,teamLabel:x})}),/* @__PURE__ */ I(h,{$isActive:A===`rules`,children:/* @__PURE__ */ I(ee,{base:e,rules:o.problemsByRule})}),b&&/* @__PURE__ */ I(h,{$isActive:A===`teams`,children:/* @__PURE__ */ I(O,{teams:o.teams,levelNames:t,filters:_,teamLabel:x,teamProperty:o.teamProperty,onSelectTeam:M})})]})]})})}function $({base:e}){return/* @__PURE__ */ I(j,{icon:/* @__PURE__ */ I(B,{}),iconPosition:`left`,variant:`ghost`,size:`large`,to:e,children:`Back to dashboard`})}function re({base:e,api:n,scorecard:s,rulesPerLevel:d}){let _=C(n.scorecard.relativePath),v=_?.levels??{},y=Object.keys(v),[S,w]=k.useState(),T=S??y[0];return _===void 0?/* @__PURE__ */ I(t,{children:`Loading…`}):_===null?/* @__PURE__ */ I(t,{children:`Scorecard not found`}):/* @__PURE__ */ L(t,{"data-component-name":`Scorecard/ApiPage`,children:[/* @__PURE__ */ I($,{base:e}),/* @__PURE__ */ I(`h1`,{children:n.title}),/* @__PURE__ */ L(u,{children:[n.publishedAt&&/* @__PURE__ */ L(F,{children:[`Published at: `,new Date(n.publishedAt).toLocaleDateString(),/* @__PURE__ */ I(`br`,{})]}),/* @__PURE__ */ I(z,{to:n.link,external:!0,children:`Documentation`})]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ L(o,{children:[/* @__PURE__ */ I(`span`,{children:`Scorecard level`}),/* @__PURE__ */ I(g,{level:_.scorecardLevel,colorVariable:P(_.scorecardLevelIdx,y.length+1)})]}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ I(`div`,{children:`Compliance by level`}),/* @__PURE__ */ I(`div`,{children:Object.entries(v).map(([e,t])=>/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{style:{width:`100px`,textAlign:`right`},children:e}),/* @__PURE__ */ I(b,{errors:t.errors,warnings:t.warnings})]},e))})]})]}),/* @__PURE__ */ I(x,{title:`Rules compliance`,levels:Object.entries(v).map(([e,t])=>({name:e,errors:t.uniqueErrors,warnings:t.uniqueWarnings,total:d[e]?.length??0}))}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:s.teamLabel}),/* @__PURE__ */ I(r,{style:{fontWeight:`normal`},children:n.team})]})]}),/* @__PURE__ */ I(l,{"data-component-name":`Scorecard/ModeSwitcherTabs`,children:y.map(e=>/* @__PURE__ */ I(c,{"data-component-name":`Scorecard/ModeSwitcherTab`,$isActive:T===e,onClick:()=>w(e),children:/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(`span`,{children:e}),/* @__PURE__ */ I(b,{errors:v[e].errors,warnings:v[e].warnings})]})},e))}),y.map(e=>/* @__PURE__ */ I(h,{$isActive:T===e,children:/* @__PURE__ */ I(E,{level:e,problems:v[e].problems})},e))]})}function ie({base:e,rule:o,scorecard:s}){let c=Object.entries(o.teams).sort((e,t)=>t[1]-e[1]),l=o.apis.length;return/* @__PURE__ */ L(t,{"data-component-name":`Scorecard/RulePage`,children:[/* @__PURE__ */ I($,{base:e}),/* @__PURE__ */ L(`h1`,{children:[`Rule `,o.ruleId]}),/* @__PURE__ */ L(i,{children:[/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Rule status`}),/* @__PURE__ */ L(f,{children:[/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ I(r,{children:l}),/* @__PURE__ */ I(`br`,{}),`APIs`]}),/* @__PURE__ */ L(`div`,{children:[/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:l-o.warningApisCount-o.errorApisCount}),/* @__PURE__ */ I(y,{severity:`Pass`})]}),/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:o.warningApisCount}),/* @__PURE__ */ I(y,{severity:`Warn`})]}),/* @__PURE__ */ L(a,{children:[/* @__PURE__ */ I(r,{children:o.errorApisCount}),/* @__PURE__ */ I(y,{severity:`Error`})]})]})]})]}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Problems by level`}),/* @__PURE__ */ I(d,{children:Object.entries(o.levels).map(([e,t])=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{children:e}),/* @__PURE__ */ I(_,{chunks:[{share:t.errors/o.count*100,colorVariable:`--scorecard-color-error`},{share:t.warnings/o.count*100,colorVariable:`--scorecard-color-warning`}]}),/* @__PURE__ */ I(v,{children:t.errors+t.warnings})]},e))})]}),/* @__PURE__ */ L(p,{children:[/* @__PURE__ */ I(m,{children:`Problems by ${s.teamLabel}`}),/* @__PURE__ */ I(d,{children:c.slice(0,4).map(([e,t])=>/* @__PURE__ */ L(n,{children:[/* @__PURE__ */ I(`span`,{style:{flex:1,textAlign:`left`},children:e}),/* @__PURE__ */ I(r,{children:t})]},e))})]})]}),/* @__PURE__ */ I(D,{ruleId:o.ruleId,apis:o.apis,hasPublishedAt:s.hasPublishedAt,hasTeam:s.hasTeam,teamLabel:s.teamLabel})]})}const ae=A(V)`
2
2
  display: none;
3
3
 
4
4
  @media screen and (min-width: ${N.medium}) {
@@ -1,2 +1,2 @@
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{compareStrings as i}from"../../../../shared/utils/compare-strings.js";import{isObject as a}from"../../../../shared/utils/is-object.js";import"../../../../shared/constants/l10n/defaults.js";import{NAV_ITEM_RBAC as o}from"../../../../shared/rbac/types.js";import{toLocaleSlug as s}from"../../../../shared/utils/l10n.js";import{resolveContentPath as c}from"../../../../shared/utils/resolve-content-path.js";import{isLocalImagePath as l}from"../assets/extensions.js";import{splitUrlSuffix as u}from"../../../../shared/utils/routes/split-url-suffix.js";import{resolvePageTarget as d}from"../../../../shared/utils/routes/resolve-page-target.js";import{toPublicVersionedSlug as f}from"../../../../shared/constants/versions.js";import{collectVersionGroups as p,findVersionedDirectories as ee}from"../../../versions/version-groups.js";import{publicLink as m}from"../../../versions/public-link.js";import{linkedPageAccess as h}from"../../utils/link-access.js";import{safeDecodeURI as g}from"../../../../shared/utils/safe-decode-uri.js";import{joinSrcSet as _,parseSrcSet as v}from"../assets/srcset.js";import{bundleSidebar as y,bundleSidebarEntries as te,collectSidebarLinkRefs as b,collectSidebarRefTargets as x,stampDefaultVersions as ne}from"./bundle.js";import{SIDEBAR_CONTRIBUTIONS_ENTITY_TYPE as S,sidebarStartEntityKey as C}from"./contributions.js";import{applySubtree as w}from"./subtree.js";import{collectSlugOverrides as re}from"../../utils/slug-overrides.js";import{SIDEBAR_BACK_LINK_ROUTE_DEP_KEY as T,SIDEBAR_BREADCRUMBS_ROUTE_DEP_KEY as E,SIDEBAR_ROUTE_DEP_KEY as D,localizedSidebarDepKey as ie}from"../../../../shared/constants/route-deps.js";import{SITE_START_ENTITY_KEY as O}from"../../../../shared/constants/site-start.js";import{posix as k}from"node:path";import{REDOCLY_TEAMS_RBAC as A}from"@redocly/config";const j=`internal.sidebar`,M=r(j,`aggregate`),N=/(^|[/._-])sidebars\.ya?ml$/,P=/(^|\/)sidebars\.ya?ml$/,F=`sidebars.yaml`,I=`redocly.yaml`;function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Array.isArray(e.tabs)}function R(e){if(Array.isArray(e))return e.find(e=>z(e.label)!==void 0)?.label}function z(e){return typeof e==`string`&&e.trim()!==``?e:void 0}function B(e){let t=((e??``).split(/[?#]/)[0]?.split(`/`).filter(Boolean).pop()??``).replace(/[-_]+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)}async function V(e,{route:t,link:n},r){let i=r.subtreeKeyOf(t);if(!i)return{...e,link:void 0};let a=await r.loadEntity(i);if(a===void 0)return{...e,label:e.label??B(e.link)};let o=H(w({link:t},a),n.toLowerCase());return o===void 0?{...e,link:void 0}:{...e,label:e.label??o.label,[A]:o[A]}}function H(e,t){for(let n of e){if(n.link?.toLowerCase()===t)return n;let e=n.items===void 0?void 0:H(n.items,t);if(e!==void 0)return e}}async function U(e,t){let n=[];for(let r of e){let e=r.subtreeItem===void 0?r:await V(r,r.subtreeItem,t),i=e.link?t.subtreeKeyOf(e.link):void 0,a=i?await t.loadEntity(i):void 0,s=e.tabId!==void 0,c=s||!!i&&a===void 0,l=s?{...e,isGroup:!0,label:e.label??R(a)}:e,u=a===void 0?[l]:w(l,a);for(let r of u){let i=r[`redocly::nav-item-rbac`]??e[`redocly::nav-item-rbac`],a=r[A]??(i===void 0&&r.link!==void 0?t.accessOf(r.link)??void 0:void 0);n.push({type:r.type,expanded:r.expanded,selectFirstItemOnExpand:r.selectFirstItemOnExpand,external:r.external,target:r.target,languageInsensitive:r.languageInsensitive,icon:r.icon===void 0?void 0:await t.resolveAsset(r.icon),srcSet:r.srcSet===void 0?void 0:await W(r.srcSet,t),items:r.items?await U(r.items,t):void 0,tab:r.tab,tabId:r.tabId,menu:r.menu?await U(r.menu,t):void 0,label:c?r.label??B(r.link):r.label,labelTranslationKey:r.labelTranslationKey,link:r.link!==void 0&&r.versionGroup!==void 0&&r.version!==void 0?f(r.link,r.versionGroup,r.version,r.isDefaultVersion===!0):r.link,separatorLine:r.separatorLine,linePosition:r.linePosition,variant:r.variant,menuStyle:r.menuStyle,sublabel:r.sublabel,version:r.version,versionGroup:r.versionGroup,isDefaultVersion:r.isDefaultVersion,versionLabel:r.versionLabel,httpVerb:r.httpVerb,deprecated:r.deprecated,badges:r.badges,[A]:a,[o]:i})}}return n}async function W(e,t){let n=v(e);if(n===null)return e;let r=await Promise.all(n.map(async e=>Object.assign(e,{src:await t.resolveAsset(e.src)})));return _(r)}function G(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;return{async resolve(r){if(!l(r))return r;let i=await e.resolveImageReference(r,``),a=c(g(r),``);a!==null&&t.set(`file:${a}`,{kind:`file`,path:a});for(let e of i.entityDeps)t.set(e.kind===`file`?`file:${e.path}`:`entity:${e.key}`,e);for(let e of i.assetUsages)n.set(e.path,e);return i.result.kind===`assetRef`?i.result.url:r},collected(){return{entityDeps:[...t.values()],assetUsages:[...n.values()]}}}}function K(e){return e.tabId!==void 0}function q(e){return K(e)&&e.link!==void 0}function J(e){return{tabId:e.tabId,version:e.version,versionGroup:e.versionGroup,isDefaultVersion:e.isDefaultVersion,versionLabel:e.versionLabel,[A]:e[A],[o]:e[o]}}function ae(e){return{...J(e),label:e.label,labelTranslationKey:e.labelTranslationKey,link:e.link,icon:e.icon,items:e.items??[]}}function oe(e){return{...J(e),label:e.label,labelTranslationKey:e.labelTranslationKey,link:e.menu?void 0:e.link,icon:e.icon,items:e.menu?void 0:e.items??[],menu:e.menu?.filter(q).map(ae)}}const Y=t(M,async e=>{let t=G(e.markdown),{locale:n,slugOverrides:r={},versionedDirectories:i=[]}=e.args,a=t=>e.routes.bySlug(t)?.sidebarSubtreeEntityKey,o=i.length===0?/* @__PURE__ */ new Map:await p({io:e.io,routes:e.routes,versionedDirectories:i}),c=await U(e.args.nodes,{loadEntity:t=>e.entities.tryLoad(t),subtreeKeyOf:e=>(n===void 0?void 0:a(r[e]??s(e,n)))??a(e),accessOf:t=>h(t,e.routes,o),resolveAsset:t.resolve});return{value:e.args.nodes.some(e=>e.tab)?{tabs:c.filter(K).map(oe)}:c,...t.collected()}});async function se(e){let t=await e.loadEntity(e.subtreeKey);return U(w({link:e.routeSlug,...e.version},t),{loadEntity:e.loadEntity,subtreeKeyOf:()=>void 0,accessOf:()=>void 0,resolveAsset:async e=>e})}function ce(e){let t=typeof e==`string`?e:a(e)?e.path:void 0;return typeof t==`string`&&t.trim()!==``?t.trim():null}function X(e){return[e.originPluginId,e.originFilePath,e.routeId].join(`\0`)}async function Z(e,t){let n=/* @__PURE__ */ new Map;for(let r of e.assignedRouteSlugs){let e=t.routes.bySlug(r),i=e?.originFilePath===null?e.sidebarSubtreeEntityKey:null;if(!i||await t.entities.get(i)===null)continue;let a=e=>{for(let i of e){let e=i.link===void 0?void 0:t.routes.bySlug(i.link);e!==void 0&&!n.has(e.slug)&&n.set(e.slug,r),i.items&&a(i.items)}};a(w({link:r},await t.entities.load(i)))}return n}function le(e,t){for(let n of t)for(let[t,r]of n){let n=e.get(r);n!==void 0&&!e.has(t)&&e.set(t,n)}}async function ue(e){let t=[];for(let n of await e.list({type:S}))t.push(...await e.load(n.key));return t}function de(e,t=[]){let n=[];for(let[r,i]of e.entries()){if(t[r]?.link!==i.link)break;n.push(i)}return n}async function fe(e,t,n,r,i){let a=await Promise.all(e.map(async e=>{let r=pe(e,t,n);return r===null?null:{item:e,link:r.link,label:await me(e,r,i)}})),o=/* @__PURE__ */ new Map;for(let{item:e,link:t,label:n}of a.filter(e=>e!==null))for(let i of e.linkedSidebars??[]){let e=c(i,I),a=e===null?void 0:r.get(e);a!==void 0&&!o.has(a)&&o.set(a,{label:n,link:t})}return o}function pe(e,t,n){if(typeof e.href==`string`&&e.href.trim()!==``)return{link:e.href.trim()};if(typeof e.page!=`string`||e.page.trim()===``)return null;let{path:r,suffix:i,anchor:a}=u(e.page.trim()),o=d(r,I,t);if(o.kind!==`found`)return null;let s=o.value;return{link:`${m(s,n)}${i}`,anchor:a,route:s}}async function me(e,t,n){let r=z(e.label)??z(e.group)??t.anchor;if(r!==void 0)return r;let i=t.route?.sidebarSubtreeEntityKey,o=i?await n(i):void 0;return(a(o)?z(o.label):void 0)??t.link}function Q(e,t){for(let n of e){if(!t(n))continue;if(n.link!==void 0&&n.languageInsensitive!==!0)return n;let e=Q([...n.items??[],...n.menu??[]],t);if(e!==null)return e}return null}function he(e,t){return Q(e,e=>e.version===void 0||e.version===t)?.link??null}function $(e){let t=Q(e,e=>e.version===void 0||e.isDefaultVersion===!0);return t?.link===void 0?null:t.versionGroup!==void 0&&t.version!==void 0?f(t.link,t.versionGroup,t.version,!0):t.link}function ge(e){let[t]=e;if(t===void 0)return null;let n=t.path.split(`/`).length;return(e.find(({path:e})=>e.split(`/`).length===n&&P.test(e))??t).link}function _e(e){let t=null;for(let{slug:n,originFilePath:r,locale:a,versionGroup:o}of e)r!==null&&a===``&&o===null&&(t===null||n.length<t.length||n.length===t.length&&i(n,t)<0)&&(t=n);return t}const ve=e({id:j,version:`1.27.0`,content:{filter:{match:e=>N.test(e)},async extractFile(e,t){let n=await t.io.readFile(e.path);return{routes:[],linkRefs:await b({source:n,filePath:e.path,readFile:t.io.readFile})}}},async finalize(e){let t=[],r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=[],c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,d=[],f=await Promise.all(e.files.map(async t=>({path:t.path,source:await e.io.readFile(t.path)}))),m=e.routes.all(),g=re(m,e.localeContext),_=ee(m),v=_.length>0?_:void 0;f.sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length);let b=new Map(f.map(({path:e,source:t})=>[e,t])),S=/* @__PURE__ */ new Map;for(let{path:e}of f)P.test(e)&&S.set(k.dirname(e),e);let w=/* @__PURE__ */ new Set;for(let{path:e,source:t}of f)for(let n of x(t,e))w.add(n);let j=await p({io:e.io,routes:e.routes,versionedDirectories:_}),M={routes:e.routes,versionGroups:j,report:e=>r.push(e),readFile:async t=>b.get(t)??e.io.readFile(t),exists:t=>e.io.exists(t),sidebarByDirectory:S},N=async(n,r)=>{if(n.nodes.length===0)return;ne(n.nodes,j);let i=Y.withArgs({nodes:n.nodes,versionedDirectories:v},r===void 0?void 0:{metadata:{sourcePath:r}});t.push(i),l.set(i,n.nodes);let a=/* @__PURE__ */ new Map;for(let r of e.localeContext.locales){let e=Y.withArgs({nodes:n.nodes,locale:r,slugOverrides:g[r]??{},versionedDirectories:v});t.push(e),a.set(r,e)}return c.set(i,a),i};for(let{path:t,source:n}of f){if(w.has(t))continue;let c=await y({...M,file:{path:t},source:n}),l=await N(c,t);if(l===void 0)continue;a.set(t,l);let u=t.startsWith(`@l10n/`)?null:$(c.nodes);u!==null&&d.push({path:t,link:u}),s.push(await Z(c,e));for(let e of c.assignedRouteSlugs){let n=o.get(e);n!==void 0&&r.push({code:`sidebar/route-conflict`,message:`Page "${e}" is in sidebars ${n} and ${t}; it shows ${t}.`,location:{filePath:t}}),i.set(e,l),o.set(e,t)}}le(i,s);let I=new Map(m.map(e=>[e.slug,e]));for(let[t,n]of Object.entries(e.routes.metadata(`sidebar`))){let e=I.get(t);if(e===void 0||e.originFilePath===null)continue;let o=ce(n);if(o===null)continue;let s=k.normalize(o.startsWith(`/`)?o.slice(1):k.join(k.dirname(e.originFilePath),o)),c=a.get(s);if(c===void 0){r.push({code:`sidebar/missing-target`,message:`Front matter sidebar "${o}" is not a sidebar file of this project.`,location:{filePath:e.originFilePath}});continue}i.set(e.slug,c)}let L=await ue(e.entities),R=/* @__PURE__ */ new Set,z=/* @__PURE__ */ new Map,B=/* @__PURE__ */ new Map;for(let t of L){let n=i.get(t.route);if(n===void 0){let r=await te({...M,file:{path:F},entries:t.entries});if(n=await N(r),n===void 0)continue;let a=(await Z(r,e)).keys();for(let e of[...r.assignedRouteSlugs,...a])i.has(e)||(i.set(e,n),R.add(e))}let r=z.get(n);z.set(n,r===void 0?t.backLink??null:r!==null&&r.link===t.backLink?.link?r:null);let a=B.get(n);B.set(n,a===void 0?t.breadcrumbs??[]:de(a,t.breadcrumbs))}if(f.length===0&&m.length>0){let e=await y({...M,file:{path:F},source:`- directory: .
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{compareStrings as i}from"../../../../shared/utils/compare-strings.js";import{isObject as a}from"../../../../shared/utils/is-object.js";import"../../../../shared/constants/l10n/defaults.js";import{NAV_ITEM_RBAC as o}from"../../../../shared/rbac/types.js";import{toLocaleSlug as s}from"../../../../shared/utils/l10n.js";import{resolveContentPath as c}from"../../../../shared/utils/resolve-content-path.js";import{isLocalImagePath as l}from"../assets/extensions.js";import{splitUrlSuffix as u}from"../../../../shared/utils/routes/split-url-suffix.js";import{resolvePageTarget as d}from"../../../../shared/utils/routes/resolve-page-target.js";import{toPublicVersionedSlug as f}from"../../../../shared/constants/versions.js";import{collectVersionGroups as p,findVersionedDirectories as ee}from"../../../versions/version-groups.js";import{publicLink as m}from"../../../versions/public-link.js";import{linkedPageAccess as h}from"../../utils/link-access.js";import{safeDecodeURI as g}from"../../../../shared/utils/safe-decode-uri.js";import{joinSrcSet as _,parseSrcSet as v}from"../assets/srcset.js";import{bundleSidebar as y,bundleSidebarEntries as te,collectSidebarLinkRefs as b,collectSidebarRefTargets as x,stampDefaultVersions as ne}from"./bundle.js";import{SIDEBAR_CONTRIBUTIONS_ENTITY_TYPE as S,sidebarStartEntityKey as C}from"./contributions.js";import{applySubtree as w}from"./subtree.js";import{collectSlugOverrides as re}from"../../utils/slug-overrides.js";import{SIDEBAR_BACK_LINK_ROUTE_DEP_KEY as T,SIDEBAR_BREADCRUMBS_ROUTE_DEP_KEY as E,SIDEBAR_ROUTE_DEP_KEY as D,localizedSidebarDepKey as ie}from"../../../../shared/constants/route-deps.js";import{SITE_START_ENTITY_KEY as O}from"../../../../shared/constants/site-start.js";import{posix as k}from"node:path";import{REDOCLY_TEAMS_RBAC as A}from"@redocly/config";const j=`internal.sidebar`,M=r(j,`aggregate`),N=/(^|[/._-])sidebars\.ya?ml$/,P=/(^|\/)sidebars\.ya?ml$/,F=`sidebars.yaml`,I=`redocly.yaml`;function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Array.isArray(e.tabs)}function R(e){if(Array.isArray(e))return e.find(e=>z(e.label)!==void 0)?.label}function z(e){return typeof e==`string`&&e.trim()!==``?e:void 0}function B(e){let t=((e??``).split(/[?#]/)[0]?.split(`/`).filter(Boolean).pop()??``).replace(/[-_]+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)}async function V(e,{route:t,link:n},r){let i=r.subtreeKeyOf(t);if(!i)return{...e,link:void 0};let a=await r.loadEntity(i);if(a===void 0)return{...e,label:e.label??B(e.link)};let o=H(w({link:t},a),n.toLowerCase());return o===void 0?{...e,link:void 0}:{...e,label:e.label??o.label,[A]:o[A]}}function H(e,t){for(let n of e){if(n.link?.toLowerCase()===t)return n;let e=n.items===void 0?void 0:H(n.items,t);if(e!==void 0)return e}}async function U(e,t){let n=[];for(let r of e){let e=r.subtreeItem===void 0?r:await V(r,r.subtreeItem,t),i=e.link?t.subtreeKeyOf(e.link):void 0,a=i?await t.loadEntity(i):void 0,s=e.tabId!==void 0,c=s||!!i&&a===void 0,l=s?{...e,isGroup:!0,label:e.label??R(a)}:e,u=a===void 0?[l]:w(l,a);for(let r of u){let i=r[`redocly::nav-item-rbac`]??e[`redocly::nav-item-rbac`],a=r[A]??(i===void 0&&r.link!==void 0?t.accessOf(r.link)??void 0:void 0);n.push({type:r.type,expanded:r.expanded,selectFirstItemOnExpand:r.selectFirstItemOnExpand,external:r.external,target:r.target,languageInsensitive:r.languageInsensitive,icon:r.icon===void 0?void 0:await t.resolveAsset(r.icon),srcSet:r.srcSet===void 0?void 0:await W(r.srcSet,t),items:r.items?await U(r.items,t):void 0,tab:r.tab,tabId:r.tabId,menu:r.menu?await U(r.menu,t):void 0,label:c?r.label??B(r.link):r.label,labelTranslationKey:r.labelTranslationKey,link:r.link!==void 0&&r.versionGroup!==void 0&&r.version!==void 0?f(r.link,r.versionGroup,r.version,r.isDefaultVersion===!0):r.link,separatorLine:r.separatorLine,linePosition:r.linePosition,variant:r.variant,menuStyle:r.menuStyle,sublabel:r.sublabel,version:r.version,versionGroup:r.versionGroup,isDefaultVersion:r.isDefaultVersion,versionLabel:r.versionLabel,httpVerb:r.httpVerb,deprecated:r.deprecated,badges:r.badges,[A]:a,[o]:i})}}return n}async function W(e,t){let n=v(e);if(n===null)return e;let r=await Promise.all(n.map(async e=>Object.assign(e,{src:await t.resolveAsset(e.src)})));return _(r)}function G(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;return{async resolve(r){if(!l(r))return r;let i=await e.resolveImageReference(r,``),a=c(g(r),``);a!==null&&t.set(`file:${a}`,{kind:`file`,path:a});for(let e of i.entityDeps)t.set(e.kind===`file`?`file:${e.path}`:`entity:${e.key}`,e);for(let e of i.assetUsages)n.set(e.path,e);return i.result.kind===`assetRef`?i.result.url:r},collected(){return{entityDeps:[...t.values()],assetUsages:[...n.values()]}}}}function K(e){return e.tabId!==void 0}function q(e){return K(e)&&e.link!==void 0}function J(e){return{tabId:e.tabId,version:e.version,versionGroup:e.versionGroup,isDefaultVersion:e.isDefaultVersion,versionLabel:e.versionLabel,[A]:e[A],[o]:e[o]}}function ae(e){return{...J(e),label:e.label,labelTranslationKey:e.labelTranslationKey,link:e.link,icon:e.icon,items:e.items??[]}}function oe(e){return{...J(e),label:e.label,labelTranslationKey:e.labelTranslationKey,link:e.menu?void 0:e.link,icon:e.icon,items:e.menu?void 0:e.items??[],menu:e.menu?.filter(q).map(ae)}}const Y=t(M,async e=>{let t=G(e.markdown),{locale:n,slugOverrides:r={},versionedDirectories:i=[]}=e.args,a=t=>e.routes.bySlug(t)?.sidebarSubtreeEntityKey,o=i.length===0?/* @__PURE__ */ new Map:await p({io:e.io,routes:e.routes,versionedDirectories:i}),c=await U(e.args.nodes,{loadEntity:t=>e.entities.tryLoad(t),subtreeKeyOf:e=>(n===void 0?void 0:a(r[e]??s(e,n)))??a(e),accessOf:t=>h(t,e.routes,o),resolveAsset:t.resolve});return{value:e.args.nodes.some(e=>e.tab)?{tabs:c.filter(K).map(oe)}:c,...t.collected()}});async function se(e){let t=await e.loadEntity(e.subtreeKey);return U(w({link:e.routeSlug,...e.version},t),{loadEntity:e.loadEntity,subtreeKeyOf:()=>void 0,accessOf:()=>void 0,resolveAsset:async e=>e})}function ce(e){let t=typeof e==`string`?e:a(e)?e.path:void 0;return typeof t==`string`&&t.trim()!==``?t.trim():null}function X(e){return[e.originPluginId,e.originFilePath,e.routeId].join(`\0`)}async function Z(e,t){let n=/* @__PURE__ */ new Map;for(let r of e.assignedRouteSlugs){let e=t.routes.bySlug(r),i=e?.originFilePath===null?e.sidebarSubtreeEntityKey:null;if(!i||await t.entities.get(i)===null)continue;let a=e=>{for(let i of e){let e=i.link===void 0?void 0:t.routes.bySlug(i.link);e!==void 0&&!n.has(e.slug)&&n.set(e.slug,r),i.items&&a(i.items)}};a(w({link:r},await t.entities.load(i)))}return n}function le(e,t){for(let n of t)for(let[t,r]of n){let n=e.get(r);n!==void 0&&!e.has(t)&&e.set(t,n)}}async function ue(e){let t=[];for(let n of await e.list({type:S}))t.push(...await e.load(n.key));return t}function de(e,t=[]){let n=[];for(let[r,i]of e.entries()){if(t[r]?.link!==i.link)break;n.push(i)}return n}async function fe(e,t,n,r,i){let a=await Promise.all(e.map(async e=>{let r=pe(e,t,n);return r===null?null:{item:e,link:r.link,label:await me(e,r,i)}})),o=/* @__PURE__ */ new Map;for(let{item:e,link:t,label:n}of a.filter(e=>e!==null))for(let i of e.linkedSidebars??[]){let e=c(i,I),a=e===null?void 0:r.get(e);a!==void 0&&!o.has(a)&&o.set(a,{label:n,link:t})}return o}function pe(e,t,n){if(typeof e.href==`string`&&e.href.trim()!==``)return{link:e.href.trim()};if(typeof e.page!=`string`||e.page.trim()===``)return null;let{path:r,suffix:i,anchor:a}=u(e.page.trim()),o=d(r,I,t);if(o.kind!==`found`)return null;let s=o.value;return{link:`${m(s,n)}${i}`,anchor:a,route:s}}async function me(e,t,n){let r=z(e.label)??z(e.group)??t.anchor;if(r!==void 0)return r;let i=t.route?.sidebarSubtreeEntityKey,o=i?await n(i):void 0;return(a(o)?z(o.label):void 0)??t.link}function Q(e,t){for(let n of e){if(!t(n))continue;if(n.link!==void 0&&n.languageInsensitive!==!0)return n;let e=Q([...n.items??[],...n.menu??[]],t);if(e!==null)return e}return null}function he(e,t){return Q(e,e=>e.version===void 0||e.version===t)?.link??null}function $(e){let t=Q(e,e=>e.version===void 0||e.isDefaultVersion===!0);return t?.link===void 0?null:t.versionGroup!==void 0&&t.version!==void 0?f(t.link,t.versionGroup,t.version,!0):t.link}function ge(e){let[t]=e;if(t===void 0)return null;let n=t.path.split(`/`).length;return(e.find(({path:e})=>e.split(`/`).length===n&&P.test(e))??t).link}function _e(e){let t=null;for(let{slug:n,originFilePath:r,locale:a,versionGroup:o}of e)r!==null&&a===``&&o===null&&(t===null||n.length<t.length||n.length===t.length&&i(n,t)<0)&&(t=n);return t}const ve=e({id:j,version:`1.28.0`,content:{filter:{match:e=>N.test(e)},async extractFile(e,t){let n=await t.io.readFile(e.path);return{routes:[],linkRefs:await b({source:n,filePath:e.path,readFile:t.io.readFile})}}},async finalize(e){let t=[],r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=[],c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,d=[],f=await Promise.all(e.files.map(async t=>({path:t.path,source:await e.io.readFile(t.path)}))),m=e.routes.all(),g=re(m,e.localeContext),_=ee(m),v=_.length>0?_:void 0;f.sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length);let b=new Map(f.map(({path:e,source:t})=>[e,t])),S=/* @__PURE__ */ new Map;for(let{path:e}of f)P.test(e)&&S.set(k.dirname(e),e);let w=/* @__PURE__ */ new Set;for(let{path:e,source:t}of f)for(let n of x(t,e))w.add(n);let j=await p({io:e.io,routes:e.routes,versionedDirectories:_}),M={routes:e.routes,versionGroups:j,report:e=>r.push(e),readFile:async t=>b.get(t)??e.io.readFile(t),exists:t=>e.io.exists(t),sidebarByDirectory:S},N=async(n,r)=>{if(n.nodes.length===0)return;ne(n.nodes,j);let i=Y.withArgs({nodes:n.nodes,versionedDirectories:v},r===void 0?void 0:{metadata:{sourcePath:r}});t.push(i),l.set(i,n.nodes);let a=/* @__PURE__ */ new Map;for(let r of e.localeContext.locales){let e=Y.withArgs({nodes:n.nodes,locale:r,slugOverrides:g[r]??{},versionedDirectories:v});t.push(e),a.set(r,e)}return c.set(i,a),i};for(let{path:t,source:n}of f){if(w.has(t))continue;let c=await y({...M,file:{path:t},source:n}),l=await N(c,t);if(l===void 0)continue;a.set(t,l);let u=t.startsWith(`@l10n/`)?null:$(c.nodes);u!==null&&d.push({path:t,link:u}),s.push(await Z(c,e));for(let e of c.assignedRouteSlugs){let n=o.get(e);n!==void 0&&r.push({code:`sidebar/route-conflict`,message:`Page "${e}" is in sidebars ${n} and ${t}; it shows ${t}.`,location:{filePath:t}}),i.set(e,l),o.set(e,t)}}le(i,s);let I=new Map(m.map(e=>[e.slug,e]));for(let[t,n]of Object.entries(e.routes.metadata(`sidebar`))){let e=I.get(t);if(e===void 0||e.originFilePath===null)continue;let o=ce(n);if(o===null)continue;let s=k.normalize(o.startsWith(`/`)?o.slice(1):k.join(k.dirname(e.originFilePath),o)),c=a.get(s);if(c===void 0){r.push({code:`sidebar/missing-target`,message:`Front matter sidebar "${o}" is not a sidebar file of this project.`,location:{filePath:e.originFilePath}});continue}i.set(e.slug,c)}let L=await ue(e.entities),R=/* @__PURE__ */ new Set,z=/* @__PURE__ */ new Map,B=/* @__PURE__ */ new Map;for(let t of L){let n=i.get(t.route);if(n===void 0){let r=await te({...M,file:{path:F},entries:t.entries});if(n=await N(r),n===void 0)continue;let a=(await Z(r,e)).keys();for(let e of[...r.assignedRouteSlugs,...a])i.has(e)||(i.set(e,n),R.add(e))}let r=z.get(n);z.set(n,r===void 0?t.backLink??null:r!==null&&r.link===t.backLink?.link?r:null);let a=B.get(n);B.set(n,a===void 0?t.breadcrumbs??[]:de(a,t.breadcrumbs))}if(f.length===0&&m.length>0){let e=await y({...M,file:{path:F},source:`- directory: .
2
2
  `,skipRoutes:R}),t=await N(e);if(t!==void 0){for(let n of e.assignedRouteSlugs)i.has(n)||i.set(n,t);let n=$(e.nodes);n!==null&&d.push({path:F,link:n})}}let V=ge(d)??_e(m);if(V!==null){let{path:e}=u(V);t.push(n(e,{stableKey:O}))}let H=/* @__PURE__ */ new Map;for(let e of m){if(e.originFilePath===null)continue;let t=X(e);H.set(t,[...H.get(t)??[],e.slug])}for(let[e,t]of[...i]){let n=I.get(e);for(let e of(n&&H.get(X(n)))??[])i.has(e)||i.set(e,t)}let U=/* @__PURE__ */ new Map,W=(e.config.navbar?.items??[]).filter(e=>e.linkedSidebars?.length),G=/* @__PURE__ */ new Map;for(let[t,n]of await fe(W,e.routes,j,a,t=>e.entities.tryLoad(t)))B.set(t,[n,...B.get(t)??[]]);let K=({label:t,link:n,icon:r})=>({label:t,link:n,icon:r,[A]:h(n,e.routes,j)??void 0});for(let[e,r]of z){if(r===null)continue;let i=n(K(r));t.push(i),U.set(e,i)}for(let[e,r]of B){if(r.length===0)continue;let i=n(r.map(K));t.push(i),G.set(e,i)}for(let r of new Set(L.map(e=>e.route))){let a=i.get(r),o=a===void 0?void 0:l.get(a),s=o===void 0?null:he(o,e.routes.bySlug(r)?.version??null);s!==null&&t.push(n(s,{stableKey:C(r)}))}return{entities:t,attach:[...i.entries()].map(([e,t])=>{let n={[D]:t},r=U.get(t);r!==void 0&&(n[T]=r);let i=G.get(t);if(i!==void 0&&(n[E]=i),I.get(e)?.locale===``)for(let[e,r]of c.get(t)??[])n[ie(e)]=r;return{slug:e,deps:n}}),problems:r}},loaders:[Y]});export{P as FOLDER_SIDEBAR_FILENAME_REGEX,M as SIDEBAR_AGGREGATOR_LOADER_ID,N as SIDEBAR_FILENAME_REGEX,j as SIDEBAR_PLUGIN_ID,D as SIDEBAR_ROUTE_DEP_KEY,L as isTabbedSidebar,se as resolveAutoSidebar,ve as sidebarContentPlugin};
@@ -1 +1 @@
1
- import{defineContentPlugin as e}from"../../define.js";import{toJsonValue as t}from"../../../database/utils/json.js";import{createInlineEntityReference as n}from"../../../loaders/define.js";import{normalizeRouteSlug as r}from"../../../../shared/utils/routes/normalize-route-slug.js";import{slugifySegment as i}from"../../../../shared/utils/routes/slugify-segment.js";import{versionDefaultEntityKey as a,versionsConfigEntityKey as o}from"../../../../shared/constants/versions.js";import{collectVersionGroups as s,findVersionedDirectories as c}from"../../../versions/version-groups.js";import{posix as l}from"node:path";import u from"js-yaml";const d=`internal.versions`,f=`versions.yaml`;function p(e){let t=l.dirname(e);return t===`.`?`/`:r(t.split(`/`).map(e=>i(e)).join(`/`))}const m=e({id:d,version:`1.2.0`,content:{filter:{match:e=>e===f||e.endsWith(`/${f}`)},async extractFile(e,r){let i=await r.io.readFile(e.path),a=u.load(i);return{routes:[],entities:[n(t(a??{}),{stableKey:o(p(e.path))})]}}},async finalize(e){return{entities:[...await s({io:e.io,routes:e.routes,versionedDirectories:c(e.routes.all())})].map(([e,t])=>n(t.defaultVersion,{stableKey:a(e)}))}}});export{d as VERSIONS_PLUGIN_ID,m as versionsContentPlugin};
1
+ import{defineContentPlugin as e}from"../../define.js";import{toJsonValue as t}from"../../../database/utils/json.js";import{createInlineEntityReference as n}from"../../../loaders/define.js";import{normalizeRouteSlug as r}from"../../../../shared/utils/routes/normalize-route-slug.js";import{slugifySegment as i}from"../../../../shared/utils/routes/slugify-segment.js";import{versionDefaultEntityKey as a,versionsConfigEntityKey as o}from"../../../../shared/constants/versions.js";import{collectVersionGroups as s,findVersionedDirectories as c}from"../../../versions/version-groups.js";import{posix as l}from"node:path";import u from"js-yaml";const d=`internal.versions`,f=`versions.yaml`;function p(e){let t=l.dirname(e);return t===`.`?`/`:r(t.split(`/`).map(e=>i(e)).join(`/`))}const m=e({id:d,version:`1.3.0`,content:{filter:{match:e=>e===f||e.endsWith(`/${f}`)},async extractFile(e,r){let i=await r.io.readFile(e.path),a=u.load(i);return{routes:[],entities:[n(t(a??{}),{stableKey:o(p(e.path))})]}}},async finalize(e){return{entities:[...await s({io:e.io,routes:e.routes,versionedDirectories:c(e.routes.all())})].map(([e,t])=>n(t.defaultVersion,{stableKey:a(e)}))}}});export{d as VERSIONS_PLUGIN_ID,m as versionsContentPlugin};
@@ -1 +1 @@
1
- import{hashJsonValue as e,toStableJsonString as t}from"../../database/utils/json.js";import{compareStrings as n}from"../../../shared/utils/compare-strings.js";import{compileRouteAccessMatcher as r}from"../../../shared/rbac/engine.js";import{computePathPrefixes as i}from"../../../shared/utils/routes/compute-path-prefixes.js";import{normalizeRoutePath as a}from"../../../shared/utils/routes/normalize-route-path.js";import{resolveRouteScope as o}from"../../../shared/rbac/route-scope.js";import{hashEntityListMembership as s,hashEntityRead as c}from"../../database/entity-store.js";import{getRouteByFilePath as l,getRouteBySlug as u,getRoutesInDirectory as d}from"./state-lookup.js";function f(e,t){let f=r(t),m=e=>f===null?null:o(f,{hasRbacKey:`rbac`in e.metadata,rbacValue:e.metadata.rbac,slug:e.slug,sourcePath:e.originFilePath},()=>{}),h=e=>{let t=[];for(let n of e)t.push(v(n));return t.sort((e,t)=>n(e.slug,t.slug))};function*g(t){for(let n of e.routeBySlug.values())!n.isFallback&&(t===void 0||t(n))&&(yield n)}let y=e=>e!==void 0&&!e.isFallback?e:void 0,b=t=>{let n=a(t),r=y(u(e,n));if(r)return r;let o=i(n),s;for(let e of g(e=>e.wildcardPrefix&&o.includes(e.slug)))(s===void 0||e.slug.length>s.slug.length)&&(s=e);return s};function x(t,r){switch(t){case`byFilePath`:{let t=l(e,r);return _(t?v(t):void 0)}case`bySlug`:{let t=y(u(e,r));return _(t?v(t):void 0)}case`inDirectory`:return _(h(d(e,r)));case`all`:return _(h(g()));case`get`:{let t=y(u(e,r));return _(t?{...v(t),metadata:t.metadata,access:m(t)}:void 0)}case`getAccess`:{let e=b(r);return _(e?m(e):void 0)}case`list`:{let{sidebarKey:e}=JSON.parse(r);return _(h(g(t=>t.sidebarSubtreeEntityKey===e)))}case`metadata`:{let e={};for(let t of[...g()].sort((e,t)=>n(e.slug,t.slug)))Object.hasOwn(t.metadata,r)&&(e[t.slug]=t.metadata[r]);return _(e)}case`entity`:return{value:void 0,hash:c(e,r)};case`entity-type`:return{value:void 0,hash:s(e,r)};default:return{value:void 0,hash:``}}}return p(x)}function p(e){return{hash:(t,n)=>e(t,n).hash,index(n){let r=(t,r)=>{let i=e(t,r);return n?.({kind:t,argument:r,resultHash:i.hash}),i.value};return{byFilePath:e=>r(`byFilePath`,e),bySlug:e=>r(`bySlug`,e),inDirectory:e=>r(`inDirectory`,e),all:()=>r(`all`,``),get:e=>r(`get`,e),getAccess:e=>r(`getAccess`,e),list:e=>r(`list`,t({sidebarKey:e.sidebarKey})),metadata:e=>r(`metadata`,e)}},memoized(){let t=/* @__PURE__ */ new Map;return p((n,r)=>{if(n===`entity`||n===`entity-type`)return e(n,r);let i=`${n}\u0000${r}`,a=t.get(i);return a===void 0&&(a=e(n,r),t.set(i,a)),a})}}}function m(e,t,n){return f(e,t).index(n)}function h(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(`${n.kind}\u0000${n.argument}`,n);return[...t.values()].sort((e,t)=>n(e.kind,t.kind)||n(e.argument,t.argument))}function g(e,t){return e.hash(t.kind,t.argument)!==t.resultHash}function _(t){return{value:t,hash:e(t===void 0?`absent`:t)}}function v(e){return{slug:e.slug,routeId:e.routeId,originPluginId:e.originPluginId,originFilePath:e.originFilePath,versionGroup:e.versionGroup,version:e.version,sidebarSubtreeEntityKey:e.sidebarSubtreeEntityKey,template:e.template,locale:e.locale,canonicalSlug:e.canonicalSlug}}export{m as createRouteIndex,f as createRouteQueryEvaluator,h as dedupeRouteQueryDependencies,g as isRouteQueryStale};
1
+ import{hashJsonValue as e,toStableJsonString as t}from"../../database/utils/json.js";import{compareStrings as n}from"../../../shared/utils/compare-strings.js";import{compileRouteAccessMatcher as r}from"../../../shared/rbac/engine.js";import{computePathPrefixes as i}from"../../../shared/utils/routes/compute-path-prefixes.js";import{normalizeRoutePath as a}from"../../../shared/utils/routes/normalize-route-path.js";import{resolveRouteScope as o}from"../../../shared/rbac/route-scope.js";import{hashEntityListMembership as s,hashEntityRead as c}from"../../database/entity-store.js";import{getRouteByFilePath as l,getRouteBySlug as u,getRoutesInDirectory as d}from"./state-lookup.js";function f(e,t){let f=r(t),m=e=>f===null?null:o(f,{hasRbacKey:`rbac`in e.metadata,rbacValue:e.metadata.rbac,slug:e.slug,sourcePath:e.originFilePath},()=>{}),h=e=>{let t=[];for(let n of e)t.push(v(n));return t.sort((e,t)=>n(e.slug,t.slug))};function*g(t){for(let n of e.routeBySlug.values())!n.isFallback&&(t===void 0||t(n))&&(yield n)}let y=e=>e!==void 0&&!e.isFallback?e:void 0,b=t=>{let n=a(t),r=y(u(e,n));if(r)return r;for(let t of i(n).reverse()){let n=y(u(e,t));if(n?.wildcardPrefix)return n}};function x(t,r){switch(t){case`byFilePath`:{let t=l(e,r);return _(t?v(t):void 0)}case`bySlug`:{let t=y(u(e,r));return _(t?v(t):void 0)}case`inDirectory`:return _(h(d(e,r)));case`all`:return _(h(g()));case`get`:{let t=y(u(e,r));return _(t?{...v(t),metadata:t.metadata,access:m(t)}:void 0)}case`getAccess`:{let e=b(r);return _(e?m(e):void 0)}case`list`:{let{sidebarKey:e}=JSON.parse(r);return _(h(g(t=>t.sidebarSubtreeEntityKey===e)))}case`metadata`:{let e={};for(let t of[...g()].sort((e,t)=>n(e.slug,t.slug)))Object.hasOwn(t.metadata,r)&&(e[t.slug]=t.metadata[r]);return _(e)}case`entity`:return{value:void 0,hash:c(e,r)};case`entity-type`:return{value:void 0,hash:s(e,r)};default:return{value:void 0,hash:``}}}return p(x)}function p(e){return{hash:(t,n)=>e(t,n).hash,index(n){let r=(t,r)=>{let i=e(t,r);return n?.({kind:t,argument:r,resultHash:i.hash}),i.value};return{byFilePath:e=>r(`byFilePath`,e),bySlug:e=>r(`bySlug`,e),inDirectory:e=>r(`inDirectory`,e),all:()=>r(`all`,``),get:e=>r(`get`,e),getAccess:e=>r(`getAccess`,e),list:e=>r(`list`,t({sidebarKey:e.sidebarKey})),metadata:e=>r(`metadata`,e)}},memoized(){let t=/* @__PURE__ */ new Map;return p((n,r)=>{if(n===`entity`||n===`entity-type`)return e(n,r);let i=`${n}\u0000${r}`,a=t.get(i);return a===void 0&&(a=e(n,r),t.set(i,a)),a})}}}function m(e,t,n){return f(e,t).index(n)}function h(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(`${n.kind}\u0000${n.argument}`,n);return[...t.values()].sort((e,t)=>n(e.kind,t.kind)||n(e.argument,t.argument))}function g(e,t){return e.hash(t.kind,t.argument)!==t.resultHash}function _(t){return{value:t,hash:e(t===void 0?`absent`:t)}}function v(e){return{slug:e.slug,routeId:e.routeId,originPluginId:e.originPluginId,originFilePath:e.originFilePath,versionGroup:e.versionGroup,version:e.version,sidebarSubtreeEntityKey:e.sidebarSubtreeEntityKey,template:e.template,locale:e.locale,canonicalSlug:e.canonicalSlug}}export{m as createRouteIndex,f as createRouteQueryEvaluator,h as dedupeRouteQueryDependencies,g as isRouteQueryStale};
@@ -1 +1 @@
1
- import{loadSiteConfig as e,resolveSiteConfig as t}from"../database/site-config.js";import{isRemoteDatabaseUrl as n}from"../database/utils/is-remote-database-url.js";import{openContentLayerDatabase as r,resolveLocalDatabasePath as i}from"../database/connection.js";import{garbageCollectOrphanBlobs as a,getBlob as o}from"../database/blobs.js";import{createEntityStore as s,loadCurrentEntityMetadata as c}from"../database/entity-store.js";import{listAssetSourcePaths as l}from"../database/assets.js";import{loadEntityRecordByKey as u}from"../database/entities.js";import{listProblemsForEntity as d}from"../database/problems.js";import{listRoutePagesByFile as f}from"../database/files.js";import{listStaticFileRecords as p}from"../database/static-files.js";import{createKvStore as m}from"../database/kv.js";export{s as createEntityStore,m as createKvStore,a as garbageCollectOrphanBlobs,o as getBlob,n as isRemoteDatabaseUrl,l as listAssetSourcePaths,d as listProblemsForEntity,f as listRoutePagesByFile,p as listStaticFileRecords,c as loadCurrentEntityMetadata,u as loadEntityRecordByKey,e as loadSiteConfig,r as openContentLayerDatabase,i as resolveLocalDatabasePath,t as resolveSiteConfig};
1
+ import{loadSiteConfig as e,resolveSiteConfig as t}from"../database/site-config.js";import{isRemoteDatabaseUrl as n}from"../database/utils/is-remote-database-url.js";import{openContentLayerDatabase as r,resolveLocalDatabasePath as i}from"../database/connection.js";import{garbageCollectOrphanBlobs as a,getBlob as o}from"../database/blobs.js";import{createEntityStore as s,loadCurrentEntityMetadata as c}from"../database/entity-store.js";import{listAssetSourcePaths as l}from"../database/assets.js";import{loadEntityRecordByKey as u,loadSiteStart as d}from"../database/entities.js";import{listProblemsForEntity as f}from"../database/problems.js";import{listRoutePagesByFile as p}from"../database/files.js";import{listStaticFileRecords as m}from"../database/static-files.js";import{createKvStore as h}from"../database/kv.js";export{s as createEntityStore,h as createKvStore,a as garbageCollectOrphanBlobs,o as getBlob,n as isRemoteDatabaseUrl,l as listAssetSourcePaths,f as listProblemsForEntity,p as listRoutePagesByFile,m as listStaticFileRecords,c as loadCurrentEntityMetadata,u as loadEntityRecordByKey,e as loadSiteConfig,d as loadSiteStart,r as openContentLayerDatabase,i as resolveLocalDatabasePath,t as resolveSiteConfig};
@@ -16,6 +16,7 @@ export type VersionGroupInfo = {
16
16
  * Pure core of version-group resolution, shared by the catalog and the
17
17
  * sidebar bundler. Without versions.yaml, detected versions sort newest
18
18
  * first and the highest is the default. versions.yaml controls order and
19
- * visibility; its `default` wins, else the last listed version.
19
+ * visibility; its `default` wins, else the last listed version. Its entries
20
+ * match the detected versions, which are folder slugs, by their slug form.
20
21
  */
21
22
  export declare function computeVersionGroupInfo(detectedUnsorted: readonly string[], config: VersionsYamlConfig | null): VersionGroupInfo;
@@ -1 +1 @@
1
- import{compareVersions as e}from"../../shared/constants/versions.js";function t(t,n){let r=[...t].sort((t,n)=>e(n,t)),i=/* @__PURE__ */ new Map,a=r,o=!1;if(n?.versions&&Array.isArray(n.versions)&&n.versions.length>0){let e=[];for(let t of n.versions){let n=typeof t==`string`?t:t?.version;if(typeof n==`string`&&n.trim()!==``&&(e.push(n),typeof t==`object`)){let e=typeof t.label==`string`?t.label:t.name;typeof e==`string`&&i.set(n,e)}}a=e.filter(e=>r.includes(e)),o=a.length>0}let s=typeof n?.default==`string`&&a.includes(n.default)?n.default:null;return{versions:a,defaultVersion:s??(o?a.at(-1):a[0])??null,labels:i}}export{t as computeVersionGroupInfo};
1
+ import{slugifySegment as e}from"../../shared/utils/routes/slugify-segment.js";import{compareVersions as t}from"../../shared/constants/versions.js";function n(n,r){let i=[...n].sort((e,n)=>t(n,e)),a=/* @__PURE__ */ new Map,o=i,s=!1;if(r?.versions&&Array.isArray(r.versions)&&r.versions.length>0){let t=[];for(let n of r.versions){let r=typeof n==`string`?n:n?.version;if(typeof r!=`string`||r.trim()===``)continue;let i=e(r);if(t.includes(i))continue;t.push(i);let o=(typeof n==`object`?[n.label,n.name].find(e=>typeof e==`string`):void 0)??(r===i?void 0:r);o!==void 0&&a.set(i,o)}o=t.filter(e=>i.includes(e)),s=o.length>0}let c=typeof r?.default==`string`?e(r.default):void 0,l=c!==void 0&&o.includes(c)?c:null;return{versions:o,defaultVersion:l??(s?o.at(-1):o[0])??null,labels:a}}export{n as computeVersionGroupInfo};