xmcp 1.11.0 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/client/handlers.d.ts +16 -0
- package/dist/client/index.d.ts +6 -1
- package/dist/client/managed.d.ts +3 -9
- package/dist/client.js +2 -2
- package/dist/cloudflare.js +1 -1
- package/dist/config/index.d.ts +165 -1
- package/dist/config/schemas/cache-hints.d.ts +119 -0
- package/dist/config/schemas/index.d.ts +1 -0
- package/dist/config.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +15 -15
- package/dist/runtime/adapter-express.js +16 -24
- package/dist/runtime/adapter-fastify.js +16 -24
- package/dist/runtime/adapter-fetch-cloudflare.js +21 -29
- package/dist/runtime/adapter-fetch.js +16 -24
- package/dist/runtime/adapter-nestjs.js +16 -24
- package/dist/runtime/adapter-nextjs.js +16 -24
- package/dist/runtime/cloudflare-worker.js +23 -31
- package/dist/runtime/contexts/request-context.d.ts +6 -0
- package/dist/runtime/http.js +22 -30
- package/dist/runtime/stdio.js +19 -27
- package/dist/runtime/utils/schema-compat.d.ts +26 -0
- package/dist/runtime/utils/server.d.ts +5 -2
- package/dist/runtime/utils/transformers/tool.d.ts +4 -3
- package/dist/runtime/vercel.js +23 -31
- package/dist/types/resource.d.ts +7 -1
- package/dist/types/tool.d.ts +5 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
<div align="center">
|
|
3
2
|
|
|
4
3
|
<a href="https://xmcp.dev">
|
|
@@ -13,7 +12,6 @@
|
|
|
13
12
|
<a href="https://www.npmjs.com/package/xmcp"><img alt="NPM version" src="https://img.shields.io/npm/v/xmcp.svg?style=for-the-badge&labelColor=000000"></a>
|
|
14
13
|
<a href="https://github.com/basementstudio/xmcp/blob/main/license.md"><img alt="License" src="https://img.shields.io/npm/l/xmcp.svg?style=for-the-badge&labelColor=000000"></a>
|
|
15
14
|
|
|
16
|
-
|
|
17
15
|
</div>
|
|
18
16
|
<div align="center">
|
|
19
17
|
<a href="https://vercel.com/open-source-program">
|
|
@@ -84,3 +82,7 @@ If you believe you have found a security vulnerability, we encourage you to let
|
|
|
84
82
|
We will investigate all legitimate reports and do our best to quickly fix the problem.
|
|
85
83
|
|
|
86
84
|
Please report any vulnerabilities in our open source repositories to [security@xmcp.dev](mailto:security@xmcp.dev).
|
|
85
|
+
|
|
86
|
+
### Node.js module compatibility
|
|
87
|
+
|
|
88
|
+
The `xmcp` root entry supports both CommonJS `require("xmcp")` and native ESM named imports, including `import { createContext } from "xmcp"` used by provider plugins. Production `xmcp build` exits with a nonzero status on compilation errors, so deployment scripts stop before starting an invalid build.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Client, ClientCapabilities, ClientContext, HandlerResultTypeMap, RequestTypeMap } from "@modelcontextprotocol/client";
|
|
2
|
+
type Handler<Method extends keyof RequestTypeMap> = (request: RequestTypeMap[Method], context: ClientContext) => HandlerResultTypeMap[Method] | Promise<HandlerResultTypeMap[Method]>;
|
|
3
|
+
export interface ClientHandlers {
|
|
4
|
+
sampling?: Handler<"sampling/createMessage">;
|
|
5
|
+
/** Handles both form and URL elicitation requests. */
|
|
6
|
+
elicitation?: Handler<"elicitation/create">;
|
|
7
|
+
roots?: Handler<"roots/list">;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Advertise only what the client can serve: servers use these capabilities to
|
|
11
|
+
* decide which requests (and multi round-trip inputs) to send.
|
|
12
|
+
*/
|
|
13
|
+
export declare function capabilitiesForHandlers(handlers: ClientHandlers): ClientCapabilities;
|
|
14
|
+
/** Install handlers before connecting so they are ready during negotiation. */
|
|
15
|
+
export declare function registerClientHandlers(client: Client, handlers: ClientHandlers): void;
|
|
16
|
+
export {};
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Client } from "@modelcontextprotocol/client";
|
|
2
2
|
import { StdioClientTransport, type StdioServerParameters } from "@modelcontextprotocol/client/stdio";
|
|
3
3
|
import type { Buffer } from "node:buffer";
|
|
4
|
+
import { type ClientHandlers } from "./handlers";
|
|
4
5
|
import { CustomHeaders } from "./headers";
|
|
5
6
|
export declare const CLIENT_IDENTITY: {
|
|
6
7
|
name: any;
|
|
@@ -10,17 +11,21 @@ interface HttpClientOptions {
|
|
|
10
11
|
/** Full MCP server base URL — example: https://host.tld/mcp */
|
|
11
12
|
url: string;
|
|
12
13
|
headers?: CustomHeaders;
|
|
14
|
+
/** Sampling, elicitation, and roots handlers; only these are advertised. */
|
|
15
|
+
handlers?: ClientHandlers;
|
|
13
16
|
}
|
|
14
17
|
/**
|
|
15
18
|
* Pure direct HTTP MCP client (no proxy, no SSE, no stdio)
|
|
16
19
|
*/
|
|
17
|
-
export declare function createHTTPClient({ url, headers, }: HttpClientOptions): Promise<Client>;
|
|
20
|
+
export declare function createHTTPClient({ url, headers, handlers, }: HttpClientOptions): Promise<Client>;
|
|
18
21
|
export interface StdioClientOptions extends StdioServerParameters {
|
|
19
22
|
/**
|
|
20
23
|
* Optional hook that receives stderr chunks when the transport
|
|
21
24
|
* runs with piped stderr (defaults to logging to console.error).
|
|
22
25
|
*/
|
|
23
26
|
onStderrData?: (chunk: Buffer) => void;
|
|
27
|
+
/** Sampling, elicitation, and roots handlers; only these are advertised. */
|
|
28
|
+
handlers?: ClientHandlers;
|
|
24
29
|
}
|
|
25
30
|
export interface StdioClientConnection {
|
|
26
31
|
client: Client;
|
package/dist/client/managed.d.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import { Client, type
|
|
1
|
+
import { Client, type ClientOptions, type ConnectOptions } from "@modelcontextprotocol/client";
|
|
2
|
+
import { type ClientHandlers } from "./handlers";
|
|
2
3
|
import type { ClientDefinition } from "./types";
|
|
3
|
-
type
|
|
4
|
-
export interface ClientHandlers {
|
|
5
|
-
sampling?: Handler<"sampling/createMessage">;
|
|
6
|
-
/** Handles both form and URL elicitation requests. */
|
|
7
|
-
elicitation?: Handler<"elicitation/create">;
|
|
8
|
-
roots?: Handler<"roots/list">;
|
|
9
|
-
}
|
|
4
|
+
export type { ClientHandlers } from "./handlers";
|
|
10
5
|
export interface ManagedClientOptions {
|
|
11
6
|
handlers?: ClientHandlers;
|
|
12
7
|
/** Defaults to automatic modern/legacy protocol negotiation. */
|
|
@@ -20,4 +15,3 @@ export interface ManagedClientOptions {
|
|
|
20
15
|
export declare function createClient(definition: ClientDefinition, options?: ManagedClientOptions): Promise<Client>;
|
|
21
16
|
/** Run an operation and close the connection even when the operation fails. */
|
|
22
17
|
export declare function withClient<T>(definition: ClientDefinition, operation: (client: Client) => T | Promise<T>, options?: ManagedClientOptions): Promise<T>;
|
|
23
|
-
export {};
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{var e,t,r={6507(e,t,r){"use strict";let o=r(5317),i=r(8388),a=r(442);function n(e,t,r){let n=i(e,t,r),s=o.spawn(n.command,n.args,n.options);return a.hookChildProcess(s,n),s}e.exports=n,e.exports.spawn=n,e.exports.sync=function(e,t,r){let n=i(e,t,r),s=o.spawnSync(n.command,n.args,n.options);return s.error=s.error||a.verifyENOENTSync(s.status,n),s},e.exports._parse=i,e.exports._enoent=a},442(e){"use strict";let t="win32"===process.platform;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,o){return t&&1===e&&!o.file?r(o.original,"spawn"):null}e.exports={hookChildProcess:function(e,r){if(!t)return;let i=e.emit;e.emit=function(t,a){if("exit"===t){let t=o(a,r);if(t)return i.call(e,"error",t)}return i.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,o){return t&&1===e&&!o.file?r(o.original,"spawnSync"):null},notFoundError:r}},8388(e,t,r){"use strict";let o=r(6928),i=r(3803),a=r(2077),n=r(1880),s="win32"===process.platform,l=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;e.exports=function(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null);let u={command:e,args:t=t?t.slice(0):[],options:r=Object.assign({},r),file:void 0,original:{command:e,args:t}};return r.shell?u:function(e){let t;if(!s)return e;let r=(e.file=i(e),(t=e.file&&n(e.file))?(e.args.unshift(e.file),e.command=t,i(e)):e.file),u=!l.test(r);if(e.options.forceShell||u){let t=c.test(r);e.command=o.normalize(e.command),e.command=a.command(e.command),e.args=e.args.map(e=>a.argument(e,t));let i=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${i}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(u)}},2077(e){"use strict";let t=/([()\][%!^"`<>&|;, *?])/g;e.exports.command=function(e){return e.replace(t,"^$1")},e.exports.argument=function(e,r){return e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1"),e=(e=`"${e}"`).replace(t,"^$1"),r&&(e=e.replace(t,"^$1")),e}},1880(e,t,r){"use strict";let o=r(9896),i=r(600);e.exports=function(e){let t,r=Buffer.alloc(150);try{t=o.openSync(e,"r"),o.readSync(t,r,0,150,0),o.closeSync(t)}catch(e){}return i(r.toString())}},3803(e,t,r){"use strict";let o=r(6928),i=r(1905),a=r(9695);function n(e,t){let r,n=e.options.env||process.env,s=process.cwd(),l=null!=e.options.cwd,c=l&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}try{r=i.sync(e.command,{path:n[a({env:n})],pathExt:t?o.delimiter:void 0})}catch(e){}finally{c&&process.chdir(s)}return r&&(r=o.resolve(l?e.options.cwd:"",r)),r}e.exports=function(e){return n(e)||n(e,!0)}},9344(e,t,r){var o;function i(e,t,r){if("function"==typeof t&&(r=t,t={}),!r){if("function"!=typeof Promise)throw TypeError("callback not provided");return new Promise(function(r,o){i(e,t||{},function(e,t){e?o(e):r(t)})})}o(e,t||{},function(e,o){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,o=!1),r(e,o)})}r(9896),o="win32"===process.platform||global.TESTING_WINDOWS?r(8541):r(709),e.exports=i,i.sync=function(e,t){try{return o.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}},709(e,t,r){e.exports=i,i.sync=function(e,t){return a(o.statSync(e),t)};var o=r(9896);function i(e,t,r){o.stat(e,function(e,o){r(e,!e&&a(o,t))})}function a(e,t){var r,o,i,a,n,s,l,c,u;return e.isFile()&&(r=e,o=t,i=r.mode,a=r.uid,n=r.gid,s=void 0!==o.uid?o.uid:process.getuid&&process.getuid(),l=void 0!==o.gid?o.gid:process.getgid&&process.getgid(),c=parseInt("100",8),u=parseInt("010",8),i&parseInt("001",8)||i&u&&n===l||i&c&&a===s||i&(c|u)&&0===s)}},8541(e,t,r){e.exports=a,a.sync=function(e,t){return i(o.statSync(e),e,t)};var o=r(9896);function i(e,t,r){if(!e.isSymbolicLink()&&!e.isFile())return!1;var o=void 0!==r.pathExt?r.pathExt:process.env.PATHEXT;if(!o||-1!==(o=o.split(";")).indexOf(""))return!0;for(var i=0;i<o.length;i++){var a=o[i].toLowerCase();if(a&&t.substr(-a.length).toLowerCase()===a)return!0}return!1}function a(e,t,r){o.stat(e,function(o,a){r(o,!o&&i(a,e,t))})}},9695(e){"use strict";let t=(e={})=>{let t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};e.exports=t,e.exports.default=t},600(e,t,r){"use strict";let o=r(7257);e.exports=(e="")=>{let t=e.match(o);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,"").split(" "),a=r.split("/").pop();return"env"===a?i:i?`${a} ${i}`:a}},7257(e){"use strict";e.exports=/^#!(.*)/},1905(e,t,r){let o="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,i=r(6928),a=o?";":":",n=r(9344),s=e=>Object.assign(Error(`not found: ${e}`),{code:"ENOENT"}),l=(e,t)=>{let r=t.colon||a,i=e.match(/\//)||o&&e.match(/\\/)?[""]:[...o?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],n=o?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=o?n.split(r):[""];return o&&-1!==e.indexOf(".")&&""!==s[0]&&s.unshift(""),{pathEnv:i,pathExt:s,pathExtExe:n}},c=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});let{pathEnv:o,pathExt:a,pathExtExe:c}=l(e,t),u=[],d=r=>new Promise((a,n)=>{if(r===o.length)return t.all&&u.length?a(u):n(s(e));let l=o[r],c=/^".*"$/.test(l)?l.slice(1,-1):l,d=i.join(c,e);a(p(!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d,r,0))}),p=(e,r,o)=>new Promise((i,s)=>{if(o===a.length)return i(d(r+1));let l=a[o];n(e+l,{pathExt:c},(a,n)=>{if(!a&&n)if(!t.all)return i(e+l);else u.push(e+l);return i(p(e,r,o+1))})});return r?d(0).then(e=>r(null,e),r):d(0)};e.exports=c,c.sync=(e,t)=>{let{pathEnv:r,pathExt:o,pathExtExe:a}=l(e,t=t||{}),c=[];for(let s=0;s<r.length;s++){let l=r[s],u=/^".*"$/.test(l)?l.slice(1,-1):l,d=i.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<o.length;e++){let r=p+o[e];try{if(n.sync(r,{pathExt:a}))if(!t.all)return r;else c.push(r)}catch(e){}}}if(t.all&&c.length)return c;if(t.nothrow)return null;throw s(e)}},5317(e){"use strict";e.exports=require("child_process")},9896(e){"use strict";e.exports=require("fs")},7598(e){"use strict";e.exports=require("node:crypto")},6928(e){"use strict";e.exports=require("path")},8330(e){"use strict";e.exports=JSON.parse('{"name":"xmcp","version":"1.11.0"}')}},o={};function i(e){var t=o[e];if(void 0!==t)return t.exports;var a=o[e]={exports:{}};return r[e](a,a.exports,i),a.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,o){if(1&o&&(r=this(r)),8&o||"object"==typeof r&&r&&(4&o&&r.__esModule||16&o&&"function"==typeof r.then))return r;var a=Object.create(null);i.r(a);var n={};e=e||[null,t({}),t([]),t(t)];for(var s=2&o&&r;("object"==typeof s||"function"==typeof s)&&!~e.indexOf(s);s=t(s))Object.getOwnPropertyNames(s).forEach(e=>{n[e]=()=>r[e]});return n.default=()=>r,i.d(a,n),a},i.d=(e,t,r)=>{var o=(t,r)=>{for(var o in t)i.o(t,o)&&!i.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,[r]:t[o]})};o(t,"get"),o(r,"value")},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};for(var n in(()=>{"use strict";let e,t,r,o,n,s,l,c,u,d,p,h,f,m,y,g,v,_,b,S;i.r(a),i.d(a,{createClient:()=>he,withClient:()=>ht});var w,$,R,P,k,x,E,O,T=Object.create,C=Object.defineProperty,j=Object.getOwnPropertyDescriptor,I=Object.getOwnPropertyNames,N=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),A=(e,t,r)=>(r=null!=e?T(N(e)):{},((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var o,i=I(t),a=0,n=i.length;a<n;a++)o=i[a],z.call(e,o)||void 0===o||C(e,o,{get:(e=>t[e]).bind(null,o),enumerable:!(r=j(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?r:C(r,"default",{value:e,enumerable:!0}),e));let M=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),L=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),U=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),D=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function V(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function F(e,t="|"){return e.map(e=>ed(e)).join(t)}function H(e,t){return"bigint"==typeof t?t.toString():t}class Z{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function J(e){return new Z(e)}function B(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let K=Symbol("evaluating");function G(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function W(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function X(e){return W(e._zod.def)??e._zod.def.shape}function Y(e,t,r){Object.defineProperty(e,t,{get(){let e=r();return G(this,t,e),e},enumerable:!0,configurable:!0})}function Q(e,t,r){t in e?G(e,t,r):e[t]=r}function ee(e,t,r,o){let i=X(t);for(let a of r){let r=Object.getOwnPropertyDescriptor(i,a);r.enumerable&&(r.get?Y(e,a,()=>{let e=t._zod.def.shape[a];return o?o(e,a):e}):Q(e,a,o?o(r.value,a):r.value))}}function et(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let er="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function eo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let ei=J(()=>{if(eM.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ea(e){if(!1===eo(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==eo(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function en(e){return ea(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let es=new Set(["string","number","symbol"]);function el(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ec(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function eu(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function ed(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}let ep={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},eh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ef(e,t){let r=X(e),o=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&o.push(e)}return o}function em(e,t){let r={};ee(r,e,Reflect.ownKeys(X(e)));var o=r,i=t;for(let e of Reflect.ownKeys(i)){let t=Object.getOwnPropertyDescriptor(i,e);t.enumerable&&(t.get?Y(o,e,()=>i[e]):Q(o,e,t.value))}return r}function ey(e,t,r,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${o}() cannot be used on object schemas containing refinements`);let a=r?new Set(ef(t,r)):void 0,n={};return ee(n,t,Reflect.ownKeys(X(t)),e&&((t,r)=>a&&!a.has(r)?t:new e({type:"optional",innerType:t}))),ec(t,et(t._zod.def,{shape:n,checks:[]}))}function eg(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ev(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function e_(e){return"string"==typeof e?e:e?.message}function eb(e){let t=[];for(let r of e??[]){let e=r._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let o=e.maximum??e.length??e.size;o>=0&&t.push([o,r])}return t}function eS(e,t,r){var o;for(let i=t;i<e.length;i++)(o=e[i]).schema??(o.schema=r)}function ew(e,t,r){let o=e.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?e.schema??(e.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:e_(e.inst?._zod.def?.error?.(e))??e_(i?.(e))??e_(t?.error?.(e))??e_(r.customError?.(e))??e_(r.localeError?.(e))??"Invalid input",n={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(n[t]=e[t]);return n.path??(n.path=[]),n.message=a,t?.reportInput&&(n.input=e.input),n}let e$=/[\uD800-\uDBFF]/;function eR(e){let t=e.length;if(!e$.test(e))return t;let r=t;for(let o=0;o<t-1;o++)(64512&e.charCodeAt(o))==55296&&(64512&e.charCodeAt(o+1))==56320&&(r--,o++);return r}function eP(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ek(...e){let[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}function ex(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function eE(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return ex(this,r,o(this))},set(e){ex(this,r,e)}})}return t}let eO=!1,eT={configurable:!0,get(){eO=!0}};function eC(t,r,o){let i=Object.getPrototypeOf(t._zod);if(r in i&&e!==t._zod){e=void 0;return}e=t._zod,Object.defineProperty(i,r,{configurable:!0,get(){Object.defineProperty(this,r,eT);let e=eO;eO=!1;try{let t=o(this);return eO?delete this[r]:Object.defineProperty(this,r,{configurable:!0,writable:!0,value:t}),eO=eO||e,t}catch(t){throw delete this[r],eO=eO||e,t}},set(e){Object.defineProperty(this,r,{configurable:!0,writable:!0,value:e})}})}let ej=Object.freeze({status:"aborted"}),eI={value:void 0,enumerable:!1},eN="captureStackTrace"in Error?Error:null;function ez(e,t,r,o){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let a=r&&new WeakSet;function n(o,n){if(o._zod){if(o._zod.traits.has(e))return}else{eI.value=new i(n);try{Object.defineProperty(o,"_zod",eI)}finally{eI.value=void 0}}if(o._zod.traits.add(e),t(o,n),a){let e=Object.getPrototypeOf(o),t=o._zod.constr.prototype,i=e;for(;i&&i!==t;)i=Object.getPrototypeOf(i);let n=i??e;if(!a.has(n)){a.add(n);var s=n,l=r;for(let e in l){let t=Object.getOwnPropertyDescriptor(l,e);t.get?Object.defineProperty(s,e,{...t,enumerable:!1}):function(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:ex(this,t,r.bind(this))},set(e){ex(this,t,e)}})}(s,e,t.value)}}}let u=c.prototype;for(let e in u)Object.prototype.hasOwnProperty.call(u,e)&&(e in o||(o[e]=u[e].bind(o)))}let s=o?.Parent??Object;class l extends s{}function c(e){let t=o?.Parent?function(e){let t=eN;if(t){let r=t.stackTraceLimit;if("number"==typeof r){try{t.stackTraceLimit=0}catch{return eN=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}(l):this;n(t,e);let r=t._zod.deferred;if(r){for(let e of r)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(c,"init",{value:n}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!o?.Parent&&t instanceof o.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class eq extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eA extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(x=globalThis).__zod_globalConfig??(x.__zod_globalConfig={});let eM=globalThis.__zod_globalConfig;function eL(e){return e&&Object.assign(eM,e),eM}class eU extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eD="~memo",eV=[];function eF(e){return null!==e&&"object"==typeof e}function eH(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let eZ=new WeakMap,eJ=[],eB={alloc(e,r,o){let i=t;if(!i)return o;t=void 0;let a={value:o,issues:null};return i.set(r.value,a),eJ.push(a),o},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,r=(e,r)=>{var o,i;let a;if("backward"!==r.direction&&(o=r,i=e.value,void 0!==(a=o[eD]?.backEdges)&&eF(i)&&a.has(i)))throw new eU;return t(e,r)};e._zod.parse=r,e._zod.run===t&&(e._zod.run=r)})},attach(e){var r;let o,i,a,n=!1;(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,s=(l,c)=>{let u;if(void 0===o){let t=function e(t,r,o){var i,a;let n=eZ.get(t);if(void 0!==n)return 2*!!n;if(r.has(t))return 2;r.add(t);let s=0,l=t=>{if(2!==s&&t?._zod){let i=e(t,r,o);i>s&&(s=i)}},c=e=>{e>s&&(s=e)},u=t._zod.def;switch(u.type){case"object":{let t=W(u);c(t?((t,i)=>{let a=0;for(let n of Reflect.ownKeys(t)){let s=Object.getOwnPropertyDescriptor(t,n);if(i&&!s.enumerable)continue;let l=s.get?1:s.value?._zod?e(s.value,r,o):0;l>a&&(a=l)}return a})(t,!0):1),l(u.catchall);break}case"array":l(u.element);break;case"tuple":for(let e of u.items)l(e);l(u.rest);break;case"record":case"map":l(u.keyType),l(u.valueType);break;case"set":l(u.valueType);break;case"union":for(let e of u.options)l(e);break;case"intersection":l(u.left),l(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":l(u.innerType);break;case"pipe":l(u.in),l(u.out);break;case"function":l(u.input),l(u.output);break;case"lazy":{let i=u._cachedInner??(o?t._zod.innerType:void 0);c(i?e(i,r,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in u){let t=Object.getOwnPropertyDescriptor(u,e);if(!t||t.get)continue;let r=t.value;if(r&&"object"==typeof r){if(r._zod)l(r);else if(Array.isArray(r))for(let e of r)l(e)}}}return r.delete(t),i=t,1!==(a=s)&&eZ.set(i,2===a),a}(e,new Set,!1);if(0===t)return e._zod.parse=r,e._zod.run===s&&(e._zod.run=r),r(l,c);2===t||n?o=!0:n=!0}let d=l.value;if(!eF(d))return r(l,c);let p=c[eD];if(p||(p={buckets:new WeakMap,backEdges:void 0},c[eD]=p),i===c)u=a;else{var h,f;let t;h=p,f=e,(t=h.buckets.get(f))||(t=new WeakMap,h.buckets.set(f,t)),u=t,i=c,a=u}let m=u.get(d);if(m)return l.value=m.value,m.issues?m.issues.length&&l.issues.push(...eH(m.issues)):(l.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(m.value)),l;t=u;let y=eJ.length,g=r(l,c);t=void 0;let v=eJ.length>y?eJ.pop():void 0;return g instanceof Promise?g.then(e=>(v&&(v.issues=e.issues.length?eH(e.issues):eV),e)):(v&&(v.issues=g.issues.length?eH(g.issues):eV),g)};e._zod.parse=s,e._zod.run===r&&(e._zod.run=s)})}},eK=/^[cC][0-9a-z]{6,}$/,eG=/^[0-9a-z]+$/,eW=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,eX=/^[0-9a-vA-V]{20}$/,eY=/^[A-Za-z0-9]{27}$/,eQ=/^[a-zA-Z0-9_-]{21}$/,e0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,e1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,e2=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,e9=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,e4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,e3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,e5=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,e6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e8=/^https?$/,e7=/^\+[1-9]\d{6,14}$/,te="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",tt=(w=te,RegExp(`^${w}$`));function tr(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let to=/^[\s\S]{0,}$/,ti=/^-?\d+$/,ta=/^-?\d+(?:\.\d+)?$/,tn=/^(?:true|false)$/i,ts=/^null$/i,tl=/^[^A-Z]*$/,tc=/^[^a-z]*$/,tu=ez("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),td=e=>{let t=e.value;return null!=t&&void 0!==t.length},tp={number:"number",bigint:"bigint",object:"date"},th=ez("$ZodCheckLessThan",(e,t)=>{tu.init(e,t);let r=tp[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:tp[typeof o.value]??r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tf=ez("$ZodCheckGreaterThan",(e,t)=>{tu.init(e,t);let r=tp[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:tp[typeof o.value]??r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tm=ez("$ZodCheckMultipleOf",(e,t)=>{tu.init(e,t),e._zod.check=r=>{var o;let i,a,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):0==(a=Math.round(i=(o=r.value)/t.value),n=4*Number.EPSILON*Math.max(Math.abs(i),1),Math.abs(i-a)<n?0:i-a))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ty=ez("$ZodCheckNumberFormat",(e,t)=>{tu.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[i,a]=ep[t.format];e._zod.check=n=>{let s=n.value;if(r){if(!Number.isInteger(s))return void n.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?n.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):n.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}))}s<i&&n.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&n.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),tg=ez("$ZodCheckMaxLength",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length;if(("string"==typeof o&&i>t.maximum?eR(o):i)<=t.maximum)return;let a=eP(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tv=ez("$ZodCheckMinLength",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length;if(("string"==typeof o&&i>=t.minimum&&i<2*t.minimum?eR(o):i)>=t.minimum)return;let a=eP(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),t_=ez("$ZodCheckLengthEquals",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length,a="string"==typeof o&&i>=t.length&&i<=2*t.length?eR(o):i;if(a===t.length)return;let n=eP(o),s=a>t.length;r.issues.push({origin:n,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tb=ez("$ZodCheckStringFormat",(e,t)=>{var r,o;tu.init(e,t),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),tS=ez("$ZodCheckRegex",(e,t)=>{tb.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tw=ez("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tl),tb.init(e,t)}),t$=ez("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tc),tb.init(e,t)}),tR=ez("$ZodCheckIncludes",(e,t)=>{tu.init(e,t);let r=el(t.includes),o=new RegExp("number"==typeof t.position?`^.{${t.position},}${r}`:r);t.pattern=o,e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),tP=ez("$ZodCheckStartsWith",(e,t)=>{tu.init(e,t);let r=RegExp(`^${el(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),tk=ez("$ZodCheckEndsWith",(e,t)=>{tu.init(e,t);let r=RegExp(`.*${el(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),tx=ez("$ZodCheckOverwrite",(e,t)=>{tu.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class tE{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
1
|
+
(()=>{var e,t,r={6507(e,t,r){"use strict";let o=r(5317),i=r(8388),a=r(442);function n(e,t,r){let n=i(e,t,r),s=o.spawn(n.command,n.args,n.options);return a.hookChildProcess(s,n),s}e.exports=n,e.exports.spawn=n,e.exports.sync=function(e,t,r){let n=i(e,t,r),s=o.spawnSync(n.command,n.args,n.options);return s.error=s.error||a.verifyENOENTSync(s.status,n),s},e.exports._parse=i,e.exports._enoent=a},442(e){"use strict";let t="win32"===process.platform;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,o){return t&&1===e&&!o.file?r(o.original,"spawn"):null}e.exports={hookChildProcess:function(e,r){if(!t)return;let i=e.emit;e.emit=function(t,a){if("exit"===t){let t=o(a,r);if(t)return i.call(e,"error",t)}return i.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,o){return t&&1===e&&!o.file?r(o.original,"spawnSync"):null},notFoundError:r}},8388(e,t,r){"use strict";let o=r(6928),i=r(3803),a=r(2077),n=r(1880),s="win32"===process.platform,l=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;e.exports=function(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null);let u={command:e,args:t=t?t.slice(0):[],options:r=Object.assign({},r),file:void 0,original:{command:e,args:t}};return r.shell?u:function(e){let t;if(!s)return e;let r=(e.file=i(e),(t=e.file&&n(e.file))?(e.args.unshift(e.file),e.command=t,i(e)):e.file),u=!l.test(r);if(e.options.forceShell||u){let t=c.test(r);e.command=o.normalize(e.command),e.command=a.command(e.command),e.args=e.args.map(e=>a.argument(e,t));let i=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${i}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(u)}},2077(e){"use strict";let t=/([()\][%!^"`<>&|;, *?])/g;e.exports.command=function(e){return e.replace(t,"^$1")},e.exports.argument=function(e,r){return e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1"),e=(e=`"${e}"`).replace(t,"^$1"),r&&(e=e.replace(t,"^$1")),e}},1880(e,t,r){"use strict";let o=r(9896),i=r(600);e.exports=function(e){let t,r=Buffer.alloc(150);try{t=o.openSync(e,"r"),o.readSync(t,r,0,150,0),o.closeSync(t)}catch(e){}return i(r.toString())}},3803(e,t,r){"use strict";let o=r(6928),i=r(1905),a=r(9695);function n(e,t){let r,n=e.options.env||process.env,s=process.cwd(),l=null!=e.options.cwd,c=l&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}try{r=i.sync(e.command,{path:n[a({env:n})],pathExt:t?o.delimiter:void 0})}catch(e){}finally{c&&process.chdir(s)}return r&&(r=o.resolve(l?e.options.cwd:"",r)),r}e.exports=function(e){return n(e)||n(e,!0)}},9344(e,t,r){var o;function i(e,t,r){if("function"==typeof t&&(r=t,t={}),!r){if("function"!=typeof Promise)throw TypeError("callback not provided");return new Promise(function(r,o){i(e,t||{},function(e,t){e?o(e):r(t)})})}o(e,t||{},function(e,o){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,o=!1),r(e,o)})}r(9896),o="win32"===process.platform||global.TESTING_WINDOWS?r(8541):r(709),e.exports=i,i.sync=function(e,t){try{return o.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}},709(e,t,r){e.exports=i,i.sync=function(e,t){return a(o.statSync(e),t)};var o=r(9896);function i(e,t,r){o.stat(e,function(e,o){r(e,!e&&a(o,t))})}function a(e,t){var r,o,i,a,n,s,l,c,u;return e.isFile()&&(r=e,o=t,i=r.mode,a=r.uid,n=r.gid,s=void 0!==o.uid?o.uid:process.getuid&&process.getuid(),l=void 0!==o.gid?o.gid:process.getgid&&process.getgid(),c=parseInt("100",8),u=parseInt("010",8),i&parseInt("001",8)||i&u&&n===l||i&c&&a===s||i&(c|u)&&0===s)}},8541(e,t,r){e.exports=a,a.sync=function(e,t){return i(o.statSync(e),e,t)};var o=r(9896);function i(e,t,r){if(!e.isSymbolicLink()&&!e.isFile())return!1;var o=void 0!==r.pathExt?r.pathExt:process.env.PATHEXT;if(!o||-1!==(o=o.split(";")).indexOf(""))return!0;for(var i=0;i<o.length;i++){var a=o[i].toLowerCase();if(a&&t.substr(-a.length).toLowerCase()===a)return!0}return!1}function a(e,t,r){o.stat(e,function(o,a){r(o,!o&&i(a,e,t))})}},9695(e){"use strict";let t=(e={})=>{let t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};e.exports=t,e.exports.default=t},600(e,t,r){"use strict";let o=r(7257);e.exports=(e="")=>{let t=e.match(o);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,"").split(" "),a=r.split("/").pop();return"env"===a?i:i?`${a} ${i}`:a}},7257(e){"use strict";e.exports=/^#!(.*)/},1905(e,t,r){let o="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,i=r(6928),a=o?";":":",n=r(9344),s=e=>Object.assign(Error(`not found: ${e}`),{code:"ENOENT"}),l=(e,t)=>{let r=t.colon||a,i=e.match(/\//)||o&&e.match(/\\/)?[""]:[...o?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],n=o?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=o?n.split(r):[""];return o&&-1!==e.indexOf(".")&&""!==s[0]&&s.unshift(""),{pathEnv:i,pathExt:s,pathExtExe:n}},c=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});let{pathEnv:o,pathExt:a,pathExtExe:c}=l(e,t),u=[],d=r=>new Promise((a,n)=>{if(r===o.length)return t.all&&u.length?a(u):n(s(e));let l=o[r],c=/^".*"$/.test(l)?l.slice(1,-1):l,d=i.join(c,e);a(p(!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d,r,0))}),p=(e,r,o)=>new Promise((i,s)=>{if(o===a.length)return i(d(r+1));let l=a[o];n(e+l,{pathExt:c},(a,n)=>{if(!a&&n)if(!t.all)return i(e+l);else u.push(e+l);return i(p(e,r,o+1))})});return r?d(0).then(e=>r(null,e),r):d(0)};e.exports=c,c.sync=(e,t)=>{let{pathEnv:r,pathExt:o,pathExtExe:a}=l(e,t=t||{}),c=[];for(let s=0;s<r.length;s++){let l=r[s],u=/^".*"$/.test(l)?l.slice(1,-1):l,d=i.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<o.length;e++){let r=p+o[e];try{if(n.sync(r,{pathExt:a}))if(!t.all)return r;else c.push(r)}catch(e){}}}if(t.all&&c.length)return c;if(t.nothrow)return null;throw s(e)}},5317(e){"use strict";e.exports=require("child_process")},9896(e){"use strict";e.exports=require("fs")},7598(e){"use strict";e.exports=require("node:crypto")},6928(e){"use strict";e.exports=require("path")},8330(e){"use strict";e.exports=JSON.parse('{"name":"xmcp","version":"1.12.1"}')}},o={};function i(e){var t=o[e];if(void 0!==t)return t.exports;var a=o[e]={exports:{}};return r[e](a,a.exports,i),a.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,o){if(1&o&&(r=this(r)),8&o||"object"==typeof r&&r&&(4&o&&r.__esModule||16&o&&"function"==typeof r.then))return r;var a=Object.create(null);i.r(a);var n={};e=e||[null,t({}),t([]),t(t)];for(var s=2&o&&r;("object"==typeof s||"function"==typeof s)&&!~e.indexOf(s);s=t(s))Object.getOwnPropertyNames(s).forEach(e=>{n[e]=()=>r[e]});return n.default=()=>r,i.d(a,n),a},i.d=(e,t,r)=>{var o=(t,r)=>{for(var o in t)i.o(t,o)&&!i.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,[r]:t[o]})};o(t,"get"),o(r,"value")},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};for(var n in(()=>{"use strict";let e,t,r,o,n,s,l,c,u,d,p,h,f,m,y,g,v,_,b,S;i.r(a),i.d(a,{createClient:()=>he,withClient:()=>ht});var w,$,R,P,k,x,E,O,T=Object.create,C=Object.defineProperty,j=Object.getOwnPropertyDescriptor,I=Object.getOwnPropertyNames,N=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),A=(e,t,r)=>(r=null!=e?T(N(e)):{},((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var o,i=I(t),a=0,n=i.length;a<n;a++)o=i[a],z.call(e,o)||void 0===o||C(e,o,{get:(e=>t[e]).bind(null,o),enumerable:!(r=j(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?r:C(r,"default",{value:e,enumerable:!0}),e));let M=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),L=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),U=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),D=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function V(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function F(e,t="|"){return e.map(e=>ed(e)).join(t)}function H(e,t){return"bigint"==typeof t?t.toString():t}class Z{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function J(e){return new Z(e)}function B(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let K=Symbol("evaluating");function G(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function W(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function X(e){return W(e._zod.def)??e._zod.def.shape}function Y(e,t,r){Object.defineProperty(e,t,{get(){let e=r();return G(this,t,e),e},enumerable:!0,configurable:!0})}function Q(e,t,r){t in e?G(e,t,r):e[t]=r}function ee(e,t,r,o){let i=X(t);for(let a of r){let r=Object.getOwnPropertyDescriptor(i,a);r.enumerable&&(r.get?Y(e,a,()=>{let e=t._zod.def.shape[a];return o?o(e,a):e}):Q(e,a,o?o(r.value,a):r.value))}}function et(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let er="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function eo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let ei=J(()=>{if(eM.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ea(e){if(!1===eo(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==eo(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function en(e){return ea(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let es=new Set(["string","number","symbol"]);function el(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ec(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function eu(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function ed(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}let ep={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},eh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ef(e,t){let r=X(e),o=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&o.push(e)}return o}function em(e,t){let r={};ee(r,e,Reflect.ownKeys(X(e)));var o=r,i=t;for(let e of Reflect.ownKeys(i)){let t=Object.getOwnPropertyDescriptor(i,e);t.enumerable&&(t.get?Y(o,e,()=>i[e]):Q(o,e,t.value))}return r}function ey(e,t,r,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${o}() cannot be used on object schemas containing refinements`);let a=r?new Set(ef(t,r)):void 0,n={};return ee(n,t,Reflect.ownKeys(X(t)),e&&((t,r)=>a&&!a.has(r)?t:new e({type:"optional",innerType:t}))),ec(t,et(t._zod.def,{shape:n,checks:[]}))}function eg(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ev(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function e_(e){return"string"==typeof e?e:e?.message}function eb(e){let t=[];for(let r of e??[]){let e=r._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let o=e.maximum??e.length??e.size;o>=0&&t.push([o,r])}return t}function eS(e,t,r){var o;for(let i=t;i<e.length;i++)(o=e[i]).schema??(o.schema=r)}function ew(e,t,r){let o=e.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?e.schema??(e.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:e_(e.inst?._zod.def?.error?.(e))??e_(i?.(e))??e_(t?.error?.(e))??e_(r.customError?.(e))??e_(r.localeError?.(e))??"Invalid input",n={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(n[t]=e[t]);return n.path??(n.path=[]),n.message=a,t?.reportInput&&(n.input=e.input),n}let e$=/[\uD800-\uDBFF]/;function eR(e){let t=e.length;if(!e$.test(e))return t;let r=t;for(let o=0;o<t-1;o++)(64512&e.charCodeAt(o))==55296&&(64512&e.charCodeAt(o+1))==56320&&(r--,o++);return r}function eP(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ek(...e){let[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}function ex(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function eE(e,t){for(let r in e){let o=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return ex(this,r,o(this))},set(e){ex(this,r,e)}})}return t}let eO=!1,eT={configurable:!0,get(){eO=!0}};function eC(t,r,o){let i=Object.getPrototypeOf(t._zod);if(r in i&&e!==t._zod){e=void 0;return}e=t._zod,Object.defineProperty(i,r,{configurable:!0,get(){Object.defineProperty(this,r,eT);let e=eO;eO=!1;try{let t=o(this);return eO?delete this[r]:Object.defineProperty(this,r,{configurable:!0,writable:!0,value:t}),eO=eO||e,t}catch(t){throw delete this[r],eO=eO||e,t}},set(e){Object.defineProperty(this,r,{configurable:!0,writable:!0,value:e})}})}let ej=Object.freeze({status:"aborted"}),eI={value:void 0,enumerable:!1},eN="captureStackTrace"in Error?Error:null;function ez(e,t,r,o){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let a=r&&new WeakSet;function n(o,n){if(o._zod){if(o._zod.traits.has(e))return}else{eI.value=new i(n);try{Object.defineProperty(o,"_zod",eI)}finally{eI.value=void 0}}if(o._zod.traits.add(e),t(o,n),a){let e=Object.getPrototypeOf(o),t=o._zod.constr.prototype,i=e;for(;i&&i!==t;)i=Object.getPrototypeOf(i);let n=i??e;if(!a.has(n)){a.add(n);var s=n,l=r;for(let e in l){let t=Object.getOwnPropertyDescriptor(l,e);t.get?Object.defineProperty(s,e,{...t,enumerable:!1}):function(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:ex(this,t,r.bind(this))},set(e){ex(this,t,e)}})}(s,e,t.value)}}}let u=c.prototype;for(let e in u)Object.prototype.hasOwnProperty.call(u,e)&&(e in o||(o[e]=u[e].bind(o)))}let s=o?.Parent??Object;class l extends s{}function c(e){let t=o?.Parent?function(e){let t=eN;if(t){let r=t.stackTraceLimit;if("number"==typeof r){try{t.stackTraceLimit=0}catch{return eN=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}(l):this;n(t,e);let r=t._zod.deferred;if(r){for(let e of r)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(c,"init",{value:n}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!o?.Parent&&t instanceof o.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class eq extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eA extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(x=globalThis).__zod_globalConfig??(x.__zod_globalConfig={});let eM=globalThis.__zod_globalConfig;function eL(e){return e&&Object.assign(eM,e),eM}class eU extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eD="~memo",eV=[];function eF(e){return null!==e&&"object"==typeof e}function eH(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let eZ=new WeakMap,eJ=[],eB={alloc(e,r,o){let i=t;if(!i)return o;t=void 0;let a={value:o,issues:null};return i.set(r.value,a),eJ.push(a),o},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,r=(e,r)=>{var o,i;let a;if("backward"!==r.direction&&(o=r,i=e.value,void 0!==(a=o[eD]?.backEdges)&&eF(i)&&a.has(i)))throw new eU;return t(e,r)};e._zod.parse=r,e._zod.run===t&&(e._zod.run=r)})},attach(e){var r;let o,i,a,n=!1;(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,s=(l,c)=>{let u;if(void 0===o){let t=function e(t,r,o){var i,a;let n=eZ.get(t);if(void 0!==n)return 2*!!n;if(r.has(t))return 2;r.add(t);let s=0,l=t=>{if(2!==s&&t?._zod){let i=e(t,r,o);i>s&&(s=i)}},c=e=>{e>s&&(s=e)},u=t._zod.def;switch(u.type){case"object":{let t=W(u);c(t?((t,i)=>{let a=0;for(let n of Reflect.ownKeys(t)){let s=Object.getOwnPropertyDescriptor(t,n);if(i&&!s.enumerable)continue;let l=s.get?1:s.value?._zod?e(s.value,r,o):0;l>a&&(a=l)}return a})(t,!0):1),l(u.catchall);break}case"array":l(u.element);break;case"tuple":for(let e of u.items)l(e);l(u.rest);break;case"record":case"map":l(u.keyType),l(u.valueType);break;case"set":l(u.valueType);break;case"union":for(let e of u.options)l(e);break;case"intersection":l(u.left),l(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":l(u.innerType);break;case"pipe":l(u.in),l(u.out);break;case"function":l(u.input),l(u.output);break;case"lazy":{let i=u._cachedInner??(o?t._zod.innerType:void 0);c(i?e(i,r,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in u){let t=Object.getOwnPropertyDescriptor(u,e);if(!t||t.get)continue;let r=t.value;if(r&&"object"==typeof r){if(r._zod)l(r);else if(Array.isArray(r))for(let e of r)l(e)}}}return r.delete(t),i=t,1!==(a=s)&&eZ.set(i,2===a),a}(e,new Set,!1);if(0===t)return e._zod.parse=r,e._zod.run===s&&(e._zod.run=r),r(l,c);2===t||n?o=!0:n=!0}let d=l.value;if(!eF(d))return r(l,c);let p=c[eD];if(p||(p={buckets:new WeakMap,backEdges:void 0},c[eD]=p),i===c)u=a;else{var h,f;let t;h=p,f=e,(t=h.buckets.get(f))||(t=new WeakMap,h.buckets.set(f,t)),u=t,i=c,a=u}let m=u.get(d);if(m)return l.value=m.value,m.issues?m.issues.length&&l.issues.push(...eH(m.issues)):(l.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(m.value)),l;t=u;let y=eJ.length,g=r(l,c);t=void 0;let v=eJ.length>y?eJ.pop():void 0;return g instanceof Promise?g.then(e=>(v&&(v.issues=e.issues.length?eH(e.issues):eV),e)):(v&&(v.issues=g.issues.length?eH(g.issues):eV),g)};e._zod.parse=s,e._zod.run===r&&(e._zod.run=s)})}},eK=/^[cC][0-9a-z]{6,}$/,eG=/^[0-9a-z]+$/,eW=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,eX=/^[0-9a-vA-V]{20}$/,eY=/^[A-Za-z0-9]{27}$/,eQ=/^[a-zA-Z0-9_-]{21}$/,e0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,e1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,e2=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,e9=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,e4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,e3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,e5=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,e6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e8=/^https?$/,e7=/^\+[1-9]\d{6,14}$/,te="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",tt=(w=te,RegExp(`^${w}$`));function tr(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let to=/^[\s\S]{0,}$/,ti=/^-?\d+$/,ta=/^-?\d+(?:\.\d+)?$/,tn=/^(?:true|false)$/i,ts=/^null$/i,tl=/^[^A-Z]*$/,tc=/^[^a-z]*$/,tu=ez("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),td=e=>{let t=e.value;return null!=t&&void 0!==t.length},tp={number:"number",bigint:"bigint",object:"date"},th=ez("$ZodCheckLessThan",(e,t)=>{tu.init(e,t);let r=tp[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:tp[typeof o.value]??r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tf=ez("$ZodCheckGreaterThan",(e,t)=>{tu.init(e,t);let r=tp[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:tp[typeof o.value]??r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tm=ez("$ZodCheckMultipleOf",(e,t)=>{tu.init(e,t),e._zod.check=r=>{var o;let i,a,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):0==(a=Math.round(i=(o=r.value)/t.value),n=4*Number.EPSILON*Math.max(Math.abs(i),1),Math.abs(i-a)<n?0:i-a))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ty=ez("$ZodCheckNumberFormat",(e,t)=>{tu.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[i,a]=ep[t.format];e._zod.check=n=>{let s=n.value;if(r){if(!Number.isInteger(s))return void n.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?n.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):n.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}))}s<i&&n.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&n.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),tg=ez("$ZodCheckMaxLength",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length;if(("string"==typeof o&&i>t.maximum?eR(o):i)<=t.maximum)return;let a=eP(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tv=ez("$ZodCheckMinLength",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length;if(("string"==typeof o&&i>=t.minimum&&i<2*t.minimum?eR(o):i)>=t.minimum)return;let a=eP(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),t_=ez("$ZodCheckLengthEquals",(e,t)=>{var r;tu.init(e,t),(r=e._zod.def).when??(r.when=td),e._zod.check=r=>{let o=r.value,i=o.length,a="string"==typeof o&&i>=t.length&&i<=2*t.length?eR(o):i;if(a===t.length)return;let n=eP(o),s=a>t.length;r.issues.push({origin:n,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tb=ez("$ZodCheckStringFormat",(e,t)=>{var r,o;tu.init(e,t),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),tS=ez("$ZodCheckRegex",(e,t)=>{tb.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tw=ez("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tl),tb.init(e,t)}),t$=ez("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tc),tb.init(e,t)}),tR=ez("$ZodCheckIncludes",(e,t)=>{tu.init(e,t);let r=el(t.includes),o=new RegExp("number"==typeof t.position?`^.{${t.position},}${r}`:r);t.pattern=o,e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),tP=ez("$ZodCheckStartsWith",(e,t)=>{tu.init(e,t);let r=RegExp(`^${el(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),tk=ez("$ZodCheckEndsWith",(e,t)=>{tu.init(e,t);let r=RegExp(`.*${el(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),tx=ez("$ZodCheckOverwrite",(e,t)=>{tu.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class tE{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
2
2
|
${t.join("\n")}
|
|
3
3
|
};`)(...Object.values(this.closed))}}let tO={major:4,minor:6,patch:7},tT=ez("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tO;let o=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...o??[]]:o?.length?[...o]:[];for(let t of i)for(let r of t._zod.onattach)r(e);if(0===i.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,r,o)=>{let i;if(t.memo)return t;let a=eg(t);for(let n of r){if(n._zod.def.when){if(function(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}(t)||!n._zod.def.when(t))continue}else if(a)continue;let r=t.issues.length,s=n._zod.check(t);if(s instanceof Promise&&o?.async===!1)throw new eq;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,t.issues.length!==r&&(eS(t.issues,r,e),a||(a=eg(t,r)))});else{if(t.issues.length===r)continue;eS(t.issues,r,e),a||(a=eg(t,r))}}return i?i.then(()=>t):t},r=(r,o,a)=>{if(eg(r))return r.aborted=!0,r;let n=t(o,i,a);if(n instanceof Promise){if(!1===a.async)throw new eq;return n.then(t=>e._zod.parse(t,a))}return e._zod.parse(n,a)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if("backward"===a.direction){let t=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,o,a)):r(t,o,a)}let n=e._zod.parse(o,a);if(n instanceof Promise){if(!1===a.async)throw new eq;return n.then(e=>t(e,i,a))}return t(n,i,a)}}},{get"~standard"(){var e;return e=this,ex(e,"~standard",tj(this),!1)},set"~standard"(e){ex(this,"~standard",e)}}),tC=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ew(e,t,eL()))}:{value:e.value};function tj(e){return{validate:t=>{let r={async:!1};try{let o=e._zod.run({value:t,issues:[]},r);if(!(o instanceof Promise))return tC(o,r)}catch(e){}return async function(e,t){let r={async:!0};return tC(await e._zod.run({value:t,issues:[]},r),r)}(e,t)},vendor:"zod",version:1}}let tI=ez("$ZodString",(e,t)=>{tT.init(e,t),e._zod.pattern=t.pattern??to,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tN=ez("$ZodStringFormat",(e,t)=>{tb.init(e,t),tI.init(e,t)}),tz=ez("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=e1),tN.init(e,t)}),tq=ez("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=e2(e))}else t.pattern??(t.pattern=e2());tN.init(e,t)}),tA=ez("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=e9),tN.init(e,t)});function tM(e){try{if("u">typeof URL&&"function"==typeof URL.canParse)return URL.canParse(e);return new URL(e),!0}catch{return!1}}let tL=/[\t\n\r]/g;function tU(e){return e.replace(tL,"")}let tD=ez("$ZodURL",(e,t)=>{tN.init(e,t),e._zod.check=r=>{try{var o,i,a,n,s,l;let c=r.value.trim(),u=(o=c,i=t,"normalize"in i||"hostname"in i||"protocol"in i?function(e,t){if(!t.normalize&&t.protocol?.source===e8.source&&!/^https?:\/\//i.test(e))return 1;try{if("u">typeof URL){let t=URL;if("function"==typeof t.parse)return t.parse(e)??2}return new URL(e)}catch{return 2}}(o,i):tM(o)||2);if(1===u)return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});if(2===u)return void r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});if(!0===u){r.value=tU(c);return}t.hostname&&(a=u,(n=t.hostname).lastIndex=0,!n.test(a.hostname))&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort}),t.protocol&&(s=u,(l=t.protocol).lastIndex=0,!l.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol))&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort}),r.value=t.normalize?u.href:tU(c);return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),tV=ez("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),tN.init(e,t)}),tF=ez("$ZodNanoID",(e,t)=>{var r;if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=void 0===t.length?eQ:(r=t.length,RegExp(`^[a-zA-Z0-9_-]{${r}}$`))),tN.init(e,t)}),tH=ez("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=eK),tN.init(e,t)}),tZ=ez("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=eG),tN.init(e,t)}),tJ=ez("$ZodULID",(e,t)=>{t.pattern??(t.pattern=eW),tN.init(e,t)}),tB=ez("$ZodXID",(e,t)=>{t.pattern??(t.pattern=eX),tN.init(e,t)}),tK=ez("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=eY),tN.init(e,t)}),tG=ez("$ZodISODateTime",(e,t)=>{var r;let o,i,a;t.pattern??(o=["Z"],(r=t).offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),i=`${tr({precision:r.precision,seconds:!0})}(?:${o.join("|")})`,a=r.local?`${i}|${tr({precision:r.precision})}`:i,t.pattern=RegExp(`^${te}T(?:${a})$`)),tN.init(e,t)}),tW=ez("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=tt),tN.init(e,t)}),tX=ez("$ZodISOTime",(e,t)=>{var r;t.pattern??(r=t,t.pattern=RegExp(`^${tr(r)}$`)),tN.init(e,t)}),tY=ez("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=e0),tN.init(e,t)}),tQ=ez("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=e4),tN.init(e,t)}),t0=/^[0-9a-fA-F:.]+$/;function t1(e){return!!t0.test(e)&&tM(`http://[${e}]`)}let t2=ez("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=e3),tN.init(e,t),e._zod.check=r=>{t1(r.value)||r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}),t9=ez("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=e5),tN.init(e,t)}),t4=ez("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=e6),tN.init(e,t),e._zod.check=r=>{!function(e){let t=e.split("/");if(2!==t.length)return!1;let[r,o]=t;if(!o)return!1;let i=Number(o);return`${i}`===o&&!(i<0)&&!(i>128)&&t1(r)}(r.value)&&r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function t3(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let t5=/^[0-9a-zA-Z+/]*={0,2}$/,t6=ez("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=t5),tN.init(e,t),e._zod.check=r=>{t3(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),t8=/^[A-Za-z0-9_-]*$/,t7=ez("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=t8),tN.init(e,t),e._zod.check=r=>{!function(e){if(!t8.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return t3(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),re=ez("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e7),tN.init(e,t)}),rt=ez("$ZodJWT",(e,t)=>{tN.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[o]=r;if(!o)return!1;let i=JSON.parse(atob(o));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),rr=ez("$ZodNumber",(e,t)=>{tT.init(e,t),e._zod.pattern=ta,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let a="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),r}}),ro=ez("$ZodNumberFormat",(e,t)=>{ty.init(e,t),rr.init(e,t)}),ri=ez("$ZodBoolean",(e,t)=>{tT.init(e,t),e._zod.pattern=tn,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),ra=ez("$ZodNull",(e,t)=>{tT.init(e,t),e._zod.pattern=ts,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let o=t.value;return null===o||t.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),t}}),rn=ez("$ZodAny",(e,t)=>{tT.init(e,t),e._zod.parse=e=>e}),rs=ez("$ZodUnknown",(e,t)=>{tT.init(e,t),e._zod.parse=e=>e}),rl=ez("$ZodNever",(e,t)=>{tT.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),rc=e=>Array.isArray(e)?e.length:-1;function ru(e,t,r){e.issues.length&&t.issues.push(...ev(r,e.issues)),t.value[r]=e.value}let rd=ez("$ZodArray",(e,t)=>{tT.init(e,t);let r=eM.memoizer;r?.attach(e),e._zod.parse=(o,i)=>{let a=o.value;if(!Array.isArray(a))return o.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),o;o.value=r?r.alloc(e,o,Array(a.length),i):Array(a.length);let n=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let r=a[e],l=t.element._zod.run({value:r,issues:[]},i);if(l instanceof Promise)n.push(l.then(t=>ru(t,o,e)));else if(ru(l,o,e),s&&0!==l.issues.length&&eg(l))break}return n.length?Promise.all(n).then(()=>o):o},function(e,t){let r=eb(e._zod.def.checks);if(!r.length)return;let o=Math.min(...r.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(r,a)=>{let n=t(r.value);if(n>o&&!a?.skipChecks&&a?.direction!=="backward"){for(let[t,o]of eb(e._zod.def.checks))if(n>t&&o._zod.def.when(r)){let t=r.issues.length;return o._zod.check(r),r.issues[t].continue=!1,eS(r.issues,t,e),r}}return i(r,a)}}(e,rc)});function rp(e,t,r,o,i,a){let n=r in o,s="optional"===a;if(n||!s||"optional"!==i){if(e.issues.length){if(void 0!==i&&s&&!n)return;t.issues.push(...ev(r,e.issues))}if(!n&&void 0===i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?(n||"defaulted"===i&&!s)&&(t.value[r]=void 0):t.value[r]=e.value}}let rh=[];function rf(e){var t;let r=Object.keys(e.shape),o=Object.getOwnPropertySymbols(e.shape),i=o.length?o:rh,a=i.length?[...r,...i]:r;for(let t of a)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let n=Object.keys(t=e.shape).filter(e=>void 0!==t[e]._zod.optin&&"optional"===t[e]._zod.optout);return{...e,allKeys:a,symbolKeys:i,keySet:new Set(r),numKeys:r.length,optionalKeys:new Set(n)}}function rm(e,t,r,o,i,a,n){let s=[],l=i.keySet,c=i.catchall._zod,u=c.def.type,d=c.optin,p=c.optout,h=0;for(let i in t){if(n&&r.issues.length!==h){if(eg(r,h))break;h=r.issues.length}if(l.has(i))continue;if("__proto__"===i){"never"===u&&s.push(i);continue}if("never"===u){s.push(i);continue}let a=c.run({value:t[i],issues:[]},o);a instanceof Promise?e.push(a.then(e=>rp(e,r,i,t,d,p))):rp(a,r,i,t,d,p)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:a,continue:!0}),e.length)?Promise.all(e).then(()=>r):r}let ry=ez("$ZodObject",(e,t)=>{let r;tT.init(e,t);let o=Object.getOwnPropertyDescriptor(t,"shape"),i=o?.get?o.get.raw:t.shape??{};if(i){let e=()=>{let r={...i};return Object.defineProperty(t,"shape",{value:r}),e.raw=r,r};e.raw=i,Object.defineProperty(t,"shape",{get:e})}let a=J(()=>rf(t));eC(e,"propValues",e=>{let t=e.def.shape,r={};for(let e in t){let o=t[e]._zod;if(o.values){for(let t of(Object.prototype.hasOwnProperty.call(r,e)||G(r,e,new Set),o.values))r[e].add(t);void 0!==o.optin&&r[e].add(void 0)}}return r});let n=t.catchall,s=eM.memoizer;s?.attach(e),e._zod.parse=(t,o)=>{r??(r=a.value);let i=t.value;if(!eo(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value=s?s.alloc(e,t,{},o):{};let l=[],c=r.shape,u=o?.abortEarly,d=t.issues.length;for(let e of r.allKeys){if(u&&t.issues.length!==d){if(eg(t,d))break;d=t.issues.length}if("__proto__"===e)continue;let r=c[e],a=r._zod.optin,n=r._zod.optout,s=r._zod.run({value:i[e],issues:[]},o);s instanceof Promise?l.push(s.then(r=>rp(r,t,e,i,a,n))):rp(s,t,e,i,a,n)}return n?rm(l,i,t,o,a.value,e,!0===u):l.length?Promise.all(l).then(()=>t):t}}),rg=ez("$ZodObjectJIT",(e,t)=>{let r,o;ry.init(e,t);let i=e._zod.parse,a=J(()=>rf(t)),n=eM.memoizer,s=!eM.jitless,l=s&&ei.value,c=t.catchall;e._zod.parse=(u,d)=>{o??(o=a.value);let p=u.value;return eo(p)?s&&l&&d?.async===!1&&!0!==d.jitless?(r||(r=(t=>{let r=a.value,o=r.symbolKeys,i=new tE(["payload","ctx"],{shape:t,inst:e,memo:n,syms:o}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,l=(e,t)=>`
|
|
4
4
|
let ${e}_ab = false;
|
|
@@ -67,4 +67,4 @@ ${a}`,d++}else pX(e,r,i)?p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,o)||void 0:y(e
|
|
|
67
67
|
`,r),i=-1;if(-1!==t&&-1!==o?i=t<o?t:o:-1!==t?i=t===e.length-1?-1:t:-1!==o&&(i=o),-1===i)break;y(e,r,i),r=i+1,13===e.charCodeAt(r-1)&&10===e.charCodeAt(r)&&r++}return e.slice(r)}function y(e,r,o){if(r===o)return void(d>0&&t({id:c,event:p,data:u}),c=void 0,u="",d=0,p=void 0);let a=e.charCodeAt(r);if(pW(e,r,a)){let t=32===e.charCodeAt(r+5)?r+6:r+5,i=e.slice(t,o);u=0===d?i:`${u}
|
|
68
68
|
${i}`,d++;return}if(pX(e,r,a)){p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,o)||void 0;return}if(105===a&&100===e.charCodeAt(r+1)&&58===e.charCodeAt(r+2)){let t=e.slice(32===e.charCodeAt(r+3)?r+4:r+3,o);t.includes("\0")||(c=t);return}if(58===a){i&&i(e.slice(r,o).slice(32===e.charCodeAt(r+1)?2:1));return}let n=e.slice(r,o),s=n.indexOf(":");if(-1===s)return void g(n,"",n);let l=n.slice(0,s),h=32===n.charCodeAt(s+1)?2:1;g(l,n.slice(s+h),n)}function g(e,t,i){switch(e){case"event":p=t||void 0;break;case"data":u=0===d?t:`${u}
|
|
69
69
|
${t}`,d++;break;case"id":t.includes("\0")||(c=t);break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new pK(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:r(new pK(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}return{feed:function(e){if(h)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===n.length){let t=m(e);""!==t&&(n.push(t),s=t.length),f();return}if(-1===e.indexOf(`
|
|
70
|
-
`)&&-1===e.indexOf("\r")){n.push(e),s+=e.length,f();return}n.push(e);let t=n.join("");n.length=0,s=0;let r=m(t);""!==r&&(n.push(r),s=r.length),f()},reset:function(e={}){if(e.consume&&n.length>0){let e=n.join("");y(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,n.length=0,s=0,h=!1}}}({onEvent:e=>{a.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&a.error(t)},onRetry:t,onComment:r,maxBufferSize:o})},transform(e){i.feed(e)}})}}(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return lN(this,e)}static isInstance(e){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lN(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,lI(this,new.target)}});let pQ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},p0=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function p1(e,t){if("function"==typeof AbortSignal.any)return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",i),t.removeEventListener("abort",a)};function i(){o(),r.abort(e.reason)}function a(){o(),r.abort(t.reason)}return e.addEventListener("abort",i,{once:!0}),t.addEventListener("abort",a,{once:!0}),r.signal}var p2=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){var r,o,i,a,n;let s;if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,null==(r=t?.authProvider)?1:"function"!=typeof r.tokens||"function"!=typeof r.clientInformation)this._authProvider=t?.authProvider;else{let e,r;this._oauthProvider=t.authProvider,this._authProvider=(o=t.authProvider,i={skipIssuerMetadataValidation:t.skipIssuerMetadataValidation},{token:async()=>(await o.tokens())?.access_token,onUnauthorized:async e=>(async function(e,t,r){let{resourceMetadataUrl:o,scope:i}=pg(t.response);if(await pf(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:i,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new pa})(o,e,i)}),t.authProvider.dpop&&(this._fetch=(a=t.authProvider,e=async()=>{try{return await a.dpop?.()}catch(e){throw pj(e)}},r=async()=>{let e;try{e=await a.tokens()}catch(e){throw pj(e)}return e?.token_type?.toLowerCase()==="dpop"?e.access_token:void 0},t=>{let o="function"==typeof e?e:()=>e;return async(e,i)=>{let a=(i?.method??"GET").toUpperCase(),n=new URL(e.toString()),s=await o();if(!s)return t(e,i);let l=async()=>{let o=await r();if(!o)return t(e,i);let l=new Headers(i?.headers),c=await s.buildProof({htm:a,htu:n,accessToken:o});return l.set("Authorization",`DPoP ${o}`),l.set("DPoP",c),t(e,{...i,headers:l})},c=await l();return function(e){var t;if(401!==e.status)return!1;let r=e.headers.get("www-authenticate")??"";return t=r,/(?:^|,)\s*dpop(?:\s|$|,)/i.test(t)&&/use_dpop_nonce/i.test(r)}(c)&&c.headers.has("dpop-nonce")&&(s.observeNonce(c,n),await c.text?.().catch(()=>{}),c=await l()),s.observeNonce(c,n),c}})(t.fetch??fetch))}this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...uu(t.headers),...uu(o.headers)}:t.headers}):e}(t?.fetch,t?.requestInit),"follow"===this._redirectPolicy&&(this._fetchWithInit=(n=this._fetchWithInit,s=(e,t)=>n(e,t),uh.add(s),s)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??pQ,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??1)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(e){throw pj(e)}}async _stepUpAuthorizeInner(e,t){if("throw"===this._onInsufficientScope||!this._oauthProvider)throw new pr({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new lL(lA.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),o=pl(this._scope,r?.scope,e.scope);this._scope=o;let i=function(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!r.has(t))return!0;return!1}(o,r?.scope);return pf(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return"follow"===this._redirectPolicy?e:uf(e)}_unfollowedRedirect(e,t){let r="follow"===this._redirectPolicy?void 0:function(e,t){if("opaqueredirect"===t.type)return"Redirect not followed: this runtime does not expose where it points";let r=up(t.url||e,t);if(r)return(r.username=r.password=r.search=r.hash="","http:"===r.protocol&&"https:"===new URL(t.url||e).protocol)?(r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`):`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e,t=new Headers(this._requestInit?.headers||void 0);try{e=await this._authProvider?.token()}catch(e){throw pj(e)}return e&&t.set("Authorization",`Bearer ${e}`),this._sessionId&&t.set("mcp-session-id",this._sessionId),this._protocolVersion&&t.set("mcp-protocol-version",this._protocolVersion),t}_applyBodyDerivedHeaders(e,t){let r;if(Array.isArray(t)||(r=t,!a3.safeParse(r).success))return;let o=t.params?._meta?.[aA];if("string"!=typeof o)return;e.set("mcp-protocol-version",o),e.set("mcp-method",t.method);let i=function(e,t){var r;let o=Object.hasOwn(cZ,e)?cZ[e]:void 0;if(void 0===o)return;let i=null===(r=t)||"object"!=typeof r||Array.isArray(r)?void 0:t[o];return{field:o,value:"string"==typeof i?i:void 0}}(t.method,t.params);i?.value!==void 0&&e.set("mcp-name",cH(i.value))}_isModernEnvelopedRequest(e){let t;if(Array.isArray(e)||(t=e,!a3.safeParse(t).success))return!1;let r=e.params?._meta?.[aA];return"string"==typeof r&&r>=lD}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),n=[...a.get("accept")?.split(",").map(e=>e.trim().toLowerCase())??[],"text/event-stream"];a.set("accept",[...new Set(n)].join(", ")),o&&a.set("last-event-id",o);let s=this._abortController?.signal,l=void 0!==i&&void 0!==s?p1(s,i):i??s,c=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:a,signal:l});if(!c.ok){if(401===c.status&&this._authProvider){if(c.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=pg(c);this._resourceMetadataUrl=e,this._scope=pl(this._scope,t)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:c,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw pj(e)}return await c.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await c.text?.().catch(()=>{}),t)throw pj(new lL(lA.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:c.statusText}));throw pj(new pa)}if(403===c.status){let{resourceMetadataUrl:o,scope:i,error:a,errorDescription:n}=pg(c);if("insufficient_scope"===a){let a=await c.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:o,errorDescription:n,statusText:c.statusText,text:a},r)!=="AUTHORIZED")throw pj(new pa);return this._startOrAuthSse(e,t,r+1)}}if(await c.text?.().catch(()=>{}),405===c.status)return void e.onRequestStreamEnd?.();let o=this._unfollowedRedirect(this._url,c)??c.statusText;throw new lL(lA.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${o}`,{status:c.status,statusText:c.statusText})}this._handleSseStream(c.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor;return Math.min(t*Math.pow(r,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted||this._startOrAuthSse(e).catch(r=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,o,t);this._cancelReconnection="function"==typeof e?e:void 0}else{let e=setTimeout(i,o);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,r){let o;if(!e)return void t.onRequestStreamEnd?.();let{onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s}=t,l=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0,c=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new pY({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(o=e.id,c=!0,i?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=a7.parse(JSON.parse(e.data));(cI(t)||cN(t))&&(u=!0,void 0!==a&&(t.id=a)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||c)&&!u&&this._abortController&&!l()?this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s},0):l()||s?.()}catch(e){if(l())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||c)&&!u&&this._abortController&&!l())try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new pa("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await async function(e,t,r,o,i){if("string"==typeof e)return{authorizationCode:e,iss:t};let a=e.get("iss")??void 0,n=e.get("code");if(n)return{authorizationCode:n,iss:a};let s=(await r.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await p$(o,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new pa("Authorization callback failed and the issuer could not be verified");ps({iss:a,expectedIssuer:s.issuer,issParameterSupported:pn(s)});let l=e.get("error");if(l)throw new lq(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new pa("Authorization callback contained neither `code` nor `error`")}(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await pf(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new pa("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let i,{resumptionToken:a,onresumptiontoken:n}=t||{};if(a){let r;return void this._startOrAuthSse({resumptionToken:a,replayMessageId:(r=e,a3.safeParse(r).success)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e))}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let l=Array.isArray(e)?e.some(e=>{let t;return t=e,nf.safeParse(t).success}):(i=e,nf.safeParse(i).success);if(l&&s.delete("mcp-session-id"),t?.headers!==void 0)for(let[e,r]of Object.entries(t.headers))p0.has(e.toLowerCase())||s.set(e,r);s.set("content-type","application/json");let c=[...s.get("accept")?.split(",").map(e=>e.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&void 0!==u?p1(u,t.requestSignal):t?.requestSignal??u,p={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},h=await this._redirects(this._fetch??fetch)(this._url,p);if(l&&h.ok&&(this._sessionId=h.headers.get("mcp-session-id")||void 0),!h.ok){if(401===h.status&&this._authProvider){if(h.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=pg(h);this._resourceMetadataUrl=e,this._scope=pl(this._scope,t)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:h,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw pj(e)}return await h.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await h.text?.().catch(()=>{}),r)throw pj(new lL(lA.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:h.statusText}));throw pj(new pa)}let i=await h.text?.().catch(()=>null);if(403===h.status){let{resourceMetadataUrl:a,scope:n,error:s,errorDescription:l}=pg(h);if("insufficient_scope"===s){if(await this._stepUpAuthorize({scope:n,resourceMetadataUrl:a,errorDescription:l,statusText:h.statusText,text:i},o)!=="AUTHORIZED")throw pj(new pa);return this._send(e,t,r,o+1)}}if(400===h.status&&"string"==typeof i&&this._isModernEnvelopedRequest(e))try{let t=a7.parse(JSON.parse(i)),r=(Array.isArray(e)?e:[e]).filter(e=>{let t;return t=e,a3.safeParse(t).success});if(cN(t)&&r.some(e=>e.id===t.id))return void this.onmessage?.(t)}catch{}let a=this._unfollowedRedirect(this._url,h)??i;throw new lL(lA.ClientHttpNotImplemented,`Error POSTing to endpoint: ${a}`,{status:h.status,statusText:h.statusText,text:i})}if(202===h.status){let t;await h.text?.().catch(()=>{}),t=e,ng.safeParse(t).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let f=(Array.isArray(e)?e:[e]).some(e=>"method"in e&&"id"in e&&void 0!==e.id),m=h.headers.get("content-type"),y=function(e){if(e)try{return ul.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(""===t||e.slice(t.length).includes(","))return;return t}}(m);if(f)if("text/event-stream"===y)this._handleSseStream(h.body,{onresumptiontoken:n,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if("application/json"===y){let e=await h.json();for(let t of Array.isArray(e)?e.map(e=>a7.parse(e)):[a7.parse(e)])this.onmessage?.(t)}else throw await h.text?.().catch(()=>{}),new lM(lA.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await h.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&405!==r.status)throw new lL(lA.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};let p9=require("node:process"),p4=require("node:stream");var p3=i(6507);let p5="win32"===p9.platform?["APPDATA","COMSPEC","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PATHEXT","PROCESSOR_ARCHITECTURE","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","WINDIR"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];var p6=class{_process;_readBuffer;_serverParams;_stderrStream=null;onclose;onerror;onmessage;constructor(e){this._serverParams=e,this._readBuffer=new uc({maxBufferSize:e.maxBufferSize}),("pipe"===e.stderr||"overlapped"===e.stderr)&&(this._stderrStream=new p4.PassThrough)}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=p3(this._serverParams.command,this._serverParams.args??[],{env:{...function(){let e={};for(let t of p5){let r=p9.env[t];void 0!==r&&(r.startsWith("()")||(e[t]=r))}return e}(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:"win32"===p9.platform,cwd:this._serverParams.cwd}),this._process.on("error",e=>{t(e),this.onerror?.(e)}),this._process.on("spawn",()=>{e()}),this._process.on("close",e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",e=>{this.onerror?.(e)}),this._process.stdout?.on("data",e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on("error",e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async _dispose(){let e=this._process;if(this._process=void 0,e&&null===e.exitCode&&null===e.signalCode){let t=new Promise(t=>e.once("exit",()=>t()));try{e.stdin?.end()}catch{}try{e.kill("SIGTERM")}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,1e3).unref())]),null===e.exitCode&&null===e.signalCode)try{e.kill("SIGKILL")}catch{}await t}try{e?.stdout?.destroy()}catch{}try{e?.stdin?.destroy()}catch{}try{e?.stderr?.destroy()}catch{}this._readBuffer.clear()}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once("close",()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),null===e.exitCode){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(null===e.exitCode)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new lM(lA.NotConnected,"Not connected");let r=JSON.stringify(e)+"\n";this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}};let p8=i(8330),p7={name:p8.name,version:p8.version};async function he(e,t={}){var r;let o,i,{handlers:a={}}=t,n={};a.sampling&&(n.sampling={}),a.elicitation&&(n.elicitation={form:{},url:{}}),a.roots&&(n.roots={});let s=new pB(p7,{capabilities:n,versionNegotiation:t.versionNegotiation??{mode:"auto"}});a.sampling&&s.setRequestHandler("sampling/createMessage",a.sampling),a.elicitation&&s.setRequestHandler("elicitation/create",a.elicitation),a.roots&&s.setRequestHandler("roots/list",a.roots);let l="http"===e.type?new p2(new URL(e.url),{requestInit:{headers:(r=e.headers??[],i={},r.forEach(e=>{let t,r=e.name.trim();if("env"in(t=e)&&"string"==typeof t.env){let t=process.env[e.env];if(void 0===t)throw Error(`Environment variable "${e.env}" is not set (required for header "${r}")`);i[r]=t}else i[r]=e.value.trim()}),i)}}):new p6({command:e.command,args:e.args,env:e.env,cwd:e.cwd,stderr:e.stderr??(t.onStderrData?"pipe":"inherit")});l instanceof p6&&l.stderr?.on("data",t.onStderrData??(e=>{process.stderr.write(e)}));let c=l.close.bind(l);l.close=()=>o??(o=c());let u=s.close.bind(s);s.close=async()=>{try{await u()}finally{await l.close()}};let d=t.connect?.signal,p=()=>{l.close().catch(()=>{})};try{return d?.throwIfAborted(),d?.addEventListener("abort",p,{once:!0}),await s.connect(l,t.connect),d?.throwIfAborted(),s}catch(e){try{await s.close()}catch(t){throw AggregateError([e,t],"Client connection and cleanup failed",{cause:e})}throw d?.throwIfAborted(),e}finally{d?.removeEventListener("abort",p)}}async function ht(e,t,r){let o=await he(e,r);try{return await t(o)}finally{await o.close()}}})(),exports.createClient=a.createClient,exports.withClient=a.withClient,a)-1===["createClient","withClient"].indexOf(n)&&(exports[n]=a[n]);Object.defineProperty(exports,"__esModule",{value:!0})})();
|
|
70
|
+
`)&&-1===e.indexOf("\r")){n.push(e),s+=e.length,f();return}n.push(e);let t=n.join("");n.length=0,s=0;let r=m(t);""!==r&&(n.push(r),s=r.length),f()},reset:function(e={}){if(e.consume&&n.length>0){let e=n.join("");y(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,n.length=0,s=0,h=!1}}}({onEvent:e=>{a.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&a.error(t)},onRetry:t,onComment:r,maxBufferSize:o})},transform(e){i.feed(e)}})}}(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return lN(this,e)}static isInstance(e){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lN(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,lI(this,new.target)}});let pQ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},p0=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function p1(e,t){if("function"==typeof AbortSignal.any)return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",i),t.removeEventListener("abort",a)};function i(){o(),r.abort(e.reason)}function a(){o(),r.abort(t.reason)}return e.addEventListener("abort",i,{once:!0}),t.addEventListener("abort",a,{once:!0}),r.signal}var p2=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){var r,o,i,a,n;let s;if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,null==(r=t?.authProvider)?1:"function"!=typeof r.tokens||"function"!=typeof r.clientInformation)this._authProvider=t?.authProvider;else{let e,r;this._oauthProvider=t.authProvider,this._authProvider=(o=t.authProvider,i={skipIssuerMetadataValidation:t.skipIssuerMetadataValidation},{token:async()=>(await o.tokens())?.access_token,onUnauthorized:async e=>(async function(e,t,r){let{resourceMetadataUrl:o,scope:i}=pg(t.response);if(await pf(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:i,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new pa})(o,e,i)}),t.authProvider.dpop&&(this._fetch=(a=t.authProvider,e=async()=>{try{return await a.dpop?.()}catch(e){throw pj(e)}},r=async()=>{let e;try{e=await a.tokens()}catch(e){throw pj(e)}return e?.token_type?.toLowerCase()==="dpop"?e.access_token:void 0},t=>{let o="function"==typeof e?e:()=>e;return async(e,i)=>{let a=(i?.method??"GET").toUpperCase(),n=new URL(e.toString()),s=await o();if(!s)return t(e,i);let l=async()=>{let o=await r();if(!o)return t(e,i);let l=new Headers(i?.headers),c=await s.buildProof({htm:a,htu:n,accessToken:o});return l.set("Authorization",`DPoP ${o}`),l.set("DPoP",c),t(e,{...i,headers:l})},c=await l();return function(e){var t;if(401!==e.status)return!1;let r=e.headers.get("www-authenticate")??"";return t=r,/(?:^|,)\s*dpop(?:\s|$|,)/i.test(t)&&/use_dpop_nonce/i.test(r)}(c)&&c.headers.has("dpop-nonce")&&(s.observeNonce(c,n),await c.text?.().catch(()=>{}),c=await l()),s.observeNonce(c,n),c}})(t.fetch??fetch))}this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...uu(t.headers),...uu(o.headers)}:t.headers}):e}(t?.fetch,t?.requestInit),"follow"===this._redirectPolicy&&(this._fetchWithInit=(n=this._fetchWithInit,s=(e,t)=>n(e,t),uh.add(s),s)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??pQ,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??1)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(e){throw pj(e)}}async _stepUpAuthorizeInner(e,t){if("throw"===this._onInsufficientScope||!this._oauthProvider)throw new pr({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new lL(lA.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),o=pl(this._scope,r?.scope,e.scope);this._scope=o;let i=function(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!r.has(t))return!0;return!1}(o,r?.scope);return pf(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return"follow"===this._redirectPolicy?e:uf(e)}_unfollowedRedirect(e,t){let r="follow"===this._redirectPolicy?void 0:function(e,t){if("opaqueredirect"===t.type)return"Redirect not followed: this runtime does not expose where it points";let r=up(t.url||e,t);if(r)return(r.username=r.password=r.search=r.hash="","http:"===r.protocol&&"https:"===new URL(t.url||e).protocol)?(r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`):`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e,t=new Headers(this._requestInit?.headers||void 0);try{e=await this._authProvider?.token()}catch(e){throw pj(e)}return e&&t.set("Authorization",`Bearer ${e}`),this._sessionId&&t.set("mcp-session-id",this._sessionId),this._protocolVersion&&t.set("mcp-protocol-version",this._protocolVersion),t}_applyBodyDerivedHeaders(e,t){let r;if(Array.isArray(t)||(r=t,!a3.safeParse(r).success))return;let o=t.params?._meta?.[aA];if("string"!=typeof o)return;e.set("mcp-protocol-version",o),e.set("mcp-method",t.method);let i=function(e,t){var r;let o=Object.hasOwn(cZ,e)?cZ[e]:void 0;if(void 0===o)return;let i=null===(r=t)||"object"!=typeof r||Array.isArray(r)?void 0:t[o];return{field:o,value:"string"==typeof i?i:void 0}}(t.method,t.params);i?.value!==void 0&&e.set("mcp-name",cH(i.value))}_isModernEnvelopedRequest(e){let t;if(Array.isArray(e)||(t=e,!a3.safeParse(t).success))return!1;let r=e.params?._meta?.[aA];return"string"==typeof r&&r>=lD}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),n=[...a.get("accept")?.split(",").map(e=>e.trim().toLowerCase())??[],"text/event-stream"];a.set("accept",[...new Set(n)].join(", ")),o&&a.set("last-event-id",o);let s=this._abortController?.signal,l=void 0!==i&&void 0!==s?p1(s,i):i??s,c=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:a,signal:l});if(!c.ok){if(401===c.status&&this._authProvider){if(c.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=pg(c);this._resourceMetadataUrl=e,this._scope=pl(this._scope,t)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:c,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw pj(e)}return await c.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await c.text?.().catch(()=>{}),t)throw pj(new lL(lA.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:c.statusText}));throw pj(new pa)}if(403===c.status){let{resourceMetadataUrl:o,scope:i,error:a,errorDescription:n}=pg(c);if("insufficient_scope"===a){let a=await c.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:o,errorDescription:n,statusText:c.statusText,text:a},r)!=="AUTHORIZED")throw pj(new pa);return this._startOrAuthSse(e,t,r+1)}}if(await c.text?.().catch(()=>{}),405===c.status)return void e.onRequestStreamEnd?.();let o=this._unfollowedRedirect(this._url,c)??c.statusText;throw new lL(lA.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${o}`,{status:c.status,statusText:c.statusText})}this._handleSseStream(c.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor;return Math.min(t*Math.pow(r,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted||this._startOrAuthSse(e).catch(r=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,o,t);this._cancelReconnection="function"==typeof e?e:void 0}else{let e=setTimeout(i,o);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,r){let o;if(!e)return void t.onRequestStreamEnd?.();let{onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s}=t,l=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0,c=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new pY({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(o=e.id,c=!0,i?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=a7.parse(JSON.parse(e.data));(cI(t)||cN(t))&&(u=!0,void 0!==a&&(t.id=a)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||c)&&!u&&this._abortController&&!l()?this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s},0):l()||s?.()}catch(e){if(l())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||c)&&!u&&this._abortController&&!l())try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a,requestSignal:n,onRequestStreamEnd:s},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new pa("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await async function(e,t,r,o,i){if("string"==typeof e)return{authorizationCode:e,iss:t};let a=e.get("iss")??void 0,n=e.get("code");if(n)return{authorizationCode:n,iss:a};let s=(await r.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await p$(o,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new pa("Authorization callback failed and the issuer could not be verified");ps({iss:a,expectedIssuer:s.issuer,issParameterSupported:pn(s)});let l=e.get("error");if(l)throw new lq(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new pa("Authorization callback contained neither `code` nor `error`")}(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await pf(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new pa("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let i,{resumptionToken:a,onresumptiontoken:n}=t||{};if(a){let r;return void this._startOrAuthSse({resumptionToken:a,replayMessageId:(r=e,a3.safeParse(r).success)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e))}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let l=Array.isArray(e)?e.some(e=>{let t;return t=e,nf.safeParse(t).success}):(i=e,nf.safeParse(i).success);if(l&&s.delete("mcp-session-id"),t?.headers!==void 0)for(let[e,r]of Object.entries(t.headers))p0.has(e.toLowerCase())||s.set(e,r);s.set("content-type","application/json");let c=[...s.get("accept")?.split(",").map(e=>e.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&void 0!==u?p1(u,t.requestSignal):t?.requestSignal??u,p={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},h=await this._redirects(this._fetch??fetch)(this._url,p);if(l&&h.ok&&(this._sessionId=h.headers.get("mcp-session-id")||void 0),!h.ok){if(401===h.status&&this._authProvider){if(h.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=pg(h);this._resourceMetadataUrl=e,this._scope=pl(this._scope,t)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:h,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw pj(e)}return await h.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await h.text?.().catch(()=>{}),r)throw pj(new lL(lA.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:h.statusText}));throw pj(new pa)}let i=await h.text?.().catch(()=>null);if(403===h.status){let{resourceMetadataUrl:a,scope:n,error:s,errorDescription:l}=pg(h);if("insufficient_scope"===s){if(await this._stepUpAuthorize({scope:n,resourceMetadataUrl:a,errorDescription:l,statusText:h.statusText,text:i},o)!=="AUTHORIZED")throw pj(new pa);return this._send(e,t,r,o+1)}}if(400===h.status&&"string"==typeof i&&this._isModernEnvelopedRequest(e))try{let t=a7.parse(JSON.parse(i)),r=(Array.isArray(e)?e:[e]).filter(e=>{let t;return t=e,a3.safeParse(t).success});if(cN(t)&&r.some(e=>e.id===t.id))return void this.onmessage?.(t)}catch{}let a=this._unfollowedRedirect(this._url,h)??i;throw new lL(lA.ClientHttpNotImplemented,`Error POSTing to endpoint: ${a}`,{status:h.status,statusText:h.statusText,text:i})}if(202===h.status){let t;await h.text?.().catch(()=>{}),t=e,ng.safeParse(t).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let f=(Array.isArray(e)?e:[e]).some(e=>"method"in e&&"id"in e&&void 0!==e.id),m=h.headers.get("content-type"),y=function(e){if(e)try{return ul.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(""===t||e.slice(t.length).includes(","))return;return t}}(m);if(f)if("text/event-stream"===y)this._handleSseStream(h.body,{onresumptiontoken:n,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if("application/json"===y){let e=await h.json();for(let t of Array.isArray(e)?e.map(e=>a7.parse(e)):[a7.parse(e)])this.onmessage?.(t)}else throw await h.text?.().catch(()=>{}),new lM(lA.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m});else await h.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&405!==r.status)throw new lL(lA.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};let p9=require("node:process"),p4=require("node:stream");var p3=i(6507);let p5="win32"===p9.platform?["APPDATA","COMSPEC","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PATHEXT","PROCESSOR_ARCHITECTURE","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","WINDIR"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];var p6=class{_process;_readBuffer;_serverParams;_stderrStream=null;onclose;onerror;onmessage;constructor(e){this._serverParams=e,this._readBuffer=new uc({maxBufferSize:e.maxBufferSize}),("pipe"===e.stderr||"overlapped"===e.stderr)&&(this._stderrStream=new p4.PassThrough)}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=p3(this._serverParams.command,this._serverParams.args??[],{env:{...function(){let e={};for(let t of p5){let r=p9.env[t];void 0!==r&&(r.startsWith("()")||(e[t]=r))}return e}(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:"win32"===p9.platform,cwd:this._serverParams.cwd}),this._process.on("error",e=>{t(e),this.onerror?.(e)}),this._process.on("spawn",()=>{e()}),this._process.on("close",e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",e=>{this.onerror?.(e)}),this._process.stdout?.on("data",e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}}),this._process.stdout?.on("error",e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async _dispose(){let e=this._process;if(this._process=void 0,e&&null===e.exitCode&&null===e.signalCode){let t=new Promise(t=>e.once("exit",()=>t()));try{e.stdin?.end()}catch{}try{e.kill("SIGTERM")}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,1e3).unref())]),null===e.exitCode&&null===e.signalCode)try{e.kill("SIGKILL")}catch{}await t}try{e?.stdout?.destroy()}catch{}try{e?.stdin?.destroy()}catch{}try{e?.stderr?.destroy()}catch{}this._readBuffer.clear()}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once("close",()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),null===e.exitCode){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(null===e.exitCode)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new lM(lA.NotConnected,"Not connected");let r=JSON.stringify(e)+"\n";this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}};let p8=i(8330),p7={name:p8.name,version:p8.version};async function he(e,t={}){var r,o,i,a;let n,s,l,{handlers:c={}}=t,u=new pB(p7,{capabilities:(s={},(r=c).sampling&&(s.sampling={}),r.elicitation&&(s.elicitation={form:{},url:{}}),r.roots&&(s.roots={}),s),versionNegotiation:t.versionNegotiation??{mode:"auto"}});o=u,(i=c).sampling&&o.setRequestHandler("sampling/createMessage",i.sampling),i.elicitation&&o.setRequestHandler("elicitation/create",i.elicitation),i.roots&&o.setRequestHandler("roots/list",i.roots);let d="http"===e.type?new p2(new URL(e.url),{requestInit:{headers:(a=e.headers??[],l={},a.forEach(e=>{let t,r=e.name.trim();if("env"in(t=e)&&"string"==typeof t.env){let t=process.env[e.env];if(void 0===t)throw Error(`Environment variable "${e.env}" is not set (required for header "${r}")`);l[r]=t}else l[r]=e.value.trim()}),l)}}):new p6({command:e.command,args:e.args,env:e.env,cwd:e.cwd,stderr:e.stderr??(t.onStderrData?"pipe":"inherit")});d instanceof p6&&d.stderr?.on("data",t.onStderrData??(e=>{process.stderr.write(e)}));let p=d.close.bind(d);d.close=()=>n??(n=p());let h=u.close.bind(u);u.close=async()=>{try{await h()}finally{await d.close()}};let f=t.connect?.signal,m=()=>{d.close().catch(()=>{})};try{return f?.throwIfAborted(),f?.addEventListener("abort",m,{once:!0}),await u.connect(d,t.connect),f?.throwIfAborted(),u}catch(e){try{await u.close()}catch(t){throw AggregateError([e,t],"Client connection and cleanup failed",{cause:e})}throw f?.throwIfAborted(),e}finally{f?.removeEventListener("abort",m)}}async function ht(e,t,r){let o=await he(e,r);try{return await t(o)}finally{await o.close()}}})(),exports.createClient=a.createClient,exports.withClient=a.withClient,a)-1===["createClient","withClient"].indexOf(n)&&(exports[n]=a[n]);Object.defineProperty(exports,"__esModule",{value:!0})})();
|
package/dist/cloudflare.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("zod/v3"));else if("function"==typeof define&&define.amd)define(["zod/v3"],t);else{var r="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,o),i.exports}o.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{let e;o.r(n),o.d(n,{apiKeyAuthMiddleware:()=>a,audio:()=>eT,embeddedResource:()=>eK,image:()=>eS,jwtAuthMiddleware:()=>eE});var t=o(4953);let r=t.z.object({apiKey:t.z.string().optional(),headerName:t.z.string().optional(),validateApiKey:t.z.function().args(t.z.string()).returns(t.z.promise(t.z.boolean())).optional()}).strict().refine(e=>void 0!==e.apiKey||void 0!==e.validateApiKey,{message:"Either 'apiKey' or 'validateApiKey' must be provided"}).refine(e=>void 0===e.apiKey||void 0===e.validateApiKey,{message:"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one"}),i="Unauthorized: Missing or invalid API key";function a(e){let t=r.safeParse(e);if(!t.success){let r="apiKey"in e,o="validateApiKey"in e;if(r&&o)throw Error("'apiKey' and 'validateApiKey' are mutually exclusive - provide only one");if(r||o)throw Error(`Invalid configuration: ${t.error.message}`);throw Error("Either 'apiKey' or 'validateApiKey' must be provided")}let o=e.headerName??"x-api-key",n="apiKey"in e?e.apiKey:void 0,a="validateApiKey"in e?e.validateApiKey:void 0;return async t=>{let r=t.headers.get(o);if(!r||"apiKey"in e&&r!==n||a&&!await a(r))return s(i)}}function s(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}class c extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class u extends c{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class l extends c{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class p extends c{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class d extends c{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class y extends c{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class f extends c{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class h extends c{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let m=new TextEncoder,g=new TextDecoder,w=new TextDecoder("utf-8",{fatal:!0}),v=/[^\x00-\x7f]/;function E(e){if("string"==typeof e&&e.length>=128){if(v.test(e))throw TypeError("non-ASCII string encountered in encode()");return m.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function A(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);return o}function b(e){try{return A("string"==typeof e?e:g.decode(e),!0)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function S(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function T(e,t,r){try{return b(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}function K(e,t,r){let o;try{o=JSON.parse(w.decode(b(e)))}catch(e){throw new t(r,{cause:e})}if(!S(o))throw new t(r);return o}let k={__proto__:null,b64:!0};function C(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}let _=[["verify"],["sign"]];function I(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:_}}function P(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:_,minRsaBits:2048}}function x(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:_}}function O(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:_}}function R(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:_}}let W=C({HS256:I(256),HS384:I(384),HS512:I(512),RS256:P(256),RS384:P(384),RS512:P(512),PS256:P(256,32),PS384:P(384,48),PS512:P(512,64),ES256:x("P-256",256),ES384:x("P-384",384),ES512:x("P-521",512),EdDSA:O(),Ed25519:O(),"ML-DSA-44":R(44),"ML-DSA-65":R(65),"ML-DSA-87":R(87)}),J={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"},N=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}};function j(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),TypeError(function(e,t,...r){if(r.length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(`Key for the ${e} algorithm must be `,t,...o))}let $=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function D(e){let t={__proto__:null,...e};if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){let e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}function U(e){if(void 0!==e&&"boolean"!=typeof e)throw TypeError('"extractable" option must be a boolean');return e}async function H(e,t,r){if(!e.kty.includes(t.kty))throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[+!!n])}function L(e){try{return E(e)}catch(e){throw new y("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}let M={s:1,m:60,h:3600,d:86400,w:604800,y:0x1e187e0},B=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,z="check_failed";function G(){throw TypeError("Invalid time period format")}function F(e){"string"!=typeof e&&G();let t=B.exec(e);(!t||t[4]&&t[1])&&G();let r=Math.round(parseFloat(t[2])*M[t[3][0].toLowerCase()]);return Number.isFinite(r)||G(),"-"===t[1]||"ago"===t[4]?-r:r}function V(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let q=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function X(e,t,r=!1){let o=e[t];if(!(void 0===o&&!r)){if("number"!=typeof o)throw new u(`"${t}" claim must be a number`,e,t,"invalid");return o}}function Y(e,t){throw new u(`unexpected "${t}" claim value`,e,t,z)}let Q=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Z=[[],["deriveBits"]],ee=[[],[]];function et(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Q,ops:["wrapKey","unwrapKey"]}}function er(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Z,ops:[void 0,"deriveBits"]}}function eo(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ee,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function en(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ee,ops:["deriveBits","deriveBits"]}}let ei=C({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ee,ops:["encrypt","decrypt"]},"RSA-OAEP":et(1),"RSA-OAEP-256":et(256),"RSA-OAEP-384":et(384),"RSA-OAEP-512":et(512),"ECDH-ES":er("direct-key-agreement"),"ECDH-ES+A128KW":er("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":er("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":er("key-agreement-with-key-wrapping"),A128KW:eo(128),A192KW:eo(192),A256KW:eo(256),A128GCMKW:eo(128,!0),A192GCMKW:eo(192,!0),A256GCMKW:eo(256,!0),"PBES2-HS256+A128KW":en(),"PBES2-HS384+A192KW":en(),"PBES2-HS512+A256KW":en()}),ea=["encrypt","decrypt"];function es(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ee,ops:ea,cekBits:e,ivBits:t?128:96,cbc:t}}C({A128GCM:es(128),A192GCM:es(192),A256GCM:es(256),"A128CBC-HS256":es(256,!0),"A192CBC-HS384":es(384,!0),"A256CBC-HS512":es(512,!0)});let ec='"alg" (Algorithm)';function eu(e='JWK "alg" (Algorithm) Parameter'){throw new d(`Invalid or unsupported ${e} value`)}function el(e,t){return("string"==typeof e?W[e]??ei[e]:void 0)??eu(t)}let ep=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},ed=e=>({data:e,pos:0}),ey=e=>{let t=e.data[e.pos++];if(void 0===t)throw Error("Unexpected end of ASN.1 input");return t},ef=e=>{let t=ey(e);if(128&t){let r=127&t,o=0;for(let t=0;t<r;t++)o=o<<8|ey(e);return o}return t},eh=(e,t=1)=>{for(;t-- >0;){e.pos++;let t=ef(e);e.pos+=t}},em=(e,t,r)=>{if(ey(e)!==t)throw Error(r)},eg=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},ew=async(e,t,r,o)=>{let n,i=U(o?.extractable),a=el(r,ec);a.secret&&eu(ec);let s="spki"===e;if(a.resolve)try{let r=ed(t);(function(e,t){if(em(e,48,`Invalid ${"spki"===t?"SPKI":"PKCS#8"} structure`),ef(e),"pkcs8"===t){em(e,2,"Expected version field");let t=ef(e);e.pos+=t}em(e,48,"Expected algorithm identifier"),ef(e)})(r,e),n=a.resolve({crv:(e=>{let t,r=(em(e,6,"Expected algorithm OID"),t=ef(e),eg(e,t));if(ep(r,[43,101,110]))return"X25519";if(!ep(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");em(e,6,"Expected curve OID");let o=ef(e),n=eg(e,o);if(ep(n,[42,134,72,206,61,3,1,7]))return"P-256";if(ep(n,[43,129,4,0,34]))return"P-384";if(ep(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")})(r)})}catch(e){throw new d("Invalid or unsupported key format",{cause:e})}else n=a.subtle;return crypto.subtle.importKey(e,t,n,i??s,a.usages[+!s])},ev=(e,t)=>A(e.replace(t,""));function eE(t){return async r=>{let o=function(e){if(!e)return null;let[t,r]=e.split(" ");return t&&r&&"bearer"===t.toLowerCase()&&r.trim()||null}(r.headers.get("authorization"));if(!o)return eA("Unauthorized: Missing or malformed Authorization header");try{await async function(t,r){var o;let n,{secret:i,...a}=r,s=function(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if("string"!=typeof t||!t)throw TypeError(r);return K(t,TypeError,r)}(t),c=a.algorithms?.[0]??("string"==typeof s.alg?s.alg:void 0);if(!c)throw Error("Missing JWT algorithm");let m=await async function(e,t){let r=e.trim();if(r.startsWith("{"))try{let e=JSON.parse(r);return await async function(e,t){if(!S(e))throw TypeError("JWK must be an object");let r=D(e),o=U(void 0),{alg:n}=r;if(t??=n,"oct"!==r.kty&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(r.kty){case"oct":if("string"!=typeof r.k)throw TypeError('missing "k" (Key Value) Parameter value');return b(r.k);case"AKP":if("string"!=typeof n||!n)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==n)throw TypeError("JWK alg and alg option value mismatch");return H(el(t),r,o);case"RSA":case"EC":case"OKP":return H(el(t),r,o);default:throw new d('Unsupported "kty" (Key Type) Parameter value')}}(e,t)}catch{return new TextEncoder().encode(e)}return r.includes("BEGIN CERTIFICATE")?await async function(e,t){let r;if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');try{let t=ev(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);r=function(e){let t=ed(e);em(t,48,"Invalid certificate structure");let r=ef(t);if(r<0||t.pos+r>t.data.length)throw Error("Unexpected end of ASN.1 input");em(t,48,"Invalid tbsCertificate structure"),ef(t),160===e[t.pos]?eh(t,6):eh(t,5);let o=t.pos;em(t,48,"Invalid SPKI structure");let n=ef(t);return e.subarray(o,o+n+(t.pos-o))}(t)}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return ew("spki",r,t,void 0)}(r,t):r.includes("BEGIN PUBLIC KEY")?await async function(e,t){var r;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return r=void 0,ew("spki",ev(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,r)}(r,t):new TextEncoder().encode(e)}(i,c),v=(o=a,n={},o.algorithms&&(n.algorithms=o.algorithms),o.audience&&("string"==typeof o.audience?n.audience=o.audience:Array.isArray(o.audience)&&(n.audience=o.audience)),o.issuer&&(n.issuer=o.issuer),o.subject&&(n.subject=o.subject),void 0!==o.clockTolerance&&(n.clockTolerance=o.clockTolerance),void 0!==o.maxAge&&(n.maxTokenAge=o.maxAge),n),{payload:A}=await async function(t,r,o){let[n,i]=await async function(t,r,o){if(t instanceof Uint8Array&&(t=g.decode(t)),"string"!=typeof t)throw new y("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:a,length:s}=t.split(".");if(3!==s)throw new y("Invalid Compact JWS");return async function(t,r,o,n){let{protected:i,header:a,payload:s}=t,c=void 0===i?{}:K(i,y,"JWS Protected Header is invalid");if(!function(...e){let t=new Set;for(let r of e)if(r)for(let e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}(c,a))throw new y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...a},l=function(e,t){if(t.includes("b64")){let t=e.b64;if("boolean"!=typeof t)throw new y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}(c,function(e,t,r,o,n){if(void 0!==n.crit&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return[];if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=void 0===r?t:{__proto__:null,...r,...t};for(let t of o.crit){if(!(t in i))throw new d(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(n,t)||void 0===n[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i[t]&&(!Object.hasOwn(o,t)||void 0===o[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return o.crit}(y,k,r[1],c,u)),{alg:f}=u;if("string"!=typeof f||!f)throw new y('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(r[0]&&!r[0].has(f))throw new p('"alg" (Algorithm) Header Parameter value not allowed');if(l){if("string"!=typeof s)throw new y("JWS Payload must be a string")}else if("string"!=typeof s&&!(s instanceof Uint8Array))throw new y("JWS Payload must be a string or an Uint8Array instance");let m=l||"string"!=typeof s?s:n(s),g=!1;"function"==typeof o&&(o=await o(c,t),g=!0);let w=function(e){let t="string"==typeof e?W[e]:void 0;if(!t)throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}(f),v=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}(void 0!==i?E(i):new Uint8Array,E("."),"string"==typeof m?r[2]??=function(e,t,r){try{return E(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}(m,"payload",y):m),A=T(t.signature,"signature",y),C=await async function(t,r,o){let n,i,{alg:a,secret:s}=t,c="decrypt"===o||"sign"===o;if(s&&r instanceof Uint8Array)return r;if(S(r)){if("string"!=typeof(n=D(r)).kty)throw j(a,r,s);if(!(s?"oct"===n.kty&&"string"==typeof n.k:"oct"!==n.kty&&(c?"AKP"===n.kty&&"string"==typeof n.priv||"string"==typeof n.d:void 0===n.d&&void 0===n.priv)))throw TypeError(s?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${c?"private":"public"} JWK`);if(((e,t,r)=>{let{alg:o}=e;if(void 0!==t.use){let e="sign"===r||"verify"===r?"sig":"enc";if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==o)throw TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let o="encrypt"===r||"decrypt"===r?e.ops?.[+("encrypt"!==r)]:r;if(o&&!t.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}})(t,n,o),"oct"===n.kty)return b(n.k);if(!Object.isFrozen(r)){let{key_ops:e}=r;Array.isArray(e)&&Object.freeze(e),Object.freeze(r)}}else{if(!(e=>N(e)||e?.[Symbol.toStringTag]==="KeyObject")(r))throw j(a,r,s);let e=s?"secret":c?"private":"public";if(r.type!==e&&(s||["secret","public","private"].includes(r.type)))throw TypeError(`${r[Symbol.toStringTag]} instances must be of type "${e}" for the ${a} algorithm`);if(N(r))return r;if("secret"===(i=r).type)return i.export()}let u=(e||=new WeakMap).get(r);if(u?.[a])return u[a];if(u||e.set(r,u={}),i&&"function"==typeof i.toCryptoKey){let e="public"===i.type,r=J[i.asymmetricKeyDetails?.namedCurve],o=t.resolve?.({crv:r,asymmetricKeyType:i.asymmetricKeyType})??t.subtle;return u[a]=i.toCryptoKey(o,e,t.usages[+!e])}return(n??=i.export({format:"jwk"})).alg=a,u[a]=await H(t,n)}(w,o,"verify"),_=await async function(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),function(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw $(t.name);if(t.hash&&o.hash?.name!==t.hash)throw $(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw $(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&o.length!==t.length)throw $(t.length,"algorithm.length");if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(e,t,r),e}(C,w.subtle,"verify");w.minRsaBits&&function(e,t){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}(w.alg,_);let I=!1;try{I=await crypto.subtle.verify(w.signing,_,A,v)}catch(e){throw new h(void 0,{cause:e})}if(!I)throw new h;let P={payload:"string"==typeof m?T(m,"payload",y):m};return void 0!==i&&(P.protectedHeader=c),void 0!==a&&(P.unprotectedHeader=a),g?[{...P,key:C},l]:[P,l]}({payload:i,protected:n,signature:a},r,o,L)}(t,[o&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);return void 0===t?void 0:new Set(t)}("algorithms",o.algorithms),o?.crit],r);if(!i)throw new f("JWTs MUST NOT use unencoded payload");let a=function(e,t,r={}){let o,n,i;try{o=JSON.parse(w.decode(t))}catch(e){throw new f("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!S(o))throw new f("JWT Claims Set must be a top-level JSON object");let{typ:a}=r;if(void 0!==a&&("string"!=typeof e.typ||q(e.typ)!==q(a)))throw new u('unexpected "typ" JWT header value',o,"typ",z);let{requiredClaims:s=[],issuer:c,subject:p,audience:d,maxTokenAge:y}=r,h=[...s];for(let e of(void 0!==y&&h.push("iat"),void 0!==d&&h.push("aud"),void 0!==p&&h.push("sub"),void 0!==c&&h.push("iss"),new Set(h.reverse())))if(!Object.hasOwn(o,e))throw new u(`missing required "${e}" claim`,o,e,"missing");void 0===c||(Array.isArray(c)?c:[c]).includes(o.iss)||Y(o,"iss"),void 0!==p&&o.sub!==p&&Y(o,"sub"),void 0===d||(n=o.aud,i="string"==typeof d?[d]:d,"string"==typeof n?i.includes(n):!!Array.isArray(n)&&i.some(e=>n.includes(e)))||Y(o,"aud");let{clockTolerance:m}=r,g=0;if("string"==typeof m)g=F(m);else if(void 0!==m){if("number"!=typeof m)throw TypeError("Invalid clockTolerance option type");g=m}if(V("clockTolerance option",g),g<0)throw TypeError("Invalid clockTolerance option input");let{currentDate:v}=r,E=V("currentDate option",Math.floor((void 0===v?new Date:v).getTime()/1e3)),A=X(o,"iat",void 0!==y),b=X(o,"nbf");if(void 0!==b&&b>E+g)throw new u('"nbf" claim timestamp check failed',o,"nbf",z);let T=X(o,"exp");if(void 0!==T&&T<=E-g)throw new l('"exp" claim timestamp check failed',o,"exp",z);if(void 0!==y){let e=E-A,t=V("maxTokenAge option","number"==typeof y?y:F(y));if(t<0)throw TypeError("Invalid maxTokenAge option input");if(e-g>t)throw new l('"iat" claim timestamp check failed (too far in the past)',o,"iat",z);if(e<-g)throw new u('"iat" claim timestamp check failed (it should be in the past)',o,"iat",z)}return o}(n.protectedHeader,n.payload,o);return{...n,payload:a}}(t,m,v);return A}(o,t);return}catch{return eA("Unauthorized: Invalid or expired token")}}}function eA(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}function eb(e){let t;if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else throw TypeError("Expected bytes as a Uint8Array or ArrayBuffer");let r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function eS(e,t){return{type:"image",data:eb(e),mimeType:t}}function eT(e,t){return{type:"audio",data:eb(e),mimeType:t}}function eK(e,t,r){return{type:"resource",resource:{uri:e,...void 0===r?{}:{mimeType:r},..."string"==typeof t?{text:t}:{blob:eb(t)}}}}})(),n})());
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(this,()=>(()=>{"use strict";let e;var t={};t.d=(e,r,o)=>{var n=(r,o)=>{for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[o]:r[n]})};n(r,"get"),n(o,"value")},t.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};t.r(r),t.d(r,{apiKeyAuthMiddleware:()=>a,audio:()=>eT,embeddedResource:()=>eK,image:()=>eS,jwtAuthMiddleware:()=>eE});let o=require("zod/v3"),n=o.z.object({apiKey:o.z.string().optional(),headerName:o.z.string().optional(),validateApiKey:o.z.function().args(o.z.string()).returns(o.z.promise(o.z.boolean())).optional()}).strict().refine(e=>void 0!==e.apiKey||void 0!==e.validateApiKey,{message:"Either 'apiKey' or 'validateApiKey' must be provided"}).refine(e=>void 0===e.apiKey||void 0===e.validateApiKey,{message:"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one"}),i="Unauthorized: Missing or invalid API key";function a(e){let t=n.safeParse(e);if(!t.success){let r="apiKey"in e,o="validateApiKey"in e;if(r&&o)throw Error("'apiKey' and 'validateApiKey' are mutually exclusive - provide only one");if(r||o)throw Error(`Invalid configuration: ${t.error.message}`);throw Error("Either 'apiKey' or 'validateApiKey' must be provided")}let r=e.headerName??"x-api-key",o="apiKey"in e?e.apiKey:void 0,a="validateApiKey"in e?e.validateApiKey:void 0;return async t=>{let n=t.headers.get(r);if(!n||"apiKey"in e&&n!==o||a&&!await a(n))return s(i)}}function s(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}class c extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class u extends c{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class l extends c{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",o="unspecified"){super(e,{cause:{claim:r,reason:o,payload:t}}),this.claim=r,this.reason=o,this.payload=t}}class p extends c{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class d extends c{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class y extends c{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class f extends c{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class h extends c{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let m=new TextEncoder,g=new TextDecoder,w=new TextDecoder("utf-8",{fatal:!0}),v=/[^\x00-\x7f]/;function E(e){if("string"==typeof e&&e.length>=128){if(v.test(e))throw TypeError("non-ASCII string encountered in encode()");return m.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function A(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);return o}function b(e){try{return A("string"==typeof e?e:g.decode(e),!0)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.",{cause:e})}}function S(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function T(e,t,r){try{return b(e)}catch(e){throw new r(`Failed to base64url decode the ${t}`,{cause:e})}}function K(e,t,r){let o;try{o=JSON.parse(w.decode(b(e)))}catch(e){throw new t(r,{cause:e})}if(!S(o))throw new t(r);return o}let k={__proto__:null,b64:!0};function C(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}let _=[["verify"],["sign"]];function I(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:_}}function P(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:_,minRsaBits:2048}}function O(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:_}}function R(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:_}}function x(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:_}}let W=C({HS256:I(256),HS384:I(384),HS512:I(512),RS256:P(256),RS384:P(384),RS512:P(512),PS256:P(256,32),PS384:P(384,48),PS512:P(512,64),ES256:O("P-256",256),ES384:O("P-384",384),ES512:O("P-521",512),EdDSA:R(),Ed25519:R(),"ML-DSA-44":x(44),"ML-DSA-65":x(65),"ML-DSA-87":x(87)}),J={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"},N=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}};function $(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),TypeError(function(e,t,...r){if(r.length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(`Key for the ${e} algorithm must be `,t,...o))}let j=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function D(e){let t={__proto__:null,...e};if(void 0!==t.ext&&"boolean"!=typeof t.ext)throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(void 0!==t.key_ops){let e=t.key_ops,r=Array.isArray(e)?[...e]:void 0;if(!r||r.some(e=>"string"!=typeof e)||new Set(r).size!==r.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=r}return t}function U(e){if(void 0!==e&&"boolean"!=typeof e)throw TypeError('"extractable" option must be a boolean');return e}async function H(e,t,r){if(!e.kty.includes(t.kty))throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return"AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[+!!n])}function L(e){try{return E(e)}catch(e){throw new y("JWS Compact Serialization payload must use only ASCII characters",{cause:e})}}let M={s:1,m:60,h:3600,d:86400,w:604800,y:0x1e187e0},B=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,G="check_failed";function z(){throw TypeError("Invalid time period format")}function F(e){"string"!=typeof e&&z();let t=B.exec(e);(!t||t[4]&&t[1])&&z();let r=Math.round(parseFloat(t[2])*M[t[3][0].toLowerCase()]);return Number.isFinite(r)||z(),"-"===t[1]||"ago"===t[4]?-r:r}function V(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let X=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`};function q(e,t,r=!1){let o=e[t];if(!(void 0===o&&!r)){if("number"!=typeof o)throw new u(`"${t}" claim must be a number`,e,t,"invalid");return o}}function Y(e,t){throw new u(`unexpected "${t}" claim value`,e,t,G)}let Q=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],Z=[[],["deriveBits"]],ee=[[],[]];function et(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:Q,ops:["wrapKey","unwrapKey"]}}function er(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:e,crv:t,asymmetricKeyType:r})=>{if("X25519"===t||"x25519"===r)return{name:"X25519"};if("OKP"===e)throw new d('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:t}},usages:Z,ops:[void 0,"deriveBits"]}}function eo(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ee,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function en(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ee,ops:["deriveBits","deriveBits"]}}let ei=C({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ee,ops:["encrypt","decrypt"]},"RSA-OAEP":et(1),"RSA-OAEP-256":et(256),"RSA-OAEP-384":et(384),"RSA-OAEP-512":et(512),"ECDH-ES":er("direct-key-agreement"),"ECDH-ES+A128KW":er("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":er("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":er("key-agreement-with-key-wrapping"),A128KW:eo(128),A192KW:eo(192),A256KW:eo(256),A128GCMKW:eo(128,!0),A192GCMKW:eo(192,!0),A256GCMKW:eo(256,!0),"PBES2-HS256+A128KW":en(),"PBES2-HS384+A192KW":en(),"PBES2-HS512+A256KW":en()}),ea=["encrypt","decrypt"];function es(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ee,ops:ea,cekBits:e,ivBits:t?128:96,cbc:t}}C({A128GCM:es(128),A192GCM:es(192),A256GCM:es(256),"A128CBC-HS256":es(256,!0),"A192CBC-HS384":es(384,!0),"A256CBC-HS512":es(512,!0)});let ec='"alg" (Algorithm)';function eu(e='JWK "alg" (Algorithm) Parameter'){throw new d(`Invalid or unsupported ${e} value`)}function el(e,t){return("string"==typeof e?W[e]??ei[e]:void 0)??eu(t)}let ep=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},ed=e=>({data:e,pos:0}),ey=e=>{let t=e.data[e.pos++];if(void 0===t)throw Error("Unexpected end of ASN.1 input");return t},ef=e=>{let t=ey(e);if(128&t){let r=127&t,o=0;for(let t=0;t<r;t++)o=o<<8|ey(e);return o}return t},eh=(e,t=1)=>{for(;t-- >0;){e.pos++;let t=ef(e);e.pos+=t}},em=(e,t,r)=>{if(ey(e)!==t)throw Error(r)},eg=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},ew=async(e,t,r,o)=>{let n,i=U(o?.extractable),a=el(r,ec);a.secret&&eu(ec);let s="spki"===e;if(a.resolve)try{let r=ed(t);(function(e,t){if(em(e,48,`Invalid ${"spki"===t?"SPKI":"PKCS#8"} structure`),ef(e),"pkcs8"===t){em(e,2,"Expected version field");let t=ef(e);e.pos+=t}em(e,48,"Expected algorithm identifier"),ef(e)})(r,e),n=a.resolve({crv:(e=>{let t,r=(em(e,6,"Expected algorithm OID"),t=ef(e),eg(e,t));if(ep(r,[43,101,110]))return"X25519";if(!ep(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");em(e,6,"Expected curve OID");let o=ef(e),n=eg(e,o);if(ep(n,[42,134,72,206,61,3,1,7]))return"P-256";if(ep(n,[43,129,4,0,34]))return"P-384";if(ep(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")})(r)})}catch(e){throw new d("Invalid or unsupported key format",{cause:e})}else n=a.subtle;return crypto.subtle.importKey(e,t,n,i??s,a.usages[+!s])},ev=(e,t)=>A(e.replace(t,""));function eE(t){return async r=>{let o=function(e){if(!e)return null;let[t,r]=e.split(" ");return t&&r&&"bearer"===t.toLowerCase()&&r.trim()||null}(r.headers.get("authorization"));if(!o)return eA("Unauthorized: Missing or malformed Authorization header");try{await async function(t,r){var o;let n,{secret:i,...a}=r,s=function(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if("string"!=typeof t||!t)throw TypeError(r);return K(t,TypeError,r)}(t),c=a.algorithms?.[0]??("string"==typeof s.alg?s.alg:void 0);if(!c)throw Error("Missing JWT algorithm");let m=await async function(e,t){let r=e.trim();if(r.startsWith("{"))try{let e=JSON.parse(r);return await async function(e,t){if(!S(e))throw TypeError("JWK must be an object");let r=D(e),o=U(void 0),{alg:n}=r;if(t??=n,"oct"!==r.kty&&!t)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(r.kty){case"oct":if("string"!=typeof r.k)throw TypeError('missing "k" (Key Value) Parameter value');return b(r.k);case"AKP":if("string"!=typeof n||!n)throw TypeError('missing "alg" (Algorithm) Parameter value');if(t!==n)throw TypeError("JWK alg and alg option value mismatch");return H(el(t),r,o);case"RSA":case"EC":case"OKP":return H(el(t),r,o);default:throw new d('Unsupported "kty" (Key Type) Parameter value')}}(e,t)}catch{return new TextEncoder().encode(e)}return r.includes("BEGIN CERTIFICATE")?await async function(e,t){let r;if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');try{let t=ev(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);r=function(e){let t=ed(e);em(t,48,"Invalid certificate structure");let r=ef(t);if(r<0||t.pos+r>t.data.length)throw Error("Unexpected end of ASN.1 input");em(t,48,"Invalid tbsCertificate structure"),ef(t),160===e[t.pos]?eh(t,6):eh(t,5);let o=t.pos;em(t,48,"Invalid SPKI structure");let n=ef(t);return e.subarray(o,o+n+(t.pos-o))}(t)}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return ew("spki",r,t,void 0)}(r,t):r.includes("BEGIN PUBLIC KEY")?await async function(e,t){var r;if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return r=void 0,ew("spki",ev(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,r)}(r,t):new TextEncoder().encode(e)}(i,c),v=(o=a,n={},o.algorithms&&(n.algorithms=o.algorithms),o.audience&&("string"==typeof o.audience?n.audience=o.audience:Array.isArray(o.audience)&&(n.audience=o.audience)),o.issuer&&(n.issuer=o.issuer),o.subject&&(n.subject=o.subject),void 0!==o.clockTolerance&&(n.clockTolerance=o.clockTolerance),void 0!==o.maxAge&&(n.maxTokenAge=o.maxAge),n),{payload:A}=await async function(t,r,o){let[n,i]=await async function(t,r,o){if(t instanceof Uint8Array&&(t=g.decode(t)),"string"!=typeof t)throw new y("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:a,length:s}=t.split(".");if(3!==s)throw new y("Invalid Compact JWS");return async function(t,r,o,n){let{protected:i,header:a,payload:s}=t,c=void 0===i?{}:K(i,y,"JWS Protected Header is invalid");if(!function(...e){let t=new Set;for(let r of e)if(r)for(let e of Object.keys(r)){if(t.has(e))return!1;t.add(e)}return!0}(c,a))throw new y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...a},l=function(e,t){if(t.includes("b64")){let t=e.b64;if("boolean"!=typeof t)throw new y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return t}return!0}(c,function(e,t,r,o,n){if(void 0!==n.crit&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return[];if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=void 0===r?t:{__proto__:null,...r,...t};for(let t of o.crit){if(!(t in i))throw new d(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(n,t)||void 0===n[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i[t]&&(!Object.hasOwn(o,t)||void 0===o[t]))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return o.crit}(y,k,r[1],c,u)),{alg:f}=u;if("string"!=typeof f||!f)throw new y('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(r[0]&&!r[0].has(f))throw new p('"alg" (Algorithm) Header Parameter value not allowed');if(l){if("string"!=typeof s)throw new y("JWS Payload must be a string")}else if("string"!=typeof s&&!(s instanceof Uint8Array))throw new y("JWS Payload must be a string or an Uint8Array instance");let m=l||"string"!=typeof s?s:n(s),g=!1;"function"==typeof o&&(o=await o(c,t),g=!0);let w=function(e){let t="string"==typeof e?W[e]:void 0;if(!t)throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}(f),v=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let o of e)t.set(o,r),r+=o.length;return t}(void 0!==i?E(i):new Uint8Array,E("."),"string"==typeof m?r[2]??=function(e,t,r){try{return E(e)}catch(e){throw new r(`The ${t} is not a valid base64url string`,{cause:e})}}(m,"payload",y):m),A=T(t.signature,"signature",y),C=await async function(t,r,o){let n,i,{alg:a,secret:s}=t,c="decrypt"===o||"sign"===o;if(s&&r instanceof Uint8Array)return r;if(S(r)){if("string"!=typeof(n=D(r)).kty)throw $(a,r,s);if(!(s?"oct"===n.kty&&"string"==typeof n.k:"oct"!==n.kty&&(c?"AKP"===n.kty&&"string"==typeof n.priv||"string"==typeof n.d:void 0===n.d&&void 0===n.priv)))throw TypeError(s?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${c?"private":"public"} JWK`);if(((e,t,r)=>{let{alg:o}=e;if(void 0!==t.use){let e="sign"===r||"verify"===r?"sig":"enc";if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==o)throw TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let o="encrypt"===r||"decrypt"===r?e.ops?.[+("encrypt"!==r)]:r;if(o&&!t.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}})(t,n,o),"oct"===n.kty)return b(n.k);if(!Object.isFrozen(r)){let{key_ops:e}=r;Array.isArray(e)&&Object.freeze(e),Object.freeze(r)}}else{if(!(e=>N(e)||e?.[Symbol.toStringTag]==="KeyObject")(r))throw $(a,r,s);let e=s?"secret":c?"private":"public";if(r.type!==e&&(s||["secret","public","private"].includes(r.type)))throw TypeError(`${r[Symbol.toStringTag]} instances must be of type "${e}" for the ${a} algorithm`);if(N(r))return r;if("secret"===(i=r).type)return i.export()}let u=(e||=new WeakMap).get(r);if(u?.[a])return u[a];if(u||e.set(r,u={}),i&&"function"==typeof i.toCryptoKey){let e="public"===i.type,r=J[i.asymmetricKeyDetails?.namedCurve],o=t.resolve?.({crv:r,asymmetricKeyType:i.asymmetricKeyType})??t.subtle;return u[a]=i.toCryptoKey(o,e,t.usages[+!e])}return(n??=i.export({format:"jwk"})).alg=a,u[a]=await H(t,n)}(w,o,"verify"),_=await async function(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),function(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw j(t.name);if(t.hash&&o.hash?.name!==t.hash)throw j(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw j(t.namedCurve,"algorithm.namedCurve");if(void 0!==t.length&&o.length!==t.length)throw j(t.length,"algorithm.length");if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(e,t,r),e}(C,w.subtle,"verify");w.minRsaBits&&function(e,t){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}(w.alg,_);let I=!1;try{I=await crypto.subtle.verify(w.signing,_,A,v)}catch(e){throw new h(void 0,{cause:e})}if(!I)throw new h;let P={payload:"string"==typeof m?T(m,"payload",y):m};return void 0!==i&&(P.protectedHeader=c),void 0!==a&&(P.unprotectedHeader=a),g?[{...P,key:C},l]:[P,l]}({payload:i,protected:n,signature:a},r,o,L)}(t,[o&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);return void 0===t?void 0:new Set(t)}("algorithms",o.algorithms),o?.crit],r);if(!i)throw new f("JWTs MUST NOT use unencoded payload");let a=function(e,t,r={}){let o,n,i;try{o=JSON.parse(w.decode(t))}catch(e){throw new f("JWT Claims Set must be a top-level JSON object",{cause:e})}if(!S(o))throw new f("JWT Claims Set must be a top-level JSON object");let{typ:a}=r;if(void 0!==a&&("string"!=typeof e.typ||X(e.typ)!==X(a)))throw new u('unexpected "typ" JWT header value',o,"typ",G);let{requiredClaims:s=[],issuer:c,subject:p,audience:d,maxTokenAge:y}=r,h=[...s];for(let e of(void 0!==y&&h.push("iat"),void 0!==d&&h.push("aud"),void 0!==p&&h.push("sub"),void 0!==c&&h.push("iss"),new Set(h.reverse())))if(!Object.hasOwn(o,e))throw new u(`missing required "${e}" claim`,o,e,"missing");void 0===c||(Array.isArray(c)?c:[c]).includes(o.iss)||Y(o,"iss"),void 0!==p&&o.sub!==p&&Y(o,"sub"),void 0===d||(n=o.aud,i="string"==typeof d?[d]:d,"string"==typeof n?i.includes(n):!!Array.isArray(n)&&i.some(e=>n.includes(e)))||Y(o,"aud");let{clockTolerance:m}=r,g=0;if("string"==typeof m)g=F(m);else if(void 0!==m){if("number"!=typeof m)throw TypeError("Invalid clockTolerance option type");g=m}if(V("clockTolerance option",g),g<0)throw TypeError("Invalid clockTolerance option input");let{currentDate:v}=r,E=V("currentDate option",Math.floor((void 0===v?new Date:v).getTime()/1e3)),A=q(o,"iat",void 0!==y),b=q(o,"nbf");if(void 0!==b&&b>E+g)throw new u('"nbf" claim timestamp check failed',o,"nbf",G);let T=q(o,"exp");if(void 0!==T&&T<=E-g)throw new l('"exp" claim timestamp check failed',o,"exp",G);if(void 0!==y){let e=E-A,t=V("maxTokenAge option","number"==typeof y?y:F(y));if(t<0)throw TypeError("Invalid maxTokenAge option input");if(e-g>t)throw new l('"iat" claim timestamp check failed (too far in the past)',o,"iat",G);if(e<-g)throw new u('"iat" claim timestamp check failed (it should be in the past)',o,"iat",G)}return o}(n.protectedHeader,n.payload,o);return{...n,payload:a}}(t,m,v);return A}(o,t);return}catch{return eA("Unauthorized: Invalid or expired token")}}}function eA(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}function eb(e){let t;if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else throw TypeError("Expected bytes as a Uint8Array or ArrayBuffer");let r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function eS(e,t){return{type:"image",data:eb(e),mimeType:t}}function eT(e,t){return{type:"audio",data:eb(e),mimeType:t}}function eK(e,t,r){return{type:"resource",resource:{uri:e,...void 0===r?{}:{mimeType:r},..."string"==typeof t?{text:t}:{blob:eb(t)}}}}return r})());
|