xmcp 1.10.0 → 1.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/client.js +42 -44
- package/dist/cloudflare.js +1 -3
- package/dist/config.js +1 -1
- package/dist/host-bridge.js +1 -1
- package/dist/index.js +55 -52
- package/dist/node.js +1 -1
- package/dist/runtime/adapter-express.js +74 -74
- package/dist/runtime/adapter-fastify.js +74 -74
- package/dist/runtime/adapter-fetch-cloudflare.js +69 -69
- package/dist/runtime/adapter-fetch.js +74 -74
- package/dist/runtime/adapter-nestjs.js +70 -70
- package/dist/runtime/adapter-nextjs.js +72 -72
- package/dist/runtime/cloudflare-worker.js +219 -219
- package/dist/runtime/headers.js +1 -1
- package/dist/runtime/http.js +95 -90
- package/dist/runtime/stdio.js +70 -60
- package/dist/runtime/vercel.js +95 -90
- package/package.json +28 -26
package/dist/cloudflare.js
CHANGED
|
@@ -1,3 +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 a in r)("object"==typeof exports?exports:e)[a]=r[a]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},r={};function a(e){var i=r[e];if(void 0!==i)return i.exports;var o=r[e]={exports:{}};return t[e](o,o.exports,a),o.exports}a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{let e;a.r(i),a.d(i,{embeddedResource:()=>el,image:()=>es,jwtAuthMiddleware:()=>er,apiKeyAuthMiddleware:()=>n,audio:()=>ec});var t=a(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"}),o="Unauthorized: Missing or invalid API key";function n(e){let t=r.safeParse(e);if(!t.success){let r="apiKey"in e,a="validateApiKey"in e;if(r&&a)throw Error("'apiKey' and 'validateApiKey' are mutually exclusive - provide only one");if(r||a)throw Error(`Invalid configuration: ${t.error.message}`);throw Error("Either 'apiKey' or 'validateApiKey' must be provided")}let a=e.headerName??"x-api-key",i="apiKey"in e?e.apiKey:void 0,n="validateApiKey"in e?e.validateApiKey:void 0;return async t=>{let r=t.headers.get(a);if(!r||"apiKey"in e&&r!==i||n&&!await n(r))return s(o)}}function s(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}let c=new TextEncoder,l=new TextDecoder;function d(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);if(a>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=a}return t}function y(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function p(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:l.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=l.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return y(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function u(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}class f 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 h extends f{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class m extends f{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class S extends f{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class w extends f{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class g extends f{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class E extends f{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class A extends f{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class b extends f{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let v=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function K(e){return parseInt(e.name.slice(4),10)}function P(e,t,...r){if((r=r.filter(Boolean)).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}let k=(e,t,...r)=>P(`Key for the ${e} algorithm must be `,t,...r);async function C(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>P("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return!function(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if("HMAC"!==e.algorithm.name)throw v("HMAC");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if("RSASSA-PKCS1-v1_5"!==e.algorithm.name)throw v("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if("RSA-PSS"!==e.algorithm.name)throw v("RSA-PSS");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if("Ed25519"!==e.algorithm.name)throw v("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let a;if(a=e.algorithm,a.name!==t)throw v(t);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==e.algorithm.name)throw v("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw v(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(t,e,r),t}async function T(e,t,r,a){let i=await C(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}(e,i);let o=function(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm);try{return await crypto.subtle.verify(o,i,r,a)}catch{return!1}}let R=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},I=e=>e?.[Symbol.toStringTag]==="KeyObject",O=e=>R(e)||I(e),W=e=>u(e)&&"string"==typeof e.kty,_=e=>e?.[Symbol.toStringTag],H=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="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!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let a;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):a=r;break;case e.startsWith("PBES2"):a="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):a=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):a="wrapKey";break;case"decrypt"===r:a=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(a&&t.key_ops?.includes?.(a)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${a}" when present`)}return!0};async function D(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new w('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),a={...e};return"AKP"!==a.kty&&delete a.alg,delete a.use,crypto.subtle.importKey("jwk",a,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let J=async(t,r,a,i=!1)=>{let o=(e||=new WeakMap).get(t);if(o?.[a])return o[a];let n=await D({...r,alg:a});return i&&Object.freeze(t),o?o[a]=n:e.set(t,{[a]:n}),n};async function x(t,r){if(t instanceof Uint8Array||R(t))return t;if(I(t)){if("secret"===t.type)return t.export();if("toCryptoKey"in t&&"function"==typeof t.toCryptoKey)try{return((t,r)=>{let a,i=(e||=new WeakMap).get(t);if(i?.[r])return i[r];let o="public"===t.type,n=!!o;if("x25519"===t.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}a=t.toCryptoKey(t.asymmetricKeyType,n,o?[]:["deriveBits"])}if("ed25519"===t.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==t.asymmetricKeyType.toUpperCase())throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}if("rsa"===t.asymmetricKeyType){let e;switch(r){case"RSA-OAEP":e="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":e="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":e="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":e="SHA-512";break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}if(r.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:e},n,o?["encrypt"]:["decrypt"]);a=t.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:e},n,[o?"verify":"sign"])}if("ec"===t.asymmetricKeyType){let e=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!e)throw TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===r&&"P-256"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES384"===r&&"P-384"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES512"===r&&"P-521"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),r.startsWith("ECDH-ES")&&(a=t.toCryptoKey({name:"ECDH",namedCurve:e},n,o?[]:["deriveBits"]))}if(!a)throw TypeError("given KeyObject instance cannot be used for this algorithm");return i?i[r]=a:e.set(t,{[r]:a}),a})(t,r)}catch(e){if(e instanceof TypeError)throw e}let a=t.export({format:"jwk"});return J(t,a,r)}if(W(t))return t.k?p(t.k):J(t,t,r,!0);throw Error("unreachable")}async function j(e,t,r){let a,i;if(!u(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!u(e.header))throw new g("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let t=p(e.protected);o=JSON.parse(l.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!function(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}(o,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...o,...e.header},s=function(e,t,r,a,i){let o;if(void 0!==i.crit&&a?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.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');for(let n of(o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,a.crit)){if(!o.has(n))throw new w(`Extension Header Parameter "${n}" is not recognized`);if(void 0===i[n])throw new e(`Extension Header Parameter "${n}" is missing`);if(o.get(n)&&void 0===a[n])throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(a.crit)}(g,new Map([["b64",!0]]),r?.crit,o,n),y=!0;if(s.has("b64")&&"boolean"!=typeof(y=o.b64))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:f}=n;if("string"!=typeof f||!f)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');let h=r&&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`);if(t)return new Set(t)}("algorithms",r.algorithms);if(h&&!h.has(f))throw new S('"alg" (Algorithm) Header Parameter value not allowed');if(y){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let m=!1;"function"==typeof t&&(t=await t(o,e),m=!0);var E=t,A="verify";switch(f.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(W(t)){if("oct"===t.kty&&"string"==typeof t.k&&H(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${_(t)} instances for symmetric algorithms must be of type "secret"`)}})(f,E,A);break;default:((e,t,r)=>{if(W(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${_(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${_(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${_(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(f,E,A)}let v=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let a of e)t.set(a,r),r+=a.length;return t}(void 0!==e.protected?d(e.protected):new Uint8Array,d("."),"string"==typeof e.payload?y?d(e.payload):c.encode(e.payload):e.payload);try{a=p(e.signature)}catch{throw new g("Failed to base64url decode the signature")}let K=await x(t,f);if(!await T(f,K,a,v))throw new b;if(y)try{i=p(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else i="string"==typeof e.payload?c.encode(e.payload):e.payload;let P={payload:i};return(void 0!==e.protected&&(P.protectedHeader=o),void 0!==e.header&&(P.unprotectedHeader=e.header),m)?{...P,key:K}:P}async function M(e,t,r){if(e instanceof Uint8Array&&(e=l.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");let{0:a,1:i,2:o,length:n}=e.split(".");if(3!==n)throw new g("Invalid Compact JWS");let s=await j({payload:i,protected:a,signature:o},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}let N=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function L(e){let t,r=N.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let a=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(a);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*a);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*a);break;case"day":case"days":case"d":t=Math.round(86400*a);break;case"week":case"weeks":case"w":t=Math.round(604800*a);break;default:t=Math.round(0x1e187e0*a)}return"-"===r[1]||"ago"===r[4]?-t:t}let $=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;async function U(e,t,r){let a=await M(e,t,r);if(a.protectedHeader.crit?.includes("b64")&&!1===a.protectedHeader.b64)throw new E("JWTs MUST NOT use unencoded payload");let i={payload:function(e,t,r={}){var a,i;let o,n;try{o=JSON.parse(l.decode(t))}catch{}if(!u(o))throw new E("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||$(e.typ)!==$(s)))throw new h('unexpected "typ" JWT header value',o,"typ","check_failed");let{requiredClaims:c=[],issuer:d,subject:y,audience:p,maxTokenAge:f}=r,S=[...c];for(let e of(void 0!==f&&S.push("iat"),void 0!==p&&S.push("aud"),void 0!==y&&S.push("sub"),void 0!==d&&S.push("iss"),new Set(S.reverse())))if(!(e in o))throw new h(`missing required "${e}" claim`,o,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(o.iss))throw new h('unexpected "iss" claim value',o,"iss","check_failed");if(y&&o.sub!==y)throw new h('unexpected "sub" claim value',o,"sub","check_failed");if(p&&(a=o.aud,i="string"==typeof p?[p]:p,"string"==typeof a?!i.includes(a):!(Array.isArray(a)&&i.some(Set.prototype.has.bind(new Set(a))))))throw new h('unexpected "aud" claim value',o,"aud","check_failed");switch(typeof r.clockTolerance){case"string":n=L(r.clockTolerance);break;case"number":n=r.clockTolerance;break;case"undefined":n=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:w}=r,g=Math.floor((w||new Date).getTime()/1e3);if((void 0!==o.iat||f)&&"number"!=typeof o.iat)throw new h('"iat" claim must be a number',o,"iat","invalid");if(void 0!==o.nbf){if("number"!=typeof o.nbf)throw new h('"nbf" claim must be a number',o,"nbf","invalid");if(o.nbf>g+n)throw new h('"nbf" claim timestamp check failed',o,"nbf","check_failed")}if(void 0!==o.exp){if("number"!=typeof o.exp)throw new h('"exp" claim must be a number',o,"exp","invalid");if(o.exp<=g-n)throw new m('"exp" claim timestamp check failed',o,"exp","check_failed")}if(f){let e=g-o.iat;if(e-n>("number"==typeof f?f:L(f)))throw new m('"iat" claim timestamp check failed (too far in the past)',o,"iat","check_failed");if(e<0-n)throw new h('"iat" claim timestamp check failed (it should be in the past)',o,"iat","check_failed")}return o}(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...i,key:a.key}:i}let B=(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},z=e=>({data:e,pos:0}),G=e=>{let t=e.data[e.pos++];if(128&t){let r=127&t,a=0;for(let t=0;t<r;t++)a=a<<8|e.data[e.pos++];return a}return t},F=(e,t=1)=>{if(t<=0)return;e.pos++;let r=G(e);e.pos+=r,t>1&&F(e,t-1)},V=(e,t,r)=>{if(e.data[e.pos++]!==t)throw Error(r)},X=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},q=async(e,t,r,a)=>{let i,o,n="spki"===e,s=()=>n?["verify"]:["sign"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=n?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":i={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[r]},o=s();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{let e=a.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new w("Invalid or unsupported key format")}o=n?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},o=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},o=s();break;default:throw new w('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,a?.extractable??!!n,o)},Y=(e,t)=>y(e.replace(t,"")),Q=(e,t,r)=>{let a=Y(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=r;return t?.startsWith?.("ECDH-ES")&&((i||={}).getNamedCurve=e=>{let t=z(e);return V(t,48,"Invalid SPKI structure"),G(t),V(t,48,"Expected algorithm identifier"),G(t),t.pos,(e=>{let t,r=(V(e,6,"Expected algorithm OID"),t=G(e),X(e,t));if(B(r,[43,101,110]))return"X25519";if(!B(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");V(e,6,"Expected curve OID");let a=G(e),i=X(e,a);for(let{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(B(i,t))return e;throw Error("Unsupported named curve")})(t)}),q("spki",a,t,i)};async function Z(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return Q(e,t,r)}async function ee(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');return((e,t,r)=>{var a,i,o;let n,s;try{let t,r,i;t=z(a=Y(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g)),V(t,48,"Invalid certificate structure"),G(t),V(t,48,"Invalid tbsCertificate structure"),G(t),160===a[t.pos]?F(t,6):F(t,5),r=t.pos,V(t,48,"Invalid SPKI structure"),i=G(t),n=a.subarray(r,r+i+(t.pos-r))}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return Q((i=function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}(n),o="PUBLIC KEY",s=(i.match(/.{1,64}/g)||[]).join("\n"),`-----BEGIN ${o}-----
|
|
2
|
-
${s}
|
|
3
|
-
-----END ${o}-----`),t,r)})(e,t,r)}async function et(e,t,r){let a;if(!u(e))throw TypeError("JWK must be an object");switch(t??=e.alg,a??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return p(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return D({...e,alg:t,ext:a});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return D({...e,ext:a});case"EC":case"OKP":return D({...e,alg:t,ext:a});default:throw new w('Unsupported "kty" (Key Type) Parameter value')}}function er(e){return async t=>{let r=function(e){if(!e)return null;let[t,r]=e.split(" ");return t&&r&&"bearer"===t.toLowerCase()&&r.trim()||null}(t.headers.get("authorization"));if(!r)return ea("Unauthorized: Missing or malformed Authorization header");try{await ei(r,e);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"}})}async function ei(e,t){var r;let a,{secret:i,...o}=t,n=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");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(l.decode(p(t)));if(!u(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}(e),s=o.algorithms?.[0]??("string"==typeof n.alg?n.alg:void 0);if(!s)throw Error("Missing JWT algorithm");let c=await eo(i,s),d=(a={},(r=o).algorithms&&(a.algorithms=r.algorithms),r.audience&&("string"==typeof r.audience?a.audience=r.audience:Array.isArray(r.audience)&&(a.audience=r.audience)),r.issuer&&(a.issuer=r.issuer),r.subject&&(a.subject=r.subject),void 0!==r.clockTolerance&&(a.clockTolerance=r.clockTolerance),void 0!==r.maxAge&&(a.maxTokenAge=r.maxAge),a),{payload:y}=await U(e,c,d);return y}async function eo(e,t){let r=e.trim();if(r.startsWith("{"))try{let e=JSON.parse(r);return await et(e,t)}catch{return new TextEncoder().encode(e)}return r.includes("BEGIN CERTIFICATE")?await ee(r,t):r.includes("BEGIN PUBLIC KEY")?await Z(r,t):new TextEncoder().encode(e)}function en(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:en(e),mimeType:t}}function ec(e,t){return{type:"audio",data:en(e),mimeType:t}}function el(e,t,r){return{type:"resource",resource:{uri:e,...void 0===r?{}:{mimeType:r},..."string"==typeof t?{text:t}:{blob:en(t)}}}}})(),i})());
|
|
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})());
|
package/dist/config.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 o="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var s=o[e]={exports:{}};return t[e](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var
|
|
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 o="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var s=o[e]={exports:{}};return t[e](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t,o)=>{var n=(t,o)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[o]:t[n]})};n(t,"get"),n(o,"value")},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{configSchema:()=>G,getResolvedCorsConfig:()=>E,getResolvedExperimentalConfig:()=>_,getResolvedHttpConfig:()=>A,getResolvedPathsConfig:()=>P,getResolvedStdioConfig:()=>R,getResolvedTemplateConfig:()=>M,getResolvedTypescriptConfig:()=>q});var e=r(4953),t=r.n(e);let o=["x-mcp-client-name","x-mcp-client-version","x-mcp-client-title","x-mcp-client-website-url","x-mcp-client-description"],s={origin:"*",methods:["GET","POST"],allowedHeaders:["Content-Type","Authorization","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name",...o],exposedHeaders:["Content-Type","Authorization","mcp-session-id"],credentials:!1,maxAge:86400},l=e.z.object({origin:e.z.union([e.z.string(),e.z.array(e.z.string()),e.z.boolean()]).default(s.origin),methods:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.methods]),allowedHeaders:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.allowedHeaders]),exposedHeaders:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.exposedHeaders]),credentials:e.z.boolean().default(s.credentials),maxAge:e.z.number().default(s.maxAge)}),i=l.parse({}),a=l.partial().transform(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),r={...i,...t};if(Array.isArray(r.allowedHeaders)){let e=new Set(r.allowedHeaders);for(let t of(e.add("mcp-session-id"),e.add("mcp-protocol-version"),e.add("mcp-method"),e.add("mcp-name"),o))e.add(t);r.allowedHeaders=Array.from(e)}if(Array.isArray(r.exposedHeaders)){let e=new Set(r.exposedHeaders);e.add("mcp-session-id"),r.exposedHeaders=Array.from(e)}return r}),p=e.z.object({port:e.z.number().default(3001),host:e.z.string().default("127.0.0.1"),bodySizeLimit:e.z.number().default(0xa00000),debug:e.z.boolean().default(!1),endpoint:e.z.string().default("/mcp"),maxSubscriptions:e.z.number().int().min(0).optional(),cors:a}),u=p.partial().transform(e=>{let t=p.parse({cors:{}}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),d=e.z.union([e.z.boolean(),u]);d.transform(e=>"boolean"==typeof e?e?{}:null:e).pipe(e.z.union([e.z.literal(null),u]));let c=e.z.object({debug:e.z.boolean().default(!1),silent:e.z.boolean().default(!1)}),f=c.partial().transform(e=>{let t=c.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),m=e.z.union([e.z.boolean(),f]).optional(),z=e.z.enum(["express","nextjs","nestjs","fastify","tanstack","hono","sveltekit","nuxt","react-router","astro"]),b=e.z.object({adapter:z.optional(),inferToolSchemas:e.z.boolean().optional()}),g=e.z.object({tools:e.z.union([e.z.boolean(),e.z.string()]).default(!0),prompts:e.z.union([e.z.boolean(),e.z.string()]).default(!0),resources:e.z.union([e.z.boolean(),e.z.string()]).default(!0),skills:e.z.union([e.z.boolean(),e.z.string()]).default(!0)}),y=g.partial().transform(e=>{let t=g.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),j="src/tools",v="src/prompts",x="src/resources",h="src/skills",O=t().function().args(t().any()).returns(t().any()).optional(),k=e.z.object({name:e.z.string().default("xmcp server"),description:e.z.string().default("This MCP server was bootstrapped with xmcp."),icons:e.z.array(e.z.object({src:e.z.string(),mimeType:e.z.string().optional(),sizes:e.z.array(e.z.string()).optional(),theme:e.z.enum(["light","dark"]).optional()})).optional(),instructions:e.z.string().optional(),homePage:e.z.string().optional()}),H=k.partial().transform(e=>{let t=k.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),S=e.z.object({skipTypeCheck:e.z.boolean().default(!1)}),w=S.partial().transform(e=>{let t=S.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),C=e.z.object({names:e.z.array(e.z.string().min(1)).optional(),tags:e.z.array(e.z.string().min(1)).optional()}).strict(),T=e.z.object({include:C.optional(),exclude:C.optional()}).strict();function A(e){if("boolean"==typeof e){if(!e)return null;let t=d.parse({});return"object"!=typeof t||null===t?null:t}if("object"==typeof e&&null!==e){let t=d.parse(e);return"object"!=typeof t||null===t?null:t}return null}function E(e){return a.parse(e?.cors??{})}function P(e){let t=e?.paths;if(!t)return{tools:j,prompts:v,resources:x,skills:h};let o={tools:j,prompts:v,resources:x,skills:h};return"boolean"==typeof t.tools?o.tools=t.tools?j:null:"string"==typeof t.tools&&(o.tools=t.tools),"boolean"==typeof t.prompts?o.prompts=t.prompts?v:null:"string"==typeof t.prompts&&(o.prompts=t.prompts),"boolean"==typeof t.resources?o.resources=t.resources?x:null:"string"==typeof t.resources&&(o.resources=t.resources),"boolean"==typeof t.skills?o.skills=t.skills?h:null:"string"==typeof t.skills&&(o.skills=t.skills),o}function R(e){let t=e?.stdio;if("boolean"==typeof t){if(!t)return null;let e=m.parse({});return"object"!=typeof e||null===e?null:e}if(t){let e=m.parse(t);return"object"!=typeof e||null===e?null:e}let o=m.parse({});return"object"!=typeof o||null===o?null:o}function M(e){let t=e?.template;return H.parse(t??{})}function _(e){let t=e?.experimental;return{adapter:t?.adapter}}function q(e){let t=e?.typescript;return w.parse(t??{})}let G=e.z.object({stdio:m.optional(),http:d.optional(),experimental:b.optional(),paths:y.optional(),bundler:O.optional(),template:H.optional(),typescript:w.optional(),observability:e.z.object({enabled:e.z.boolean()}).optional(),components:T.optional()})})(),n})());
|
package/dist/host-bridge.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 s=t();for(var o in s)("object"==typeof exports?exports:e)[o]=s[o]}}(this,()=>(()=>{"use strict";var e={};e.d=(t,s)=>{for(var
|
|
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 s=t();for(var o in s)("object"==typeof exports?exports:e)[o]=s[o]}}(this,()=>(()=>{"use strict";var e={};e.d=(t,s,o)=>{var i=(s,o)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,[o]:s[i]})};i(s,"get"),i(o,"value")},e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var t={};e.r(t),e.d(t,{HOST_CONTEXT_CHANGED_METHOD:()=>c,INITIALIZED_METHOD:()=>i,INITIALIZE_METHOD:()=>o,LOG_MESSAGE_METHOD:()=>d,MCP_APPS_PROTOCOL_VERSION:()=>s,OPEN_LINK_METHOD:()=>n,REQUEST_DISPLAY_MODE_METHOD:()=>r,RESOURCES_READ_METHOD:()=>u,SIZE_CHANGED_METHOD:()=>p,UI_MESSAGE_METHOD:()=>l,UPDATE_MODEL_CONTEXT_METHOD:()=>a,createMcpHostBridge:()=>h});let s="2026-01-26",o="ui/initialize",i="ui/notifications/initialized",r="ui/request-display-mode",n="ui/open-link",a="ui/update-model-context",l="ui/message",d="notifications/message",u="resources/read",c="ui/notifications/host-context-changed",p="ui/notifications/size-changed";function C(e){return!!e&&"object"==typeof e}function f(e,t){return e instanceof Error&&e.message?e.message:t}function h(e={}){let t=e.targetWindow??("u"<typeof window?null:window),s=e.requestTimeoutMs??15e3,o=e.connectionTimeoutMs??2e3,i=100,m=!1,E=!1,b={isConnected:!!t&&t.parent!==t,hostContext:null,hostCapabilities:null},y=new Set,M=new Map,g=e=>{if(e.isConnected!==b.isConnected||e.hostContext!==b.hostContext||e.hostCapabilities!==b.hostCapabilities)for(let t of(b=e,y))t(b)},T=e=>{var t,s;let o;g({isConnected:!0,hostContext:e.hostContext?(t=b.hostContext,s=e.hostContext,o={...t??{},...s},(t?.safeAreaInsets||s.safeAreaInsets)&&(o.safeAreaInsets={...t?.safeAreaInsets??{},...s.safeAreaInsets??{}}),(t?.containerDimensions||s.containerDimensions)&&(o.containerDimensions={...t?.containerDimensions??{},...s.containerDimensions??{}}),(t?.styles||s.styles)&&(o.styles={...t?.styles??{},...s.styles??{},variables:t?.styles?.variables||s.styles?.variables?{...t?.styles?.variables??{},...s.styles?.variables??{}}:void 0,css:t?.styles?.css||s.styles?.css?{...t?.styles?.css??{},...s.styles?.css??{}}:void 0}),o):b.hostContext,hostCapabilities:e.hostCapabilities?{...b.hostCapabilities??{},...e.hostCapabilities}:b.hostCapabilities})},O=e=>{if(!t||e.source!==t.parent||!C(e.data))return;E=!0,b.isConnected||g({...b,isConnected:!0});let s=e.data;if("id"in s&&null!=s.id&&"number"==typeof s.id){let e=M.get(s.id);e&&(clearTimeout(e.timeoutId),M.delete(s.id),C(s.error)?e.reject(Error("string"==typeof s.error.message?s.error.message:"MCP request failed")):e.resolve(s.result))}1===s.id&&C(s.result)&&T({hostContext:C(s.result.hostContext)?s.result.hostContext:void 0,hostCapabilities:C(s.result.hostCapabilities)?s.result.hostCapabilities:void 0}),s.method===c&&C(s.params)&&T({hostContext:s.params}),"ui/hostContextChanged"===s.method&&C(s.params)&&C(s.params.hostContext)&&T({hostContext:s.params.hostContext})};t&&(t.addEventListener("message",O),t.parent!==t&&setTimeout(()=>{m||E||b.hostContext||g({...b,isConnected:!1})},o));let _=()=>{if(m)throw Error("MCP host bridge has been disposed");if(!t)throw Error("MCP host bridge requires a browser window");return t},w=(e,t)=>{_().parent.postMessage({jsonrpc:"2.0",method:e,params:t},"*")},x=(e,t={})=>{let o=_();return new Promise((r,n)=>{let a=i++,l=setTimeout(()=>{M.has(a)&&(M.delete(a),n(Error(`MCP request timed out: ${e}`)))},s);M.set(a,{resolve:r,reject:n,timeoutId:l}),o.parent.postMessage({jsonrpc:"2.0",id:a,method:e,params:t},"*")})},v=async(e,t)=>{let s;for(let o of e)try{return await x(o,t)}catch(t){s=t;let e=f(t,"MCP request failed");if(!/method not found|unknown method/i.test(e))throw t}throw s instanceof Error?s:Error("MCP request failed")};return{callTool:(e,t)=>x("tools/call",{name:e,arguments:t??{}}),requestDisplayMode:e=>v([r,"ui/requestDisplayMode"],{mode:e}),async openLink(e){try{await v([n,"ui/openLink"],{url:e})}catch(s){if(!b.isConnected||!t)return void await (async e=>{if(t?.open)return void t.open(e,"_blank","noopener,noreferrer");throw Error("Unable to open link without a browser window")})(e);throw Error(f(s,"Failed to open link"))}},readResource:e=>x(u,{uri:e}),sendMessage:e=>x(l,e),updateModelContext:e=>x(a,e),async logMessage(e){w(d,e)},async notifySizeChanged(e){w(p,e)},getState:()=>b,getHostContext:()=>b.hostContext,getHostCapabilities:()=>b.hostCapabilities,isConnected:()=>b.isConnected,subscribe:e=>(y.add(e),()=>{y.delete(e)}),dispose(){if(!m){for(let[e,s]of(m=!0,t&&t.removeEventListener("message",O),M.entries()))clearTimeout(s.timeoutId),s.reject(Error("MCP host bridge has been disposed")),M.delete(e);y.clear()}}}}return t})());
|