@kya-os/mcp-i 1.7.13 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/225.js +1 -0
  2. package/dist/227.js +1 -0
  3. package/dist/242.js +1 -0
  4. package/dist/283.js +1 -0
  5. package/dist/295.js +1 -1
  6. package/dist/354.js +1 -0
  7. package/dist/361.js +1 -0
  8. package/dist/452.js +1 -0
  9. package/dist/533.js +1 -0
  10. package/dist/622.js +1 -0
  11. package/dist/65.js +1 -0
  12. package/dist/843.js +1 -0
  13. package/dist/861.js +1 -0
  14. package/dist/866.js +1 -1
  15. package/dist/914.js +1 -0
  16. package/dist/95.js +1 -0
  17. package/dist/{941.js → 966.js} +1 -1
  18. package/dist/providers/node-providers.d.ts +1 -1
  19. package/dist/providers/node-providers.js +2 -2
  20. package/dist/runtime/adapter-express.js +6 -6
  21. package/dist/runtime/adapter-nextjs.js +6 -6
  22. package/dist/runtime/auth-handshake.d.ts +4 -159
  23. package/dist/runtime/auth-handshake.js +8 -249
  24. package/dist/runtime/http.js +6 -6
  25. package/dist/runtime/mcpi-runtime.d.ts +4 -0
  26. package/dist/runtime/mcpi-runtime.js +58 -43
  27. package/dist/runtime/outbound-delegation.d.ts +34 -0
  28. package/dist/runtime/outbound-delegation.js +134 -0
  29. package/dist/runtime/proof.d.ts +13 -88
  30. package/dist/runtime/proof.js +11 -225
  31. package/dist/runtime/request-context.d.ts +41 -0
  32. package/dist/runtime/request-context.js +48 -0
  33. package/dist/runtime/session.d.ts +13 -104
  34. package/dist/runtime/session.js +31 -267
  35. package/dist/runtime/stdio.js +6 -6
  36. package/dist/runtime/utils/tools.js +17 -3
  37. package/dist/runtime/verifier-middleware.js +4 -4
  38. package/package.json +19 -19
  39. package/dist/207.js +0 -1
  40. package/dist/25.js +0 -1
  41. package/dist/360.js +0 -1
  42. package/dist/387.js +0 -1
  43. package/dist/406.js +0 -1
  44. package/dist/448.js +0 -1
  45. package/dist/478.js +0 -1
  46. package/dist/575.js +0 -1
  47. package/dist/67.js +0 -1
  48. package/dist/743.js +0 -1
  49. package/dist/784.js +0 -1
  50. package/dist/844.js +0 -1
  51. package/dist/936.js +0 -1
  52. package/dist/988.js +0 -1
@@ -1,7 +1,7 @@
1
- (()=>{var e={202:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdpTokenResolver=void 0,t.IdpTokenResolver=class{config;constructor(e){this.config={tokenStorage:e.tokenStorage,oauthService:e.oauthService,logger:e.logger||(()=>{})}}async resolveTokenFromDid(e,t,r){const o=await this.resolveTokenDataFromDid(e,t,r);return o?.access_token??null}async resolveTokenDataFromDid(e,t,r){const o=await this.config.tokenStorage.getToken(e,t,r);if(!o)return this.config.logger("[IdpTokenResolver] Token not found",{userDid:e.substring(0,20)+"...",provider:t,scopes:r}),null;const n=Date.now();if(o.expires_at<n){if(this.config.logger("[IdpTokenResolver] Token expired, attempting refresh",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(o.expires_at).toISOString(),hasRefreshToken:!!o.refresh_token}),o.refresh_token){const n=await this.config.oauthService.refreshToken(t,o.refresh_token);if(n){const i={...n,tokenUsage:o.tokenUsage,tokenHeader:o.tokenHeader,cookieFormat:o.cookieFormat,apiHeaders:o.apiHeaders};return await this.config.tokenStorage.storeToken(e,t,r,i),this.config.logger("[IdpTokenResolver] Token refreshed successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(n.expires_at).toISOString()}),i}return this.config.logger("[IdpTokenResolver] Token refresh failed",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token expired and no refresh token",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token resolved successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(o.expires_at).toISOString(),tokenUsage:o.tokenUsage}),o}}},218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(60234);class n extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,o.resolveUrl)(e,t,r),this.missingSchema=(0,o.normalizeId)((0,o.getFullPath)(e,this.missingRef))}}t.default=n},1074:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const o=r(36556),n=r(94614),i=r(93716),s=r(57747);function a(e){const{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,o._`${n.parentData}[${n.parentDataProperty}]`))}function c(e,t,r){if(void 0===r)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,o.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:n,schema:i,parentSchema:s,it:a}=e,d=t.macro.call(a.self,i,s,a),l=c(r,n,d);!1!==a.opts.validateSchema&&a.self.validateSchema(d,!0);const u=r.name("valid");e.subschema({schema:d,schemaPath:o.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),e.pass(u,()=>e.error(!0))},t.funcKeywordCode=function(e,t){var r;const{gen:d,keyword:l,schema:u,parentSchema:h,$data:f,it:p}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(p,t);const m=!f&&t.compile?t.compile.call(p.self,u,h,p):t.validate,g=c(d,l,m),y=d.let("valid");function v(r=(t.async?o._`await `:o.nil)){const s=p.opts.passContext?n.default.this:n.default.self,a=!("compile"in t&&!f||!1===t.schema);d.assign(y,o._`${r}${(0,i.callValidateCode)(e,g,s,a)}`,t.modifying)}function w(e){var r;d.if((0,o.not)(null!==(r=t.valid)&&void 0!==r?r:y),e)}e.block$data(y,function(){if(!1===t.errors)v(),t.modifying&&a(e),w(()=>e.error());else{const r=t.async?function(){const e=d.let("ruleErrs",null);return d.try(()=>v(o._`await `),t=>d.assign(y,!1).if(o._`${t} instanceof ${p.ValidationError}`,()=>d.assign(e,o._`${t}.errors`),()=>d.throw(t))),e}():function(){const e=o._`${g}.errors`;return d.assign(e,null),v(o.nil),e}();t.modifying&&a(e),w(()=>function(e,t){const{gen:r}=e;r.if(o._`Array.isArray(${t})`,()=>{r.assign(n.default.vErrors,o._`${n.default.vErrors} === null ? ${t} : ${n.default.vErrors}.concat(${t})`).assign(n.default.errors,o._`${n.default.vErrors}.length`),(0,s.extendErrors)(e)},()=>e.error())}(e,r))}}),e.ok(null!==(r=t.valid)&&void 0!==r?r:y)},t.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},t.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:o},n,i){if(Array.isArray(n.keyword)?!n.keyword.includes(i):n.keyword!==i)throw new Error("ajv implementation error");const s=n.dependencies;if(null==s?void 0:s.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(n.validateSchema&&!n.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},2882:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const o=r(57747),n=r(36556),i=r(94614),s={message:"boolean schema is false"};function a(e,t){const{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,o.reportError)(i,s,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:o}=e;!1===r?a(e,!1):"object"==typeof r&&!0===r.$async?t.return(i.default.data):(t.assign(n._`${o}.errors`,null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),a(e)):r.var(t,!0)}},4901:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionServiceError=t.DelegationRequiredError=void 0;class r extends Error{toolName;requiredScopes;consentUrl;resumeToken;interceptedCall;constructor(e,t,r,o,n){super(`Delegation required for tool "${e}"`),this.toolName=e,this.requiredScopes=t,this.consentUrl=r,this.name="DelegationRequiredError",this.interceptedCall=o,this.resumeToken=n}}t.DelegationRequiredError=r;class o extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ToolProtectionServiceError"}}t.ToolProtectionServiceError=o},5019:(e,t,r)=>{"use strict";const{normalizeIPv6:o,removeDotSegments:n,recomposeAuthority:i,normalizeComponentEncoding:s,isIPv4:a,nonSimpleDomain:c}=r(96214),{SCHEMES:d,getSchemeHandler:l}=r(99147);function u(e,t,r,o){const i={};return o||(e=p(h(e,r),r),t=p(h(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=n(t.path||""),i.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=n(t.path||""),i.query=t.query):(t.path?("/"===t.path[0]?i.path=n(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path:i.path="/"+t.path,i.path=n(i.path)),i.query=t.query):(i.path=e.path,void 0!==t.query?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function h(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},t),s=[],a=l(o.scheme||r.scheme);a&&a.serialize&&a.serialize(r,o),void 0!==r.path&&(o.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==o.reference&&r.scheme&&s.push(r.scheme,":");const c=i(r);if(void 0!==c&&("suffix"!==o.reference&&s.push("//"),s.push(c),r.path&&"/"!==r.path[0]&&s.push("/")),void 0!==r.path){let e=r.path;o.absolutePath||a&&a.absolutePath||(e=n(e)),void 0===c&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),s.push(e)}return void 0!==r.query&&s.push("?",r.query),void 0!==r.fragment&&s.push("#",r.fragment),s.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function p(e,t){const r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let i=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const s=e.match(f);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(!1===a(n.host)){const e=o(n.host);n.host=e.host.toLowerCase(),i=e.isIPV6}else i=!0;void 0!==n.scheme||void 0!==n.userinfo||void 0!==n.host||void 0!==n.port||void 0!==n.query||n.path?void 0===n.scheme?n.reference="relative":void 0===n.fragment?n.reference="absolute":n.reference="uri":n.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");const t=l(r.scheme||n.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&n.host&&(r.domainHost||t&&t.domainHost)&&!1===i&&c(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(e){n.error=n.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==n.scheme&&(n.scheme=unescape(n.scheme)),void 0!==n.host&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),t&&t.parse&&t.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}const m={SCHEMES:d,normalize:function(e,t){return"string"==typeof e?e=h(p(e,t),t):"object"==typeof e&&(e=p(h(e,t),t)),e},resolve:function(e,t,r){const o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=u(p(e,o),p(t,o),o,!0);return o.skipEscape=!0,h(n,o)},resolveComponent:u,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=h(s(p(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=h(s(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=h(s(p(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=h(s(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:h,parse:p};e.exports=m,e.exports.default=m,e.exports.fastUri=m},5861:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(86464),n=r(25140),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",o.default,n.default];t.default=i},6447:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i=r(93716),s=r(28440),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>o.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>o._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:a}=r;o.items=!0,(0,n.alwaysValidSchema)(o,t)||(a?(0,s.validateAdditionalItems)(e,a):e.ok((0,i.validateArray)(e)))}};t.default=a},7318:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStatusListStorage=void 0,t.MemoryStatusListStorage=class{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}},8181:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(5861),n=r(64057),i=r(93591),s=r(29961),a=r(46780),c=[o.default,n.default,(0,i.default)(),s.default,a.metadataVocabulary,a.contentVocabulary];t.default=c},8762:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i=r(56935),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>o._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:s,schemaCode:a,schema:c}=e;s||c&&"object"==typeof c?e.fail$data(o._`!${(0,n.useFunc)(t,i.default)}(${r}, ${a})`):e.fail(o._`${c} !== ${r}`)}};t.default=s},9198:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const o=r(36556),n=r(29645),i=r(94614),s=r(60234),a=r(28512),c=r(96889);class d{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,s.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function l(e){const t=h.call(this,e);if(t)return t;const r=(0,s.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:a,lines:d}=this.opts.code,{ownProperties:l}=this.opts,u=new o.CodeGen(this.scope,{es5:a,lines:d,ownProperties:l});let f;e.$async&&(f=u.scopeValue("Error",{ref:n.default,code:o._`require("ajv/dist/runtime/validation_error").default`}));const p=u.scopeName("validate");e.validateName=p;const m={gen:u,allErrors:this.opts.allErrors,data:i.default.data,parentData:i.default.parentData,parentDataProperty:i.default.parentDataProperty,dataNames:[i.default.data],dataPathArr:[o.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:u.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,o.stringify)(e.schema)}:{ref:e.schema}),validateName:p,ValidationError:f,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:o.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:o._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(e),(0,c.validateFunctionCode)(m),u.optimize(this.opts.code.optimize);const t=u.toString();g=`${u.scopeRefs(i.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,e));const r=new Function(`${i.default.self}`,`${i.default.scope}`,g)(this,this.scope.get());if(this.scope.value(p,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:p,validateCode:t,scopeValues:u._values}),this.opts.unevaluated){const{props:e,items:t}=m;r.evaluated={props:e instanceof o.Name?void 0:e,items:t instanceof o.Name?void 0:t,dynamicProps:e instanceof o.Name,dynamicItems:t instanceof o.Name},r.source&&(r.source.evaluated=(0,o.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error("Error compiling schema, function code:",g),t}finally{this._compilations.delete(e)}}function u(e){return(0,s.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:l.call(this,e)}function h(e){for(const t of this._compilations)if(f(t,e))return t}function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||m.call(this,e,t)}function m(e,t){const r=this.opts.uriResolver.parse(t),o=(0,s._getFullPath)(this.opts.uriResolver,r);let n=(0,s.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return y.call(this,r,e);const i=(0,s.normalizeId)(o),a=this.refs[i]||this.schemas[i];if("string"==typeof a){const t=m.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return y.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||l.call(this,a),i===(0,s.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,s.resolveUrl)(this.opts.uriResolver,n,o)),new d({schema:t,schemaId:r,root:e,baseId:n})}return y.call(this,r,a)}}t.SchemaEnv=d,t.compileSchema=l,t.resolveRef=function(e,t,r){var o;r=(0,s.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let i=p.call(this,e,r);if(void 0===i){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:s}=this.opts;n&&(i=new d({schema:n,schemaId:s,root:e,baseId:t}))}return void 0!==i?e.refs[r]=u.call(this,i):void 0},t.getCompilingSchema=h,t.resolveSchema=m;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function y(e,{baseId:t,schema:r,root:o}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,a.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!g.has(o)&&n&&(t=(0,s.resolveUrl)(this.opts.uriResolver,t,n))}let i;if("boolean"!=typeof r&&r.$ref&&!(0,a.schemaHasRulesButRef)(r,this.RULES)){const e=(0,s.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=m.call(this,o,e)}const{schemaId:c}=this.opts;return i=i||new d({schema:r,schemaId:c,root:o,baseId:t}),i.schema!==i.root.schema?i:void 0}},9240:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(93716),n=r(36556),i=r(28512),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>n.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>n._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:s,data:a,$data:c,it:d}=e,{opts:l}=d;if(!c&&0===r.length)return;const u=r.length>=l.loopRequired;if(d.allErrors?function(){if(u||c)e.block$data(n.nil,h);else for(const t of r)(0,o.checkReportMissingProp)(e,t)}():function(){const i=t.let("missing");if(u||c){const r=t.let("valid",!0);e.block$data(r,()=>function(r,i){e.setParams({missingProperty:r}),t.forOf(r,s,()=>{t.assign(i,(0,o.propertyInData)(t,a,r,l.ownProperties)),t.if((0,n.not)(i),()=>{e.error(),t.break()})},n.nil)}(i,r)),e.ok(r)}else t.if((0,o.checkMissingProp)(e,r,i)),(0,o.reportMissingProp)(e,i),t.else()}(),l.strictRequired){const t=e.parentSchema.properties,{definedProperties:o}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!o.has(e)){const t=`required property "${e}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,i.checkStrictMode)(d,t,d.opts.strictRequired)}}function h(){t.forOf("prop",s,r=>{e.setParams({missingProperty:r}),t.if((0,o.noPropertyInData)(t,a,r,l.ownProperties),()=>e.error())})}}};t.default=s},9249:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionService=void 0;const o=r(85601);t.ToolProtectionService=class{config;cache;constructor(e,t){this.config=e,this.cache=t}getProjectId(){return this.config.projectId}async getStaleCache(e){if(!1===this.config.allowStaleCache)return null;if(!(this.cache instanceof o.InMemoryToolProtectionCache))return null;const t=this.cache.getStale(e);if(!t)return null;const r=this.cache.getExpiresAt(e);if(!r)return null;const n=Date.now(),i=this.config.maxStaleCacheAge??864e5;return n>r&&n-r<=i?(this.config.debug&&console.error("[ToolProtectionService] Using stale cache",{cacheKey:e,expiredAt:new Date(r).toISOString(),staleAgeMs:n-r,maxStaleAgeMs:i}),t):null}async getToolProtectionConfig(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`,r=await this.cache.get(t);if(r){const o=this.config.cacheTtl??3e5,n=new Date(Date.now()+o).toISOString();return this.config.debug&&console.error("[ToolProtectionService] Cache hit",{source:"cache",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",toolCount:Object.keys(r.toolProtections).length,protectedTools:Object.entries(r.toolProtections).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),cacheTtlMs:o,cachedUntil:n}),r}this.config.debug&&console.error("[ToolProtectionService] Cache miss, fetching from API",{source:"api-fetch-start",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",apiUrl:this.config.apiUrl,endpoint:this.config.projectId?`/api/v1/bouncer/projects/${this.config.projectId}/config`:`/api/v1/bouncer/config?agent_did=${e}`});try{const r=await this.fetchFromApi(e);this.config.debug&&console.error("[ToolProtectionService] API response received",{source:"api-fetch-complete",agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",responseKeys:Object.keys(r),dataKeys:r.data?Object.keys(r.data):[],rawConfig:r.data?.config||null,rawConfigToolProtection:r.data?.config?.toolProtection||null,responseMetadata:r.metadata||null});const o=this.parseToolProtectionsFromResponse(r);this.config.debug&&Object.keys(o).length>0&&console.error("[ToolProtectionService] Parsed tool protections from merged config",{toolCount:Object.keys(o).length,tools:Object.keys(o)});const n={};if(this.config.localConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.localConfig.toolProtections)){if(!t||"object"!=typeof t||0===Object.keys(t).length){this.config.debug&&console.error("[ToolProtectionService] Skipping empty/invalid local config entry",{tool:e});continue}const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[],...t.oauthProvider&&{oauthProvider:t.oauthProvider},...t.riskLevel&&{riskLevel:t.riskLevel},...t.authorization&&{authorization:t.authorization}};n[e]=r,this.config.debug&&console.error("[ToolProtectionService] Applied local config as base",{tool:e,localConfig:r})}for(const[e,t]of Object.entries(o))n[e]=t,this.config.debug&&this.config.localConfig?.toolProtections?.[e]&&console.error("[ToolProtectionService] Remote config overrides local config",{tool:e,remoteConfig:t});const i={toolProtections:n},s=this.config.cacheTtl??3e5,a=new Date(Date.now()+s);return await this.cache.set(t,i,s),console.error("[ToolProtectionService] Config loaded from API",{source:"api",toolCount:Object.keys(n).length,protectedTools:Object.entries(n).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",cacheTtlMs:s,cacheExpiresAt:a.toISOString()}),this.config.debug&&console.error("[ToolProtectionService] API fetch successful, config cached",{source:"cache-write",agentDid:e.slice(0,20)+"...",cacheKey:t,toolCount:Object.keys(n).length,tools:Object.entries(n).map(([e,t])=>({name:e,requiresDelegation:t.requiresDelegation,scopeCount:(t.requiredScopes||[]).length})),ttlMs:s,ttlMinutes:Math.round(s/6e4),expiresAt:a.toISOString(),expiresIn:`${Math.round(s/1e3)}s`}),i}catch(r){const o=r instanceof Error?r.message:String(r);if(o.includes("API key is missing or empty"))throw r;if(o.includes("projectId is required"))throw r;if(o.includes("Failed to fetch bouncer config:")&&(429!==r.status||!this.config.offlineFallbackConfig))throw r;if(o.includes("Failed to parse API response:"))throw r;if(o.includes("API returned success: false"))throw r;this.config.debug&&console.error("[ToolProtectionService] API fetch failed",{agentDid:e.slice(0,20)+"...",error:o});const n=await this.getStaleCache(t);if(n)return console.warn("[ToolProtectionService] API fetch failed, using stale cache",{agentDid:e.slice(0,20)+"...",error:o,cacheKey:t}),n;if(this.config.offlineFallbackConfig){console.warn("[ToolProtectionService] API fetch failed, using offline fallback config",{agentDid:e.slice(0,20)+"...",error:o});const r=this.config.cacheTtl??3e5;return await this.cache.set(t,this.config.offlineFallbackConfig,r),this.config.offlineFallbackConfig}if("deny-all"===(this.config.failSafeBehavior??"deny-all")){console.error("[ToolProtectionService] API fetch failed, no offline fallback, failing closed (deny-all)",{agentDid:e.slice(0,20)+"...",error:o,cacheKey:t});const r={toolProtections:{"*":{requiresDelegation:!0,requiredScopes:[]}}},n=this.config.cacheTtl??3e5;return await this.cache.set(t,r,n),r}{console.warn("[ToolProtectionService] API fetch failed, no offline fallback, failing open (allow-all)",{agentDid:e.slice(0,20)+"...",error:o,cacheKey:t});const r={toolProtections:{}},n=this.config.cacheTtl??3e5;return await this.cache.set(t,r,n),r}}}async checkToolProtection(e,t){const r=await this.getToolProtectionConfig(t);let o=r.toolProtections[e];return!o&&r.toolProtections["*"]&&(o=r.toolProtections["*"]),(this.config.debug||!o||o.requiresDelegation)&&console.error("[ToolProtectionService] Protection check",{tool:e,agentDid:t.slice(0,20)+"...",found:!!o,isWildcard:o===r.toolProtections["*"],requiresDelegation:o?.requiresDelegation??!1,availableTools:Object.keys(r.toolProtections)}),o&&o.requiresDelegation?o:null}async fetchFromApi(e,t){let r,o=!1;if(!this.config.projectId){const e=new Error("[ToolProtectionService] projectId is required for user-scoped delegation. Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). Please configure AGENTSHIELD_PROJECT_ID environment variable.");throw console.error("[ToolProtectionService]",e.message),e}if(r=`${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/config`,o=!0,t?.bypassCDNCache){const e=r.includes("?")?"&":"?";r=`${r}${e}_t=${Date.now()}`}const n=this.config.apiKey?(()=>{const e=this.config.apiKey.split("_");return e.length>=2?`${e[0]}_${e[1]}...`:`${this.config.apiKey.substring(0,8)}...`})():"(empty)",i=this.config.apiKey?.length||0;if(this.config.debug&&console.error("[ToolProtectionService] Fetching from API:",r,{method:"projects/{projectId}/config (merged)",projectId:this.config.projectId||"none",apiKeyPresent:!!this.config.apiKey,apiKeyLength:i,apiKeyMasked:n}),!this.config.apiKey||""===this.config.apiKey.trim()){const e="API key is missing or empty";throw this.config.debug&&console.error("[ToolProtectionService]",e,{apiKeyPresent:!!this.config.apiKey,apiKeyLength:i}),new Error(`ToolProtectionService: ${e}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`)}const s={"Content-Type":"application/json"};s["X-API-Key"]=this.config.apiKey,this.config.projectId&&(s["X-Project-Id"]=this.config.projectId),t?.bypassCDNCache&&(s["Cache-Control"]="no-cache, no-store, must-revalidate",s.Pragma="no-cache");const a=await fetch(r,{method:"GET",headers:s});if(!a.ok){const e=await a.text().catch(()=>"Unknown error"),t=new Error(`Failed to fetch bouncer config: ${a.status} ${a.statusText} - ${e}`);throw t.status=a.status,t}let c;try{c=await a.json()}catch(e){throw new Error(`Failed to parse API response: ${e instanceof Error?e.message:String(e)}`)}if(!c.success)throw new Error("API returned success: false");return c}parseToolProtectionsFromResponse(e){const t={},r=e.data.config?.toolProtection?.tools;if(!r)return t;for(const[e,o]of Object.entries(r)){const r=o.requiresDelegation??o.requires_delegation??!1,n=o.requiredScopes??o.required_scopes??o.scopes??[],i=o.oauthProvider??o.oauth_provider??void 0,s=o.riskLevel??o.risk_level??void 0,a=s&&["low","medium","high","critical"].includes(s)?s:void 0,c=o.authorization;t[e]={requiresDelegation:r,requiredScopes:n,...i&&{oauthProvider:i},...a&&{riskLevel:a},...c&&{authorization:c}}}return t}async clearCache(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;this.config.debug&&console.error("[ToolProtectionService] Clearing cache",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t)}async clearAndRefresh(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;console.error("[ToolProtectionService] clearAndRefresh starting",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t),console.error("[ToolProtectionService] Cache entry deleted",{cacheKey:t});try{const r=await this.fetchFromApi(e,{bypassCDNCache:!0}),o=this.parseToolProtectionsFromResponse(r),n={};if(this.config.localConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.localConfig.toolProtections))if(t&&"object"==typeof t&&Object.keys(t).length>0){const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[],...t.oauthProvider&&{oauthProvider:t.oauthProvider},...t.riskLevel&&{riskLevel:t.riskLevel},...t.authorization&&{authorization:t.authorization}};n[e]=r}for(const[e,t]of Object.entries(o))n[e]=t;const i={toolProtections:n},s=this.config.cacheTtl??3e5;return await this.cache.set(t,i,s),console.error("[ToolProtectionService] Fresh config fetched and cached",{cacheKey:t,toolCount:Object.keys(n).length,protectedTools:Object.entries(n).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),source:"api"}),{config:i,cacheKey:t,source:"api"}}catch(e){return console.warn("[ToolProtectionService] API fetch failed during refresh, using offline fallback",{error:e instanceof Error?e.message:String(e),cacheKey:t}),{config:this.config.offlineFallbackConfig||{toolProtections:{}},cacheKey:t,source:"fallback"}}}}},10494:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(52058),n=r(17122),i=r(36556),s=new i.Name("fullFormats"),a=new i.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return d(e,t,o.fullFormats,s),e;const[r,i]="fast"===t.mode?[o.fastFormats,a]:[o.fullFormats,s];return d(e,t.formats||o.formatNames,r,i),t.keywords&&(0,n.default)(e),e};function d(e,t,r,o){var n,s;null!==(n=(s=e.opts.code).formats)&&void 0!==n||(s.formats=i._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}c.get=(e,t="full")=>{const r=("fast"===t?o.fastFormats:o.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},10985:(e,t,r)=>{"use strict";r.d(t,{S:()=>n});var o="$";function n(e,t){var r="",n=t&&t.include,i=t&&t.exclude;i&&"string"==typeof i&&(i=[i]),n&&n.sort();var s=new WeakMap,a=t&&t.allowCircular,c=t&&t.filterUndefined,d=t&&t.undefinedInArrayToNull;return function e(t,l){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(h=s.get(t))&&l.startsWith(h)){if(!a)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}s.set(t,l),r+="[";var u=!1;t.forEach(function(t,o){u&&(r+=","),u=!0,d&&void 0===t&&(t=null),e(t,l+"["+o+"]")}),r+="]"}else{var h;if(void 0!==(h=s.get(t))&&l.startsWith(h)){if(!a)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}s.set(t,l),r+="{";var f=!1,p=function(o){i&&i.includes(o)||(f&&(r+=","),f=!0,r+=JSON.stringify(o),r+=":",e(t[o],l+"."+o))};if(l===o&&n)n.forEach(function(e){t.hasOwnProperty(e)&&p(e)});else{var m=Object.keys(t);c&&(m=m.filter(function(e){return void 0!==t[e]})),m.sort(),m.forEach(function(e){p(e)})}r+="}"}}(e,o),r}},11175:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class o extends r{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=o;class n extends r{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof o&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function i(e,...t){const r=[e[0]];let o=0;for(;o<t.length;)c(r,t[o]),r.push(e[++o]);return new n(r)}t._Code=n,t.nil=new n(""),t._=i;const s=new n("+");function a(e,...t){const r=[l(e[0])];let o=0;for(;o<t.length;)r.push(s),c(r,t[o]),r.push(s,l(e[++o]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===s){const r=d(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function c(e,t){var r;t instanceof n?e.push(...t._items):t instanceof o?e.push(t):e.push("number"==typeof(r=t)||"boolean"==typeof r||null===r?r:l(Array.isArray(r)?r.join(","):r))}function d(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof o||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof o?void 0:`"${e}${t.slice(1)}`}function l(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=a,t.addCodeArg=c,t.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},t.stringify=function(e){return new n(l(e))},t.safeStringify=l,t.getProperty=function(e){return"string"==typeof e&&t.IDENTIFIER.test(e)?new n(`.${e}`):i`[${e}]`},t.getEsmExportName=function(e){if("string"==typeof e&&t.IDENTIFIER.test(e))return new n(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},t.regexpCode=function(e){return new n(e.toString())}},11300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCHEMA_REGISTRY=void 0,t.getAllSchemas=function(){return t.SCHEMA_REGISTRY},t.getSchemasByCategory=function(e){const r={vc:["verifiable-credential","verifiable-presentation","statuslist2021-credential","statuslist2021-credential-subject"],delegation:["delegation-credential","delegation-record","delegation-constraints","delegation-chain","delegation-creation-request","delegation-verification-result"],handshake:["handshake-request","session-context","nonce-cache-config","nonce-cache-entry"],proof:["detached-proof","proof-meta","proof","proof-w3c","audit-record","canonical-hashes"],registry:["registration-input","registration-result","agent-status","claim-token","delegation-request","delegation-response","registry-delegation","mirror-status","receipt"],runtime:["authorization-display","needs-authorization-error","runtime-error"],cli:["register-output"],tlkrc:["rotation-chain","rotation-event"],verifier:["verify-page"],"well-known":["well-known-agent"]}[e]||[];return t.SCHEMA_REGISTRY.filter(e=>r.includes(e.id))},t.getSchemaById=function(e){return t.SCHEMA_REGISTRY.find(t=>t.id===e)},t.getCriticalSchemas=function(){const e=["verifiable-credential","statuslist2021-credential","delegation-credential","delegation-record","delegation-constraints","detached-proof","proof-meta","handshake-request","session-context","audit-record"];return t.SCHEMA_REGISTRY.filter(t=>e.includes(t.id))},t.getSchemaStats=function(){const e={},o={};for(const n of t.SCHEMA_REGISTRY){const t=n.url.replace(r+"/","").split("/")[0]||"unknown";e[t]=(e[t]||0)+1,o[n.version]=(o[n.version]||0)+1}return{total:t.SCHEMA_REGISTRY.length,byCategory:e,byVersion:o}};const r="https://schema.modelcontextprotocol-identity.io/xmcp-i";t.SCHEMA_REGISTRY=[{id:"verifiable-credential",url:`${r}/vc/verifiable-credential.v1.0.0.json`,version:"1.0.0",type:"VerifiableCredential",description:"W3C Verifiable Credential Data Model"},{id:"verifiable-presentation",url:`${r}/vc/verifiable-presentation.v1.0.0.json`,version:"1.0.0",type:"VerifiablePresentation",description:"W3C Verifiable Presentation"},{id:"statuslist2021-credential",url:`${r}/vc/statuslist-2021-credential.v1.0.0.json`,version:"1.0.0",type:"StatusList2021Credential",description:"StatusList2021 Credential for efficient revocation"},{id:"statuslist2021-credential-subject",url:`${r}/vc/statuslist-2021-credential-subject.v1.0.0.json`,version:"1.0.0",type:"StatusList2021CredentialSubject",description:"StatusList2021 Credential Subject"},{id:"delegation-credential",url:`${r}/credentials/delegation/v1.0.0.json`,version:"1.0.0",type:"DelegationCredential",description:"W3C VC-based delegation credential"},{id:"delegation-record",url:`${r}/delegation/delegation-record.v1.0.0.json`,version:"1.0.0",type:"DelegationRecord",description:"Internal delegation record"},{id:"delegation-constraints",url:`${r}/delegation/constraints.v1.0.0.json`,version:"1.0.0",type:"DelegationConstraints",description:"CRISP constraints for delegations"},{id:"delegation-chain",url:`${r}/delegation/delegation-chain.v1.0.0.json`,version:"1.0.0",type:"DelegationChain",description:"Delegation chain for hierarchy tracking"},{id:"delegation-creation-request",url:`${r}/delegation/delegation-creation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationCreationRequest",description:"Request to create a delegation"},{id:"delegation-verification-result",url:`${r}/delegation/delegation-verification-result.v1.0.0.json`,version:"1.0.0",type:"DelegationVerificationResult",description:"Result of delegation verification"},{id:"handshake-request",url:`${r}/handshake/handshake-request.v1.0.0.json`,version:"1.0.0",type:"HandshakeRequest",description:"MCP-I handshake request"},{id:"session-context",url:`${r}/handshake/session-context.v1.0.0.json`,version:"1.0.0",type:"SessionContext",description:"MCP-I session context"},{id:"nonce-cache-config",url:`${r}/handshake/nonce-cache-config.v1.0.0.json`,version:"1.0.0",type:"NonceCacheConfig",description:"Nonce cache configuration"},{id:"nonce-cache-entry",url:`${r}/handshake/nonce-cache-entry.v1.0.0.json`,version:"1.0.0",type:"NonceCacheEntry",description:"Nonce cache entry for replay protection"},{id:"detached-proof",url:`${r}/proof/detached-proof.v1.0.0.json`,version:"1.0.0",type:"DetachedProof",description:"MCP-I detached proof with JWS"},{id:"proof-meta",url:`${r}/proof/proof-meta.v1.0.0.json`,version:"1.0.0",type:"ProofMeta",description:"Metadata for MCP-I proofs"},{id:"proof",url:`${r}/proof/v1.0.0.json`,version:"1.0.0",type:"Proof",description:"Generic proof structure"},{id:"proof-w3c",url:`${r}/proof/w3c/v1.0.0.json`,version:"1.0.0",type:"W3CProof",description:"W3C-compliant proof"},{id:"audit-record",url:`${r}/proof/audit-record.v1.0.0.json`,version:"1.0.0",type:"AuditRecord",description:"Audit trail record"},{id:"canonical-hashes",url:`${r}/proof/canonical-hashes.v1.0.0.json`,version:"1.0.0",type:"CanonicalHashes",description:"Canonical hashes for proof generation"},{id:"registration-input",url:`${r}/registry/registration-input.v1.0.0.json`,version:"1.0.0",type:"RegistrationInput",description:"Agent registration input"},{id:"registration-result",url:`${r}/registry/registration-result.v1.0.0.json`,version:"1.0.0",type:"RegistrationResult",description:"Agent registration result"},{id:"agent-status",url:`${r}/registry/agent-status.v1.0.0.json`,version:"1.0.0",type:"AgentStatus",description:"Agent status information"},{id:"claim-token",url:`${r}/registry/claim-token.v1.0.0.json`,version:"1.0.0",type:"ClaimToken",description:"Token for claiming agent ownership"},{id:"delegation-request",url:`${r}/registry/delegation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationRequest",description:"Registry delegation request"},{id:"delegation-response",url:`${r}/registry/delegation-response.v1.0.0.json`,version:"1.0.0",type:"DelegationResponse",description:"Registry delegation response"},{id:"registry-delegation",url:`${r}/registry/delegation.v1.0.0.json`,version:"1.0.0",type:"RegistryDelegation",description:"Registry delegation object"},{id:"mirror-status",url:`${r}/registry/mirror-status.v1.0.0.json`,version:"1.0.0",type:"MirrorStatus",description:"Registry mirror status"},{id:"receipt",url:`${r}/registry/receipt.v1.0.0.json`,version:"1.0.0",type:"Receipt",description:"Registry receipt"},{id:"authorization-display",url:`${r}/runtime/authorization-display.v1.0.0.json`,version:"1.0.0",type:"AuthorizationDisplay",description:"Authorization display information"},{id:"needs-authorization-error",url:`${r}/runtime/needs-authorization-error.v1.0.0.json`,version:"1.0.0",type:"NeedsAuthorizationError",description:"Error indicating authorization is needed"},{id:"runtime-error",url:`${r}/runtime/runtime-error.v1.0.0.json`,version:"1.0.0",type:"RuntimeError",description:"Generic runtime error"},{id:"register-output",url:`${r}/cli/register-output/v1.0.0.json`,version:"1.0.0",type:"RegisterOutput",description:"CLI registration output"},{id:"rotation-chain",url:`${r}/tlkrc/rotation-chain.v1.0.0.json`,version:"1.0.0",type:"RotationChain",description:"Key rotation chain"},{id:"rotation-event",url:`${r}/tlkrc/rotation-event.v1.0.0.json`,version:"1.0.0",type:"RotationEvent",description:"Key rotation event"},{id:"verify-page",url:`${r}/verifier/verify-page/v1.0.0.json`,version:"1.0.0",type:"VerifyPage",description:"Verifier page response"},{id:"well-known-agent",url:`${r}/well-known/agent/v1.0.0.json`,version:"1.0.0",type:"WellKnownAgent",description:"Agent well-known metadata"}]},11755:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PolicyService=void 0;const o=r(62408);class n{config;policy;constructor(e,t){this.policy=e??structuredClone(o.DEFAULT_POLICY_CONFIG),this.config=t??{}}setPolicy(e){this.policy=e}getPolicy(){return this.policy}isEnabled(){return this.policy.enabled??!0}evaluate(e){if(!this.isEnabled())return{action:"allow",reason:"Policy enforcement disabled",matchType:"default"};const t=this.checkAllowList(e);if(t)return this.config.debug&&console.error("[PolicyService] Allow list match",{context:this.sanitizeContext(e),match:t}),{action:"allow",reason:`Allowed: ${t.reason??"On allow list"}`,matchType:"allow-list"};const r=this.checkDenyList(e);if(r)return this.config.debug&&console.error("[PolicyService] Deny list match",{context:this.sanitizeContext(e),match:r}),{action:"block",reason:r.reason??"On deny list",matchType:"deny-list"};const o=this.checkThresholds(e);if(o)return this.config.debug&&console.error("[PolicyService] Threshold match",{context:this.sanitizeContext(e),result:o}),o;const n=this.evaluateRules(e);return n?(this.config.debug&&console.error("[PolicyService] Rule match",{context:this.sanitizeContext(e),result:n}),n):{action:this.policy.defaultAction??"allow",reason:"No matching rules, using default action",matchType:"default",redirectUrl:"redirect"===this.policy.defaultAction?this.policy.redirectUrl:void 0}}checkAllowList(e){if(!this.policy.allowList?.length)return null;for(const t of this.policy.allowList)if(this.matchesListEntry(e,t))return t;return null}checkDenyList(e){if(!this.policy.denyList?.length)return null;for(const t of this.policy.denyList)if(!1!==t.active&&!(t.expiresAt&&new Date(t.expiresAt)<new Date)&&this.matchesListEntry(e,t))return t;return null}matchesListEntry(e,t){return!!(t.clientDid&&e.clientDid===t.clientDid||t.agentDid&&e.agentDid===t.agentDid||t.clientName&&e.agentName?.toLowerCase()===t.clientName.toLowerCase()||t.agentType&&e.agentType===t.agentType)}checkThresholds(e){const t=this.policy.thresholds;return t?t.trustSignedRequests&&e.signatureVerified||void 0!==e.reputationScore&&e.reputationScore>=t.trustedReputationThreshold?null:void 0!==e.confidence&&e.confidence>=t.confidenceThreshold?{action:t.confidenceAction,reason:`Detection confidence (${e.confidence}) exceeds threshold (${t.confidenceThreshold})`,matchType:"threshold",redirectUrl:"redirect"===t.confidenceAction?this.policy.redirectUrl:void 0}:t.minReputationScore>0&&void 0!==e.reputationScore&&e.reputationScore<t.minReputationScore?{action:t.lowReputationAction,reason:`Reputation score (${e.reputationScore}) below minimum (${t.minReputationScore})`,matchType:"threshold",redirectUrl:"redirect"===t.lowReputationAction?this.policy.redirectUrl:void 0}:null:null}evaluateRules(e){const t=this.policy.rules;if(!t?.length)return null;const r=[...t].filter(e=>!1!==e.enabled).sort((e,t)=>(e.priority??100)-(t.priority??100));for(const t of r)if(this.matchesRule(e,t))return{action:t.action,reason:t.description??t.name,ruleId:t.id,ruleName:t.name,redirectUrl:"redirect"===t.action?t.redirectUrl:void 0,message:t.message,matchType:"rule"};return null}matchesRule(e,t){return t.conditions.every(t=>this.matchesCondition(e,t))}matchesCondition(e,t){const r=this.getContextValue(e,t.field),o=t.value;if(null==r)return"notEquals"===t.operator||"notIn"===t.operator||"notContains"===t.operator;switch(t.operator){case"equals":return this.compareEqual(r,o,t.caseInsensitive);case"notEquals":return!this.compareEqual(r,o,t.caseInsensitive);case"contains":return"string"==typeof r&&"string"==typeof o&&(t.caseInsensitive?r.toLowerCase().includes(o.toLowerCase()):r.includes(o));case"notContains":return"string"!=typeof r||"string"!=typeof o||(t.caseInsensitive?!r.toLowerCase().includes(o.toLowerCase()):!r.includes(o));case"startsWith":return"string"==typeof r&&"string"==typeof o&&(t.caseInsensitive?r.toLowerCase().startsWith(o.toLowerCase()):r.startsWith(o));case"endsWith":return"string"==typeof r&&"string"==typeof o&&(t.caseInsensitive?r.toLowerCase().endsWith(o.toLowerCase()):r.endsWith(o));case"greaterThan":return"number"==typeof r&&"number"==typeof o&&r>o;case"lessThan":return"number"==typeof r&&"number"==typeof o&&r<o;case"greaterThanOrEquals":return"number"==typeof r&&"number"==typeof o&&r>=o;case"lessThanOrEquals":return"number"==typeof r&&"number"==typeof o&&r<=o;case"matches":if("string"!=typeof r||"string"!=typeof o)return!1;try{const e=t.caseInsensitive?"i":"";return new RegExp(o,e).test(r)}catch{return!1}case"in":return!!Array.isArray(o)&&o.some(e=>this.compareEqual(r,e,t.caseInsensitive));case"notIn":return!Array.isArray(o)||!o.some(e=>this.compareEqual(r,e,t.caseInsensitive));default:return!1}}getContextValue(e,t){switch(t){case"agentType":return e.agentType;case"agentName":return e.agentName;case"agentVendor":return e.agentVendor;case"clientDid":return e.clientDid;case"agentDid":return e.agentDid;case"confidence":return e.confidence;case"reputationScore":return e.reputationScore;case"riskLevel":return e.riskLevel;case"path":return e.path;case"method":return e.method;case"origin":return e.origin;case"userAgent":return e.userAgent;case"signatureVerified":return e.signatureVerified;case"isAuthenticated":return e.isAuthenticated;case"hasValidDelegation":return e.hasValidDelegation;default:return}}compareEqual(e,t,r){return"string"==typeof e&&"string"==typeof t&&r?e.toLowerCase()===t.toLowerCase():e===t}sanitizeContext(e){return{agentType:e.agentType,agentName:e.agentName,agentVendor:e.agentVendor,clientDid:e.clientDid?`${e.clientDid.slice(0,20)}...`:void 0,agentDid:e.agentDid?`${e.agentDid.slice(0,20)}...`:void 0,confidence:e.confidence,reputationScore:e.reputationScore,riskLevel:e.riskLevel,path:e.path,method:e.method,signatureVerified:e.signatureVerified,isAuthenticated:e.isAuthenticated,hasValidDelegation:e.hasValidDelegation}}}t.PolicyService=n,t.default=n},14218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>o._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:r,parentSchema:i,it:s}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&i.discriminator)return;const a=r,c=t.let("valid",!1),d=t.let("passing",null),l=t.name("_valid");e.setParams({passing:d}),t.block(function(){a.forEach((r,i)=>{let a;(0,n.alwaysValidSchema)(s,r)?t.var(l,!0):a=e.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},l),i>0&&t.if(o._`${l} && ${c}`).assign(c,!1).assign(d,o._`[${d}, ${i}]`).else(),t.if(l,()=>{t.assign(c,!0),t.assign(d,i),a&&e.mergeEvaluated(a,o.Name)})})}),e.result(c,()=>e.reset(),()=>e.error(!0))}};t.default=i},15988:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(93716).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=o},16928:e=>{"use strict";e.exports=require("path")},17122:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const o=r(74319),n=r(36556),i=n.operators,s={formatMaximum:{okStr:"<=",ok:i.LTE,fail:i.GT},formatMinimum:{okStr:">=",ok:i.GTE,fail:i.LT},formatExclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},formatExclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},a={message:({keyword:e,schemaCode:t})=>n.str`should be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${s[e].okStr}, limit: ${t}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:a,code(e){const{gen:t,data:r,schemaCode:i,keyword:a,it:c}=e,{opts:d,self:l}=c;if(!d.validateFormats)return;const u=new o.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return n._`${e}.compare(${r}, ${i}) ${s[a].fail} 0`}u.$data?function(){const r=t.scopeValue("formats",{ref:l.formats,code:d.code.formats}),o=t.const("fmt",n._`${r}[${u.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${o} != "object"`,n._`${o} instanceof RegExp`,n._`typeof ${o}.compare != "function"`,h(o)))}():function(){const r=u.schema,o=l.formats[r];if(!o||!0===o)return;if("object"!=typeof o||o instanceof RegExp||"function"!=typeof o.compare)throw new Error(`"${a}": format "${r}" does not define "compare" function`);const i=t.scopeValue("formats",{key:r,ref:o,code:d.code.formats?n._`${d.code.formats}${(0,n.getProperty)(r)}`:void 0});e.fail$data(h(i))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},17214:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAUTH_CORS_HEADERS=t.PREFLIGHT_CORS_HEADERS=t.MCP_CORS_HEADERS=t.WELL_KNOWN_CORS_HEADERS=void 0,t.mergeCORSHeaders=function(e,r=t.WELL_KNOWN_CORS_HEADERS){return{...e,...r}},t.applyCORSHeaders=function(e,r=t.MCP_CORS_HEADERS){Object.entries(r).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})},t.WELL_KNOWN_CORS_HEADERS={"Access-Control-Allow-Origin":"*",Vary:"Origin"},t.MCP_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"mcp-session-id",Vary:"Origin"},t.PREFLIGHT_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, mcp-session-id, mcp-protocol-version",Vary:"Origin"},t.OAUTH_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, Accept, mcp-protocol-version","Access-Control-Expose-Headers":"Content-Type",Vary:"Origin"}},17285:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var o=r(96889);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return o.KeywordCxt}});var n=r(36556);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const i=r(29645),s=r(218),a=r(99881),c=r(9198),d=r(36556),l=r(60234),u=r(54029),h=r(28512),f=r(82200),p=r(18669),m=(e,t)=>new RegExp(e,t);m.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function _(e){var t,r,o,n,i,s,a,c,d,l,u,h,f,g,y,v,w,_,b,S,P,$,k,E,I;const C=e.strict,T=null===(t=e.code)||void 0===t?void 0:t.optimize,O=!0===T||void 0===T?1:T||0,D=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:m,A=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(s=null!==(i=e.strictSchema)&&void 0!==i?i:C)||void 0===s||s,strictNumbers:null===(c=null!==(a=e.strictNumbers)&&void 0!==a?a:C)||void 0===c||c,strictTypes:null!==(l=null!==(d=e.strictTypes)&&void 0!==d?d:C)&&void 0!==l?l:"log",strictTuples:null!==(h=null!==(u=e.strictTuples)&&void 0!==u?u:C)&&void 0!==h?h:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:C)&&void 0!==g&&g,code:e.code?{...e.code,optimize:O,regExp:D}:{optimize:O,regExp:D},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(w=e.meta)||void 0===w||w,messages:null===(_=e.messages)||void 0===_||_,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(S=e.schemaId)&&void 0!==S?S:"$id",addUsedSchema:null===(P=e.addUsedSchema)||void 0===P||P,validateSchema:null===($=e.validateSchema)||void 0===$||$,validateFormats:null===(k=e.validateFormats)||void 0===k||k,unicodeRegExp:null===(E=e.unicodeRegExp)||void 0===E||E,int32range:null===(I=e.int32range)||void 0===I||I,uriResolver:A}}class b{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new d.ValueScope({scope:{},prefixes:y,es5:t,lines:r}),this.logger=function(e){if(!1===e)return C;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),S.call(this,v,e,"NOT SUPPORTED"),S.call(this,w,e,"DEPRECATED","warn"),this._metaOpts=I.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),$.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let o=f;"id"===r&&(o={...f},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const o=r(t);return"$async"in r||(this.errors=r.errors),o}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return o.call(this,e,t);async function o(e,t){await n.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||i.call(this,r)}async function n(e){e&&!this.getSchema(e)&&await o.call(this,{$ref:e},!0)}async function i(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return a.call(this,t),await c.call(this,t.missingSchema),i.call(this,e)}}function a({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await d.call(this,e);this.refs[e]||await n.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function d(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);return this}let n;if("object"==typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error(`schema ${t} must be string`)}return t=(0,l.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const o=this.validate(r,e);if(!o&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return o}getSchema(e){let t;for(;"string"==typeof(t=P.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,o=new c.SchemaEnv({schema:{},schemaId:r});if(t=c.resolveSchema.call(this,o,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=P.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,l.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(O.call(this,r,t),!t)return(0,h.eachItem)(r,e=>D.call(this,e)),this;R.call(this,t);const o={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,h.eachItem)(r,0===o.type.length?e=>D.call(this,e,o):e=>o.type.forEach(t=>D.call(this,e,o,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const o of t){const t=o.split("/").slice(1);let n=e;for(const e of t)n=n[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:o}=t.definition,i=n[e];o&&i&&(n[e]=j(i))}}return e}_removeAllSchemas(e,t){for(const r in e){const o=e[r];t&&!t.test(r)||("string"==typeof o?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,t,r,o=this.opts.validateSchema,n=this.opts.addUsedSchema){let i;const{schemaId:s}=this.opts;if("object"==typeof e)i=e[s];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let a=this._cache.get(e);if(void 0!==a)return a;r=(0,l.normalizeId)(i||r);const d=l.getSchemaRefs.call(this,e,r);return a=new c.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:r,localRefs:d}),this._cache.set(a.schema,a),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=a),o&&this.validateSchema(e,!0),a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):c.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{c.compileSchema.call(this,e)}finally{this.opts=t}}}function S(e,t,r,o="error"){for(const n in e){const i=n;i in t&&this.logger[o](`${r}: option ${n}. ${e[i]}`)}}function P(e){return e=(0,l.normalizeId)(e),this.schemas[e]||this.refs[e]}function $(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function I(){const e={...this.opts};for(const t of g)delete e[t];return e}b.ValidationError=i.default,b.MissingRefError=s.default,t.default=b;const C={log(){},warn(){},error(){}},T=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){const{RULES:r}=this;if((0,h.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function D(e,t,r){var o;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let s=n?i.post:i.rules.find(({type:e})=>e===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;const a={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?A.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,null===(o=t.implements)||void 0===o||o.forEach(e=>this.addKeyword(e))}function A(e,t,r){const o=e.rules.findIndex(e=>e.keyword===r);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}const x={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function j(e){return{anyOf:[e,x]}}},18669:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(5019);o.code='require("ajv/dist/runtime/uri").default',t.default=o},19315:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(79135),n={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,o.validateTuple)(e,"items")};t.default=n},19812:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>o.str`must be multiple of ${e}`,params:({schemaCode:e})=>o._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,a=t.let("res"),c=s?o._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:o._`${a} !== parseInt(${a})`;e.fail$data(o._`(${n} === 0 || (${a} = ${r}/${n}, ${c}))`)}};t.default=n},20925:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(28512),n={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,o.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};t.default=n},21378:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i=r(95014),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return o.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>o._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:s,it:a}=e,c="maxLength"===t?o.operators.GT:o.operators.LT,d=!1===a.opts.unicode?o._`${r}.length`:o._`${(0,n.useFunc)(e.gen,i.default)}(${r})`;e.fail$data(o._`${d} ${c} ${s}`)}};t.default=s},23137:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MCPIRuntimeBase=void 0;const o=r(4901),n=r(81296),i=r(36255),s=r(82906),a=r(65067);t.MCPIRuntimeBase=class{crypto;clock;fetch;storage;nonceCache;identity;config;cachedIdentity;sessions=new Map;lastProof;userDidManager;interceptedCalls=new Map;cryptoService;proofVerifier;accessControlService;constructor(e){this.config=e,this.crypto=e.cryptoProvider,this.clock=e.clockProvider,this.fetch=e.fetchProvider,this.storage=e.storageProvider,this.nonceCache=e.nonceCacheProvider,this.identity=e.identityProvider,this.cryptoService=new n.CryptoService(this.crypto)}async initialize(){this.cachedIdentity=await this.identity.getIdentity(),this.config.identity?.generateUserDids&&(this.userDidManager=new a.UserDidManager({crypto:this.crypto,storage:this.config.identity?.userDidStorage?{get:async e=>await this.storage.get(`userDid:${e}`),set:async(e,t,r)=>{await this.storage.set(`userDid:${e}`,t)},delete:async e=>await this.storage.delete(`userDid:${e}`)}:void 0,useDidWeb:"persistent"===this.config.identity?.userDidStorage})),"initialize"in this.nonceCache&&"function"==typeof this.nonceCache.initialize&&await this.nonceCache.initialize(),this.config.audit?.enabled&&this.logAudit("runtime_initialized",{did:this.cachedIdentity.did,environment:this.config.environment||"development",userDidGeneration:this.config.identity?.generateUserDids?"enabled":"disabled"})}async getIdentity(){return this.cachedIdentity||(this.cachedIdentity=await this.identity.getIdentity()),this.cachedIdentity}async handleHandshake(e){const t=await this.getIdentity(),r=this.clock.now(),o=await this.generateSessionId();let n;if(this.userDidManager)try{const t=e.oauthIdentity;n=await this.userDidManager.getOrCreateUserDid(o,t)??void 0,this.config.audit?.enabled&&(n?console.error("[MCP-I] Resolved existing user DID for session:",{userDid:n.substring(0,20)+"...",hasOAuth:!!t,provider:t?.provider}):console.error("[MCP-I] Session started anonymous (no userDid):",{sessionId:o.substring(0,8)+"...",hasOAuth:!!t}))}catch(e){console.warn("[MCP-I] Failed to resolve user DID:",e)}const i=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},s=i(e.clientProtocolVersion),a=e.clientCapabilities,c=e.clientInfo,d=c||"string"==typeof s||void 0!==a?{name:i(c?.name)??"unknown",title:i(c?.title),version:i(c?.version),platform:i(c?.platform),vendor:i(c?.vendor),persistentId:i(c?.persistentId),clientId:i(c?.clientId)??crypto.randomUUID(),protocolVersion:s,capabilities:a}:void 0,l={id:o,clientDid:e.clientDid||n,userDid:n,agentDid:e.agentDid,serverDid:t.did,audience:e.audience,createdAt:r,expiresAt:this.clock.calculateExpiry(60*(this.config.session?.ttlMinutes||30)),clientInfo:d,identityState:n?"authenticated":"anonymous",oauthIdentity:e.oauthIdentity??void 0};this.sessions.set(o,l);const u={sessionId:o,agentDid:t.did,timestamp:r,capabilities:["identity","proof","audit"],...n&&{userDid:n}},h=await this.signData(u);return{...u,signature:h}}async updateSessionIdentity(e,t,r){const o=this.sessions.get(e);if(!o)throw new Error(`Session not found: ${e}`);o.userDid=t,o.identityState="authenticated",r&&(o.oauthIdentity=r),this.sessions.set(e,o),this.userDidManager&&await this.userDidManager.setUserDidForSession(e,t,r),this.config.audit?.enabled&&console.error("[MCP-I] Session identity updated (Phase 5):",{sessionId:e.substring(0,8)+"...",userDid:t.substring(0,20)+"...",provider:r?.provider,identityState:"authenticated"})}getSession(e){return this.sessions.get(e)}getConsentProvider(e){if(e.authorization){const t=e.authorization;if(("oauth"===t.type||"oauth2"===t.type||"password"===t.type||"idv"===t.type)&&t.provider)return t.provider}return e.oauthProvider}async processToolCall(e,t,r,n){if(this.config.toolProtectionService){const r=await this.getIdentity();this.config.audit?.enabled&&console.error("[MCP-I] Checking tool protection:",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegation:!(!n?.delegationToken&&!n?.consentProof)});const a=await this.config.toolProtectionService.checkToolProtection(e,r.did);if(a){if(!n?.delegationToken&&!n?.consentProof){const i={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},s=this.generateResumeToken(i),c=this.buildConsentUrl(e,a.requiredScopes,n,s,void 0,this.getConsentProvider(a)),d=new o.DelegationRequiredError(e,a.requiredScopes,c,i,s);throw this.interceptedCalls.set(s,i),this.cleanupExpiredInterceptedCalls(),this.config.audit?.enabled&&console.warn("[MCP-I] BLOCKED: Tool requires delegation but none provided",{tool:e,requiredScopes:a.requiredScopes,agentDid:r.did.slice(0,20)+"...",resumeToken:d.resumeToken,consentUrl:c}),d}const c=n?.delegationToken,d=n?.consentProof;if(this.accessControlService)try{this.config.audit?.enabled&&console.error("[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!c,hasConsentProof:!!d,requiredScopes:a.requiredScopes});const s={agent_did:r.did,scopes:a.requiredScopes};n?.userDid&&(s.user_did=n.userDid,this.config.audit?.enabled&&console.error("[MCP-I] 🔐 Including user_did in verification request",{userDid:n.userDid.slice(0,20)+"..."})),c?s.delegation_token=c:d&&(s.credential_jwt=d),s.timestamp=this.clock.now(),(n?.clientDid||n?.clientId)&&(s.client_info={origin:n?.serverOrigin,user_agent:n?.userAgent});const l=await this.accessControlService.verifyDelegation(s,{delegationToken:c||void 0,credentialJwt:d||void 0});if(!l.data.valid){const i=l.data.reason||"Delegation token invalid or expired",s=l.data.error;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:i,errorCode:s?.code,errorMessage:s?.message,requiredScopes:a.requiredScopes});const c={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},d=this.generateResumeToken(c),u=this.buildConsentUrl(e,a.requiredScopes,n,d,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(d,c),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,u,c,d)}const u=l.data.credential,h=u?.user_identifier,f=u?.user_id,p=n?.userDid;if(h&&p){const i=h===p||f===p,s=h.startsWith("did:");if((s||f)&&!i){h.substring(0,20),p.substring(0,20),this.config.audit?.enabled&&console.error("[MCP-I] 🔒 SECURITY: User identifier validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:h.substring(0,20)+"...",delegationUserId:f?f.substring(0,20)+"...":"N/A",sessionUserDid:p.substring(0,20)+"...",sessionId:n?.id?.substring(0,20)+"...",reason:"user_identifier_mismatch",severity:"high"});const i={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},s=this.generateResumeToken(i),c=this.buildConsentUrl(e,a.requiredScopes,n,s,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(s,i),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,c,i,s)}this.config.audit?.enabled&&console.error("[MCP-I] ✅ User identifier validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",userDid:p.substring(0,20)+"...",sessionId:n?.id?.substring(0,20)+"...",matchType:i?"direct":"trusted_agentshield_verification",delegationIdentifierFormat:s?"did":"email_or_other"})}else h&&!p&&this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:h.substring(0,20)+"...",sessionId:n?.id?.substring(0,20)+"..."});const m=a.authorization,g=u?.authorization;if(m&&u){if(!g){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Tool requires authorization but credential missing auth data",{tool:e,agentDid:r.did.slice(0,20)+"...",toolAuth:m,note:"Credential exists but missing authorization metadata - rejecting for security"});const i={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},s=this.generateResumeToken(i),c=this.buildConsentUrl(e,a.requiredScopes,n,s,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(s,i),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,c,i,s)}if(!(0,i.authorizationMatches)(g,m)){const i=`Authorization method mismatch: delegation has ${g.type}${g.provider?`:${g.provider}`:""}${g.credentialType?`:${g.credentialType}`:""} but tool requires ${m.type}${m.provider?`:${m.provider}`:""}${m.credentialType?`:${m.credentialType}`:""}`;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Authorization method validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:i,delegationAuth:g,toolAuth:m});const s={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},c=this.generateResumeToken(s),d=this.buildConsentUrl(e,a.requiredScopes,n,c,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(c,s),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,d,s,c)}this.config.audit?.enabled&&console.error("[MCP-I] ✅ Authorization method validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",authType:g.type,provider:g.provider||"N/A"})}this.config.audit?.enabled&&console.error("[MCP-I] ✅ Delegation verification SUCCEEDED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationId:l.data.delegation_id,credentialScopes:l.data.credential?.scopes,requiredScopes:a.requiredScopes})}catch(i){if(i instanceof o.DelegationRequiredError)throw i;if(i instanceof s.AgentShieldAPIError){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification error (API failure)",{tool:e,agentDid:r.did.slice(0,20)+"...",errorCode:i.code,errorMessage:i.message,errorDetails:i.details});const s={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},c=this.generateResumeToken(s),d=this.buildConsentUrl(e,a.requiredScopes,n,c,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(c,s),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,d,s,c)}this.config.audit?.enabled&&console.error("[MCP-I] ❌ Unexpected error during delegation verification",{tool:e,agentDid:r.did.slice(0,20)+"...",error:i.message||String(i),errorStack:i.stack});const c={toolName:e,args:t,sessionId:n?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},d=this.generateResumeToken(c),l=this.buildConsentUrl(e,a.requiredScopes,n,d,void 0,this.getConsentProvider(a));throw this.interceptedCalls.set(d,c),this.cleanupExpiredInterceptedCalls(),new o.DelegationRequiredError(e,a.requiredScopes,l,c,d)}else this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!c,hasConsentProof:!!d})}else this.config.audit?.enabled&&console.error("[MCP-I] Tool protection check passed (no delegation required)",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:"Tool not configured to require delegation"})}const a=await r(t),c=await this.createProof(a,n);return this.lastProof=c,this.config.audit?.enabled&&this.logAudit("tool_executed",{tool:e,sessionId:n?.id,timestamp:this.clock.now()}),a}async resumeToolCall(e,t,r){const o=this.interceptedCalls.get(e);if(!o)throw new Error(`Invalid or expired resume token: ${e}`);if(this.clock.hasExpired(o.expiresAt))throw this.interceptedCalls.delete(e),new Error(`Resume token expired: ${e}`);const n=this.sessions.get(o.sessionId);if(!n)throw new Error(`Session not found for intercepted call: ${o.sessionId}`);const i={...n,delegationToken:r},s=await this.processToolCall(o.toolName,o.args,t,i);return this.interceptedCalls.delete(e),s}generateResumeToken(e){const t=JSON.stringify({tool:e.toolName,args:e.args,sessionId:e.sessionId,timestamp:e.timestamp});let r=0;for(let e=0;e<t.length;e++)r=(r<<5)-r+t.charCodeAt(e),r&=r;return`resume_${Math.abs(r).toString(36)}_${Date.now().toString(36)}`}cleanupExpiredInterceptedCalls(){this.clock.now();for(const[e,t]of this.interceptedCalls.entries())this.clock.hasExpired(t.expiresAt)&&this.interceptedCalls.delete(e)}buildConsentUrl(e,t,r,o,n,i){const s=new URLSearchParams({tool:e,scopes:t.join(","),session_id:r?.id||"",agent_did:r?.agentDid||""}),a=r?.agentName;return a&&s.set("agent_name",a),n&&s.set("project_id",n),o&&s.set("resume_token",o),i&&s.set("provider",i),`https://kya.vouched.id/bouncer/consent?${s.toString()}`}async issueNonce(e){const t=await this.generateNonce(),r=this.sessions.get(e),o=r?.agentDid||(await this.getIdentity()).did;return await this.nonceCache.add(t,300,o),t}async createProof(e,t){const r=await this.getIdentity(),o=this.clock.now();let n;if(t?.nonce)n=t.nonce;else{n=await this.generateNonce();const e=t?.agentDid||r.did;await this.nonceCache.add(n,300,e)}const i={data:e,timestamp:o,nonce:n,did:r.did,sessionId:t?.id,audience:t?.audience},s=await this.signData(i);return{timestamp:o,nonce:n,did:r.did,signature:s,algorithm:"Ed25519",sessionId:t?.id,audience:t?.audience}}async verifyProof(e,t){if(!(e&&"object"==typeof e&&"jws"in e&&"meta"in e))return this.verifyProofLegacy(e,t);{const r=e,o=t;if(!this.proofVerifier)return console.warn("[MCPIRuntimeBase] ProofVerifier not available, using fallback verification"),this.verifyProofLegacy(e,t);try{const e=await this.fetch.resolveDID(r.meta.did),t=this.extractPublicKeyJwk(e,r.meta.kid);if(!t)return console.error("[MCPIRuntimeBase] Failed to extract public key JWK"),!1;const n=await this.proofVerifier.verifyProof(r,t);if(n.valid&&o){const e=this.proofVerifier.buildCanonicalPayload(r.meta);o.canonicalPayload=e}return n.valid}catch(e){return console.error("[MCPIRuntimeBase] Proof verification failed:",e),!1}}}async verifyProofLegacy(e,t){try{if(await this.nonceCache.has(t.nonce,t.did))return!1;if(!this.clock.isWithinSkew(t.timestamp,this.config.session?.timestampSkewSeconds||120))return!1;const r=await this.fetch.resolveDID(t.did),o=this.extractPublicKey(r),n={data:e,timestamp:t.timestamp,nonce:t.nonce,did:t.did,sessionId:t.sessionId},i=(new TextEncoder).encode(JSON.stringify(n)),s=this.base64ToBytes(t.signature),a=await this.crypto.verify(i,s,o);if(a){const e=60*(this.config.session?.ttlMinutes||30);await this.nonceCache.add(t.nonce,e,t.did)}return a}catch(e){return console.error("Proof verification failed:",e),!1}}async verifyProofJWS(e,t,r){if(!this.cryptoService)return console.error("[MCPIRuntimeBase] CryptoService not initialized"),!1;try{const o=void 0!==r?{detachedPayload:r}:void 0;return await this.cryptoService.verifyJWS(e,t,o)}catch(e){return console.error("[MCPIRuntimeBase] JWS verification failed:",e),!1}}async getCurrentSession(){for(const[e,t]of this.sessions)if(!this.clock.hasExpired(t.expiresAt))return t;return null}getLastProof(){return this.lastProof}createWellKnownHandler(e){return async t=>{const r=await this.getIdentity();if("/.well-known/did.json"===t){const e=this.createDIDDocument(r);return{status:200,headers:{"Content-Type":"application/did+json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(e,null,2)}}if("/.well-known/agent.json"===t){const t={id:r.did,capabilities:{"mcp-i":["handshake","signing","verification"]}};return(e?.serviceName||e?.serviceEndpoint)&&(t.metadata={...e?.serviceName&&{name:e.serviceName},...e?.serviceEndpoint&&{serviceEndpoint:e.serviceEndpoint}}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(t,null,2)}}if("/.well-known/mcp-identity"===t)return{did:r.did,publicKey:r.publicKey,serviceName:e?.serviceName||"MCP-I Service",serviceEndpoint:e?.serviceEndpoint||"https://example.com",timestamp:this.clock.now()};if("/.well-known/mcp.json"===t||"/.well-known/mcp/server-card.json"===t){const t=e?.serviceName||"mcp-i-server",o={$schema:"https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json",version:"1.0",protocolVersion:e?.protocolVersion||"2025-06-18",serverInfo:{name:t,title:e?.serviceTitle||e?.serviceName||"MCP-I Server",version:e?.serverVersion||"1.0.0"},description:e?.description||"MCP-I enabled server with cryptographic identity",...e?.iconUrl&&{iconUrl:e.iconUrl},...e?.documentationUrl&&{documentationUrl:e.documentationUrl},transport:{type:"streamable-http",endpoint:"/mcp"},capabilities:{tools:{listChanged:!0}},...e?.requiresAuth&&{authentication:{required:!0,schemes:e.authSchemes||["oauth2"]}},...e?.instructions&&{instructions:e.instructions},tools:"dynamic",_meta:{...e?.metadata,"mcp-i":{agentDid:r.did,publicKey:r.publicKey,generatedAt:this.clock.now()}}};return{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=3600":"no-store","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Content-Type"},body:JSON.stringify(o,null,2)}}if("/.well-known/mcp-client-config.json"===t){const t=e?.serviceEndpoint||"https://example.com",o=e?.serviceName||"mcp-i-server",n=`${t}/mcp`,i={[o]:{url:n,transport:"sse"}},s=Buffer.from(JSON.stringify(i)).toString("base64"),a=`cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(o)}&config=${encodeURIComponent(s)}`,c={claudeDesktop:{mcpServers:{[o]:{url:n,transport:"sse"}}},cursor:{mcpServers:{[o]:{url:n,transport:"sse"}}},cursorDeepLink:a,_meta:{serverName:o,serverUrl:t,mcpEndpoint:n,agentDid:r.did,generatedAt:this.clock.now(),instructions:"Copy the appropriate config section to your client configuration file."}};return{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(c,null,2)}}return null}}createDebugEndpoint(){return"production"===this.config.environment?null:async()=>{const e=await this.getIdentity(),t=await this.getCurrentSession();return{identity:{did:e.did,publicKey:e.publicKey},session:t,config:{environment:this.config.environment,timestampSkewSeconds:this.config.session?.timestampSkewSeconds,sessionTtlMinutes:this.config.session?.ttlMinutes},timestamp:this.clock.now()}}}getAuditLogger(){return{log:(e,t)=>this.logAudit(e,t)}}async rotateKeys(){const e=this.cachedIdentity?.did,t=await this.identity.rotateKeys();return this.cachedIdentity=t,this.config.audit?.enabled&&this.logAudit("keys_rotated",{oldDid:e,newDid:t.did,timestamp:this.clock.now()}),t}async signData(e){const t=await this.getIdentity(),r=(new TextEncoder).encode(JSON.stringify(e)),o=await this.crypto.sign(r,t.privateKey);return this.bytesToBase64(o)}async generateNonce(){const e=await this.crypto.randomBytes(32);return this.bytesToBase64(e)}async generateSessionId(){const e=await this.crypto.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=this.bytesToHex(e);return`mcpi_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}logAudit(e,t){if(!this.config.audit?.enabled)return;const r={event:e,data:this.config.audit.includePayloads?t:void 0,timestamp:this.clock.now(),timestampFormatted:this.clock.format(this.clock.now())},o=JSON.stringify(r);this.config.audit.logFunction?this.config.audit.logFunction(o):console.error("[AUDIT]",o)}createDIDDocument(e){return{"@context":["https://www.w3.org/ns/did/v1"],id:e.did,verificationMethod:[{id:`${e.did}#key-1`,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyBase64:e.publicKey}],authentication:[`${e.did}#key-1`],assertionMethod:[`${e.did}#key-1`]}}extractPublicKey(e){const t=e.verificationMethod?.[0];if(t?.publicKeyBase64)return t.publicKeyBase64;if(t?.publicKeyMultibase)return t.publicKeyMultibase;throw new Error("Public key not found in DID document")}extractPublicKeyJwk(e,t){const r=e.verificationMethod?.find(e=>{const r="Ed25519VerificationKey2020"===e.type||"JsonWebKey2020"===e.type,o=!t||e.id===t||e.id.endsWith(`#${t}`);return r&&o})||e.verificationMethod?.[0];if(r?.publicKeyJwk){const e=r.publicKeyJwk;if("OKP"===e.kty&&"Ed25519"===e.crv)return e}return r?.publicKeyMultibase?(console.warn("[MCPIRuntimeBase] Multibase to JWK conversion not fully implemented"),null):null}bytesToBase64(e){return Buffer.from(e).toString("base64")}base64ToBytes(e){return new Uint8Array(Buffer.from(e,"base64"))}bytesToHex(e){return Buffer.from(e).toString("hex")}}},23967:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=23967,e.exports=t},24456:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const o=r(36556),n=r(28512);t.getSubschema=function(e,{keyword:t,schemaProp:r,schema:i,schemaPath:s,errSchemaPath:a,topSchemaRef:c}){if(void 0!==t&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const i=e.schema[t];return void 0===r?{schema:i,schemaPath:o._`${e.schemaPath}${(0,o.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:i[r],schemaPath:o._`${e.schemaPath}${(0,o.getProperty)(t)}${(0,o.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,n.escapeFragment)(r)}`}}if(void 0!==i){if(void 0===s||void 0===a||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:s,topSchemaRef:c,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:r,dataPropType:i,data:s,dataTypes:a,propertyName:c}){if(void 0!==s&&void 0!==r)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=t;if(void 0!==r){const{errorPath:s,dataPathArr:a,opts:c}=t;l(d.let("data",o._`${t.data}${(0,o.getProperty)(r)}`,!0)),e.errorPath=o.str`${s}${(0,n.getErrorPath)(r,i,c.jsPropertySyntax)}`,e.parentDataProperty=o._`${r}`,e.dataPathArr=[...a,e.parentDataProperty]}function l(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}void 0!==s&&(l(s instanceof o.Name?s:d.let("data",s,!0)),void 0!==c&&(e.propertyName=c)),a&&(e.dataTypes=a)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:i}){void 0!==o&&(e.compositeRule=o),void 0!==n&&(e.createErrors=n),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}},24886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CascadingRevocationManager=void 0,t.createCascadingRevocationManager=function(e,t){return new r(e,t)};class r{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,o=[],n=await this.graph.getNode(e);if(!n)throw new Error(`Delegation not found: ${e}`);const i=await this.graph.getDepth(e);if(i>r)throw new Error(`Delegation depth ${i} exceeds maximum ${r}`);const s=await this.revokeNode(n,!0,t.reason,t.dryRun);o.push(s),t.onRevoke&&await t.onRevoke(s);const a=await this.graph.getDescendants(e);for(const r of a){const n=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);o.push(n),t.onRevoke&&await t.onRevoke(n)}return o}async revokeNode(e,t,r,o,n){const i={delegationId:e.id,isRoot:t,parentId:n,timestamp:Date.now(),reason:r};if(o)return i;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return i}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t.reverse())if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,o]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(o,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}t.CascadingRevocationManager=r},25140:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const o=r(218),n=r(93716),i=r(36556),s=r(94614),a=r(9198),c=r(28512),d={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:n}=e,{baseId:s,schemaEnv:c,validateName:d,opts:h,self:f}=n,{root:p}=c;if(("#"===r||"#/"===r)&&s===p.baseId)return function(){if(c===p)return u(e,d,c,c.$async);const r=t.scopeValue("root",{ref:p});return u(e,i._`${r}.validate`,p,p.$async)}();const m=a.resolveRef.call(f,p,s,r);if(void 0===m)throw new o.default(n.opts.uriResolver,s,r);return m instanceof a.SchemaEnv?function(t){const r=l(e,t);u(e,r,t,t.$async)}(m):function(o){const n=t.scopeValue("schema",!0===h.code.source?{ref:o,code:(0,i.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:i.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(m)}};function l(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):i._`${r.scopeValue("wrapper",{ref:t})}.validate`}function u(e,t,r,o){const{gen:a,it:d}=e,{allErrors:l,schemaEnv:u,opts:h}=d,f=h.passContext?s.default.this:i.nil;function p(e){const t=i._`${e}.errors`;a.assign(s.default.vErrors,i._`${s.default.vErrors} === null ? ${t} : ${s.default.vErrors}.concat(${t})`),a.assign(s.default.errors,i._`${s.default.vErrors}.length`)}function m(e){var t;if(!d.opts.unevaluated)return;const o=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==d.props)if(o&&!o.dynamicProps)void 0!==o.props&&(d.props=c.mergeEvaluated.props(a,o.props,d.props));else{const t=a.var("props",i._`${e}.evaluated.props`);d.props=c.mergeEvaluated.props(a,t,d.props,i.Name)}if(!0!==d.items)if(o&&!o.dynamicItems)void 0!==o.items&&(d.items=c.mergeEvaluated.items(a,o.items,d.items));else{const t=a.var("items",i._`${e}.evaluated.items`);d.items=c.mergeEvaluated.items(a,t,d.items,i.Name)}}o?function(){if(!u.$async)throw new Error("async schema referenced by sync schema");const r=a.let("valid");a.try(()=>{a.code(i._`await ${(0,n.callValidateCode)(e,t,f)}`),m(t),l||a.assign(r,!0)},e=>{a.if(i._`!(${e} instanceof ${d.ValidationError})`,()=>a.throw(e)),p(e),l||a.assign(r,!1)}),e.ok(r)}():e.result((0,n.callValidateCode)(e,t,f),()=>m(t),()=>p(t))}t.getValidate=l,t.callRef=u,t.default=d},25344:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i=r(56935),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>o._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:s,schema:a,schemaCode:c,it:d}=e;if(!s&&0===a.length)throw new Error("enum must have non-empty array");const l=a.length>=d.opts.loopEnum;let u;const h=()=>null!=u?u:u=(0,n.useFunc)(t,i.default);let f;if(l||s)f=t.let("valid"),e.block$data(f,function(){t.assign(f,!1),t.forOf("v",c,e=>t.if(o._`${h()}(${r}, ${e})`,()=>t.assign(f,!0).break()))});else{if(!Array.isArray(a))throw new Error("ajv implementation error");const e=t.const("vSchema",c);f=(0,o.or)(...a.map((t,n)=>function(e,t){const n=a[t];return"object"==typeof n&&null!==n?o._`${h()}(${r}, ${e}[${t}])`:o._`${r} === ${n}`}(e,n)))}e.pass(f)}};t.default=s},27087:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.CryptoProvider=class{},t.ClockProvider=class{},t.FetchProvider=class{},t.StorageProvider=class{},t.NonceCacheProvider=class{},t.IdentityProvider=class{}},27399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthRequiredError=void 0;class r extends Error{toolName;requiredScopes;provider;oauthUrl;resumeToken;userDid;sessionId;authType;constructor(e){const{toolName:t,requiredScopes:r,provider:o,oauthUrl:n}=e;super(`OAuth required for tool "${t}" with provider "${o}". Required scopes: ${r.join(", ")}`),this.name="OAuthRequiredError",this.toolName=t,this.requiredScopes=r,this.provider=o,this.oauthUrl=n,this.resumeToken=e.resumeToken,this.userDid=e.userDid,this.sessionId=e.sessionId,this.authType=e.authType}}t.OAuthRequiredError=r},28440:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const o=r(36556),n=r(28512),i={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>o.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>o._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?s(e,o):(0,n.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function s(e,t){const{gen:r,schema:i,data:s,keyword:a,it:c}=e;c.items=!0;const d=r.const("len",o._`${s}.length`);if(!1===i)e.setParams({len:t.length}),e.pass(o._`${d} <= ${t.length}`);else if("object"==typeof i&&!(0,n.alwaysValidSchema)(c,i)){const i=r.var("valid",o._`${d} <= ${t.length}`);r.if((0,o.not)(i),()=>function(i){r.forRange("i",t.length,d,t=>{e.subschema({keyword:a,dataProp:t,dataPropType:n.Type.Num},i),c.allErrors||r.if((0,o.not)(i),()=>r.break())})}(i)),e.ok(i)}}t.validateAdditionalItems=s,t.default=i},28512:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const o=r(36556),n=r(11175);function i(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const n=o.RULES.keywords;for(const r in t)n[r]||p(e,`unknown keyword: "${r}"`)}function s(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function a(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function c(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,s,a,c)=>{const d=void 0===a?s:a instanceof o.Name?(s instanceof o.Name?e(i,s,a):t(i,s,a),a):s instanceof o.Name?(t(i,a,s),s):r(s,a);return c!==o.Name||d instanceof o.Name?d:n(i,d)}}function l(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",o._`{}`);return void 0!==t&&u(e,r,t),r}function u(e,t,r){Object.keys(r).forEach(r=>e.assign(o._`${t}${(0,o.getProperty)(r)}`,!0))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(i(e,t),!s(t,e.self.RULES.all))},t.checkUnknownRules=i,t.schemaHasRules=s,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return o._`${r}`}return o._`${e}${t}${(0,o.getProperty)(n)}`},t.unescapeFragment=function(e){return c(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(a(e))},t.escapeJsonPointer=a,t.unescapeJsonPointer=c,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:d({mergeNames:(e,t,r)=>e.if(o._`${r} !== true && ${t} !== undefined`,()=>{e.if(o._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,o._`${r} || {}`).code(o._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(o._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,o._`${r} || {}`),u(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:l}),items:d({mergeNames:(e,t,r)=>e.if(o._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,o._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(o._`${r} !== true`,()=>e.assign(r,!0===t||o._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=l,t.setEvaluated=u;const h={};var f;function p(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:h[t.code]||(h[t.code]=new n._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(f||(t.Type=f={})),t.getErrorPath=function(e,t,r){if(e instanceof o.Name){const n=t===f.Num;return r?n?o._`"[" + ${e} + "]"`:o._`"['" + ${e} + "']"`:n?o._`"/" + ${e}`:o._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,o.getProperty)(e).toString():"/"+a(e)},t.checkStrictMode=p},28717:e=>{"use strict";e.exports=require("@kya-os/contracts/proof")},29645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},29880:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(93716),n=r(36556),i=r(28512),s=r(28512),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:a,parentSchema:c,it:d}=e,{opts:l}=d,u=(0,o.allSchemaProperties)(r),h=u.filter(e=>(0,i.alwaysValidSchema)(d,r[e]));if(0===u.length||h.length===u.length&&(!d.opts.unevaluated||!0===d.props))return;const f=l.strictSchema&&!l.allowMatchingProperties&&c.properties,p=t.name("valid");!0===d.props||d.props instanceof n.Name||(d.props=(0,s.evaluatedPropsToName)(t,d.props));const{props:m}=d;function g(e){for(const t in f)new RegExp(e).test(t)&&(0,i.checkStrictMode)(d,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(r){t.forIn("key",a,i=>{t.if(n._`${(0,o.usePattern)(e,r)}.test(${i})`,()=>{const o=h.includes(r);o||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:i,dataPropType:s.Type.Str},p),d.opts.unevaluated&&!0!==m?t.assign(n._`${m}[${i}]`,!0):o||d.allErrors||t.if((0,n.not)(p),()=>t.break())})})}!function(){for(const e of u)f&&g(e),d.allErrors?y(e):(t.var(p,!0),y(e),t.if(p))}()}};t.default=a},29961:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=[r(62898).default];t.default=o},30124:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BatchDelegationService=void 0,t.BatchDelegationService=class{providerResolver;toolProtectionService;constructor(e,t){this.providerResolver=e,this.toolProtectionService=t}async groupToolsByProvider(e,t,r){const o=new Map;for(const n of e){const e=await this.toolProtectionService.checkToolProtection(n,r);if(!e?.requiresDelegation)continue;let i;try{i=await this.providerResolver.resolveProvider(e,t)}catch(e){console.warn(`[BatchDelegation] Could not resolve provider for tool "${n}", skipping`,e instanceof Error?e.message:String(e));continue}o.has(i)||o.set(i,{provider:i,tools:[],scopes:[],riskLevel:"medium"});const s=o.get(i);s.tools.push(n);const a=new Set([...s.scopes,...e.requiredScopes||[]]);if(s.scopes=Array.from(a),e.riskLevel){const t={low:1,medium:2,high:3,critical:4},r=t[s.riskLevel]||1;(t[e.riskLevel]||1)>r&&(s.riskLevel="critical"===e.riskLevel?"high":e.riskLevel)}}return o}async getToolsForProvider(e,t,r){return[]}}},30845:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialIssuer=void 0,t.createDelegationIssuer=function(e,t){return new i(e,t)};const o=r(62408),n=r(63969);class i{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=(0,o.wrapDelegationAsVC)(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const n=this.canonicalizeVC(r),i=await this.signingFunction(n,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:i}}async createAndIssueDelegation(e,t={}){const r=Date.now(),o={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(o,t)}canonicalizeVC(e){return(0,n.canonicalizeJSON)(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}t.DelegationCredentialIssuer=i},32299:(e,t)=>{"use strict";function r(e){return`agent:${e}:delegation`}function o(e,t,r){return r?`delegation:user:${e}:agent:${t}:project:${r}`:`delegation:user:${e}:agent:${t}`}function n(e){return`session:${e}`}function i(e,t){return`userDid:oauth:${e}:${t}`}function s(e,t){return`oauth:${e}:${t}`}function a(e){return`verified:${e}`}function c(e){return`nonce:${e}`}Object.defineProperty(t,"__esModule",{value:!0}),t.STORAGE_KEYS=void 0,t.legacyDelegationKey=r,t.compositeDelegationKey=o,t.sessionKey=n,t.userDidKey=i,t.oauthIdentityKey=s,t.verificationCacheKey=a,t.nonceKey=c,t.migrateDelegationKeys=async function(e,t={}){const r={migrated:0,failed:0,migrations:[],errors:[]};try{const n=(await e.list("agent:")).filter(e=>e.match(/^agent:[^:]+:delegation$/));console.error(`Found ${n.length} legacy delegation keys to migrate`);for(const i of n)try{const n=i.match(/^agent:([^:]+):delegation$/);if(!n){r.errors.push({key:i,error:"Invalid legacy key format"}),r.failed++;continue}const s=n[1],a=await e.get(i);if(!a)continue;let c,d=null;const l=await e.list("session:");for(const t of l){const r=await e.get(t);if(r)try{const e=JSON.parse(r);if(e.userDid&&e.agentDid===s){d=e.userDid;const r=t.match(/^session:(.+)$/);r&&(c=r[1]);break}}catch{}}if(t.resolveUserDid){const e=await t.resolveUserDid(s,c);e&&(d=e)}if(!d){r.errors.push({key:i,error:"Cannot resolve userDid - skipping migration"}),r.failed++;continue}const u=o(d,s);t.dryRun?(r.migrations.push({oldKey:i,newKey:u}),r.migrated++):(await e.set(u,a),r.migrations.push({oldKey:i,newKey:u}),r.migrated++,t.deleteOldKeys&&await e.delete(i))}catch(e){r.errors.push({key:i,error:e instanceof Error?e.message:String(e)}),r.failed++}}catch(e){r.errors.push({key:"migration",error:e instanceof Error?e.message:String(e)})}return r},t.STORAGE_KEYS={userDid:i,oauthIdentity:s,delegation:o,session:n,legacyDelegation:r,verificationCache:a,nonce:c}},36255:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessControlApiService=void 0,t.authorizationMatches=function(e,t){return!t||(!("credential"!==e.type||"oauth"!==t.type||!e.credentialType||!t.provider||e.credentialType!==t.provider)||e.type===t.type&&("oauth"===e.type?!t.provider||e.provider===t.provider:"verifiable_credential"!==e.type||(!t.credentialType||e.credentialType===t.credentialType)))};const o=r(82906),n=r(82906);function i(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}t.AccessControlApiService=class{config;metrics;constructor(e){const t=e.retryConfig||{};this.config={retryConfig:{maxRetries:t.maxRetries??3,initialDelayMs:t.initialDelayMs??100,maxDelayMs:t.maxDelayMs??5e3},logger:e.logger||(()=>{}),baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,sleepProvider:e.sleepProvider||(e=>new Promise(t=>setTimeout(t,e)))},this.metrics={successCount:0,errorCount:0,retryCount:0}}async fetchConfig(e){return this.retryWithBackoff(async()=>{const t=i(),r=`${this.config.baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e.agentDid)}`;this.config.logger(`[AccessControl] Fetching config for agent: ${e.agentDid}`,{correlationId:t,url:r});const s=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":t}}),a=await s.text(),c=this.parseResponseJSON(s,a);s.ok||this.handleErrorResponse(s,c);const d=o.toolProtectionConfigAPIResponseSchema.safeParse(c);if(!d.success)throw new n.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:d.error.errors});return this.config.logger("[AccessControl] Config fetched successfully",{correlationId:t,agentDid:e.agentDid}),d.data})}async verifyDelegation(e,t){return this.retryWithBackoff(async()=>{const r=i(),s=`${this.config.baseUrl}/api/v1/bouncer/delegations/verify`,a={agent_did:e.agent_did};void 0!==e.scopes&&(a.scopes=e.scopes),void 0!==e.user_did&&(a.user_did=e.user_did),void 0!==e.credential_jwt?a.credential_jwt=e.credential_jwt:t?.credentialJwt&&(a.credential_jwt=t.credentialJwt),void 0!==e.delegation_token?a.delegation_token=e.delegation_token:t?.delegationToken&&(a.delegation_token=t.delegationToken),void 0!==e.timestamp&&(a.timestamp=e.timestamp),e.client_info&&(a.client_info=e.client_info);const c=Object.fromEntries(Object.entries(a).filter(([e,t])=>void 0!==t)),d=o.verifyDelegationRequestSchema.safeParse(c);if(!d.success&&(!d.error.errors.find(e=>e.path.includes("scopes")&&"Required"===e.message)||"scopes"in c))throw this.config.logger("[AccessControl] Validation failed:",{errors:d.error.errors,requestBody:a}),new n.AgentShieldAPIError("validation_error","Request validation failed",{zodErrors:d.error.errors});this.config.logger(`[AccessControl] Verifying delegation for agent: ${e.agent_did}`,{correlationId:r,url:s,hasScopes:(e.scopes?.length||0)>0});const l=await this.config.fetchProvider.fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":r},body:JSON.stringify(c)}),u=await l.text(),h=this.parseResponseJSON(l,u);l.ok||this.handleErrorResponse(l,h);const f=o.verifyDelegationAPIResponseSchema.safeParse(h);if(!f.success)throw new n.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:f.error.errors});return this.config.logger("[AccessControl] Delegation verified",{correlationId:r,agentDid:e.agent_did,valid:f.data.data.valid}),f.data})}async submitProofs(e){return this.retryWithBackoff(async()=>{const t=o.proofSubmissionRequestSchema.safeParse(e);if(!t.success){const r=JSON.stringify(t.error.errors,null,2);throw this.config.logger("[AccessControl] Proof submission validation failed:",{errors:t.error.errors,request:JSON.stringify(e,null,2)}),new n.AgentShieldAPIError("validation_error",`Request validation failed: ${r}`,{zodErrors:t.error.errors})}const r=t.data,s=i(),a=`${this.config.baseUrl}/api/v1/bouncer/proofs`;this.config.logger(`[AccessControl] Submitting ${e.proofs.length} proof(s)`,{correlationId:s,url:a,sessionId:e.session_id,delegationId:e.delegation_id});const c=await this.config.fetchProvider.fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":s},body:JSON.stringify(r)}),d=await c.text();console.error("[AccessControl] 🔍 RAW API RESPONSE (before parsing):",{correlationId:s,status:c.status,statusText:c.statusText,headers:Object.fromEntries(c.headers.entries()),responseTextLength:d.length,responseTextPreview:d.substring(0,500),fullResponseText:d});const l=this.parseResponseJSON(c,d);if(console.error("[AccessControl] 🔍 PARSED RESPONSE DATA:",{correlationId:s,status:c.status,responseDataType:typeof l,responseDataKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2)}),!c.ok){const t=l;if(t.error){const r=t.error.code||"api_error";if("all_proofs_rejected"===r&&400===c.status){const r=t.error.details,i={success:!1,accepted:0,rejected:r?.rejected||e.proofs.length,outcomes:{success:0,failed:0,blocked:0,error:r?.rejected||e.proofs.length},errors:r?.errors},s=o.proofSubmissionResponseSchema.safeParse(i);if(s.success)return s.data;throw new n.AgentShieldAPIError("invalid_response","Error response validation failed",{zodErrors:s.error.errors})}const i={...t.error.details||{},status:c.status};throw new n.AgentShieldAPIError(r,t.error.message||`API error: ${c.status}`,i)}let r="api_error";throw 400===c.status?r="validation_error":404===c.status&&(r=c.statusText.includes("delegation")?"delegation_not_found":"session_not_found"),new n.AgentShieldAPIError(r,`API request failed: ${c.status} ${c.statusText}`,{status:c.status,responseData:l})}const u=l,h={correlationId:s,hasSuccess:void 0!==u.success,hasData:void 0!==u.data,responseType:typeof l,responseKeys:Object.keys(l||{}),responseData:JSON.stringify(l,null,2).substring(0,2e3)};if(this.config.logger("[AccessControl] Raw response received",h),console.error("[AccessControl] Raw response received:",JSON.stringify(l,null,2)),void 0!==u.success&&u.data){let e;try{const t=u.data,r=JSON.parse(JSON.stringify(t));if("object"!=typeof r||null===r)throw new n.AgentShieldAPIError("invalid_response","Response data is not an object after cloning",{originalType:typeof t,clonedType:typeof r,clonedValue:r});e=r}catch(e){if(e instanceof n.AgentShieldAPIError)throw e;throw new n.AgentShieldAPIError("invalid_response","Failed to clone response data",{error:e instanceof Error?e.message:String(e),dataType:typeof u.data})}console.error("[AccessControl] 🔍 DATA OBJECT STRUCTURE (after deep clone):",{correlationId:s,dataKeys:Object.keys(e),hasAccepted:"accepted"in e,hasRejected:"rejected"in e,hasOutcomes:"outcomes"in e,hasErrors:"errors"in e,acceptedType:typeof e.accepted,acceptedValue:e.accepted,rejectedType:typeof e.rejected,rejectedValue:e.rejected,outcomesType:typeof e.outcomes,outcomesValue:e.outcomes,errorsType:typeof e.errors,errorsIsArray:Array.isArray(e.errors),fullData:JSON.stringify(e,null,2)});const t={success:!0===u.success,accepted:e.accepted,rejected:e.rejected};if("outcomes"in e&&void 0!==e.outcomes&&(t.outcomes=e.outcomes),"errors"in e&&void 0!==e.errors&&(t.errors=e.errors),console.error("[AccessControl] 🔍 VALIDATING DATA WITH SUCCESS:",{correlationId:s,dataWithSuccessKeys:Object.keys(t),hasSuccess:"success"in t,successValue:t.success,hasAccepted:"accepted"in t,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedValue:t.rejected,hasOutcomes:"outcomes"in t,outcomesValue:t.outcomes,fullDataWithSuccess:JSON.stringify(t,null,2)}),"number"!=typeof t.accepted||"number"!=typeof t.rejected)throw console.error("[AccessControl] ❌ MISSING REQUIRED FIELDS AFTER CONSTRUCTION:",{correlationId:s,hasAccepted:"accepted"in t,acceptedType:typeof t.accepted,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedType:typeof t.rejected,rejectedValue:t.rejected,dataWithSuccessKeys:Object.keys(t),fullDataWithSuccess:JSON.stringify(t,null,2),dataToValidateKeys:Object.keys(e),fullDataToValidate:JSON.stringify(e,null,2),originalResponseData:JSON.stringify(l,null,2)}),new n.AgentShieldAPIError("invalid_response","Response data missing required fields (accepted/rejected)",{responseData:l,dataToValidate:e,dataWithSuccess:t});const r=o.proofSubmissionResponseSchema.safeParse(t);if(r.success)return this.config.logger("[AccessControl] Proofs submitted successfully (wrapped)",{correlationId:s,accepted:r.data.accepted,rejected:r.data.rejected}),r.data;{const o={correlationId:s,zodErrors:r.error.errors,zodErrorDetails:JSON.stringify(r.error.errors,null,2),dataToValidate:JSON.stringify(e,null,2).substring(0,2e3),dataWithSuccess:JSON.stringify(t,null,2).substring(0,2e3),dataKeys:Object.keys(e),dataWithSuccessKeys:Object.keys(t),originalResponse:JSON.stringify(l,null,2).substring(0,2e3)};throw this.config.logger("[AccessControl] Wrapped response validation failed",o),console.error("[AccessControl] Wrapped response validation failed",o),console.error("[AccessControl] Original wrapped response:",JSON.stringify(l,null,2)),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED - ${r.error.errors.length} error(s):`),r.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,JSON.stringify(r,null,2))}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(r.error.errors,null,2)),new n.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:r.error.errors,responseData:l})}}const f=o.proofSubmissionResponseSchema.safeParse(l);if(!f.success){const e={correlationId:s,zodErrors:f.error.errors,zodErrorDetails:JSON.stringify(f.error.errors,null,2),responseData:JSON.stringify(l,null,2),responseDataType:typeof l,responseKeys:Object.keys(l||{}),httpStatus:c.status,httpStatusText:c.statusText};throw this.config.logger("[AccessControl] Response validation failed",e),console.error("[AccessControl] Response validation failed",{zodErrors:f.error.errors,responseData:l}),console.error("[AccessControl] Response validation failed",e),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED (direct) - ${f.error.errors.length} error(s):`),f.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,r)}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(f.error.errors,null,2)),console.error("[AccessControl] ❌ ACTUAL RESPONSE DATA:",JSON.stringify(l,null,2)),new n.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:f.error.errors,responseData:l})}return this.config.logger("[AccessControl] Proofs submitted successfully",{correlationId:s,accepted:f.data.accepted,rejected:f.data.rejected}),f.data})}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={successCount:0,errorCount:0,retryCount:0}}async retryWithBackoff(e,t=0){try{const t=await e();return this.metrics.successCount++,t}catch(r){const o=this.isRetryableError(r),{maxRetries:n,initialDelayMs:i,maxDelayMs:s}=this.config.retryConfig;if(o&&t<n){const r=Math.min(i*Math.pow(2,t),s);return this.metrics.retryCount++,this.config.logger(`Retrying after ${r}ms (attempt ${t+1}/${n})`),await this.sleep(r),this.retryWithBackoff(e,t+1)}throw this.metrics.errorCount++,r}}isRetryableError(e){if(e instanceof TypeError&&e.message.includes("fetch"))return!0;if(e instanceof n.AgentShieldAPIError){if("server_error"===e.code)return!0;const t=e.details?.status;if(t&&t>=500&&t<600)return!0;if(429===t)return!0}if(e instanceof Error){const t=e.message.toLowerCase();if(t.includes("timeout")||t.includes("timed out"))return!0}return!1}sleep(e){return this.config.sleepProvider(e)}parseResponseJSON(e,t){try{return JSON.parse(t)}catch(r){if(!e.ok){const r=this.mapStatusToErrorCode(e.status);throw new n.AgentShieldAPIError(r,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseText:t.substring(0,500)})}throw new n.AgentShieldAPIError("invalid_response",`Failed to parse response: ${r instanceof Error?r.message:String(r)}`,{responseText:t.substring(0,500)})}}mapStatusToErrorCode(e,t=""){return 400===e?"validation_error":401===e||403===e?"authentication_failed":404===e?"config_not_found":e>=500?"server_error":"api_error"}handleErrorResponse(e,t){const r=t;if(r.error){const t=r.error.code||"api_error",o={...r.error.details||{},status:e.status};throw new n.AgentShieldAPIError(t,r.error.message||`API error: ${e.status}`,o)}const o=this.mapStatusToErrorCode(e.status,e.statusText);throw new n.AgentShieldAPIError(o,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseData:t})}}},36556:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const o=r(11175),n=r(77100);var i=r(11175);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}});var s=r(77100);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new o._Code(">"),GTE:new o._Code(">="),LT:new o._Code("<"),LTE:new o._Code("<="),EQ:new o._Code("==="),NEQ:new o._Code("!=="),NOT:new o._Code("!"),OR:new o._Code("||"),AND:new o._Code("&&"),ADD:new o._Code("+")};class a{optimizeNodes(){return this}optimizeNames(e,t){return this}}class c extends a{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const r=e?n.varKinds.var:this.varKind,o=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=D(this.rhs,e,t)),this}get names(){return this.rhs instanceof o._CodeOrName?this.rhs.names:{}}}class d extends a{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof o.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=D(this.rhs,e,t),this}get names(){return O(this.lhs instanceof o.Name?{}:{...this.lhs.names},this.rhs)}}class l extends d{constructor(e,t,r,o){super(e,r,o),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class h extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class f extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=D(this.code,e,t),this}get names(){return this.code instanceof o._CodeOrName?this.code.names:{}}}class m extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let o=r.length;for(;o--;){const n=r[o];n.optimizeNames(e,t)||(A(e,n.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>T(e,t.names),{})}}class g extends m{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class y extends m{}class v extends g{}v.kind="else";class w extends g{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new v(e):e}return t?!1===e?t instanceof w?t:t.nodes:this.nodes.length?this:new w(R(e),t instanceof w?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=D(this.condition,e,t),this}get names(){const e=super.names;return O(e,this.condition),this.else&&T(e,this.else.names),e}}w.kind="if";class _ extends g{}_.kind="for";class b extends _{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=D(this.iteration,e,t),this}get names(){return T(super.names,this.iteration.names)}}class S extends _{constructor(e,t,r,o){super(),this.varKind=e,this.name=t,this.from=r,this.to=o}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${t} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){const e=O(super.names,this.from);return O(e,this.to)}}class P extends _{constructor(e,t,r,o){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=D(this.iterable,e,t),this}get names(){return T(super.names,this.iterable.names)}}class $ extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}$.kind="func";class k extends m{render(e){return"return "+super.render(e)}}k.kind="return";class E extends g{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,o;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(o=this.finally)||void 0===o||o.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&T(e,this.catch.names),this.finally&&T(e,this.finally.names),e}}class I extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}I.kind="catch";class C extends g{render(e){return"finally"+super.render(e)}}function T(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function O(e,t){return t instanceof o._CodeOrName?T(e,t.names):e}function D(e,t,r){return e instanceof o.Name?i(e):(n=e)instanceof o._Code&&n._items.some(e=>e instanceof o.Name&&1===t[e.str]&&void 0!==r[e.str])?new o._Code(e._items.reduce((e,t)=>(t instanceof o.Name&&(t=i(t)),t instanceof o._Code?e.push(...t._items):e.push(t),e),[])):e;var n;function i(e){const o=r[e.str];return void 0===o||1!==t[e.str]?e:(delete t[e.str],o)}}function A(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function R(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:o._`!${M(e)}`}C.kind="finally",t.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,o){const n=this._scope.toName(t);return void 0!==r&&o&&(this._constants[n.str]=r),this._leafNode(new c(e,n,r)),n}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new d(e,t,r))}add(e,r){return this._leafNode(new l(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==o.nil&&this._leafNode(new p(e)),this}object(...e){const t=["{"];for(const[r,n]of e)t.length>1&&t.push(","),t.push(r),(r!==n||this.opts.es5)&&(t.push(":"),(0,o.addCodeArg)(t,n));return t.push("}"),new o._Code(t)}if(e,t,r){if(this._blockNode(new w(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new w(e))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(w,v)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new b(e),t)}forRange(e,t,r,o,i=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const s=this._scope.toName(e);return this._for(new S(i,s,t,r),()=>o(s))}forOf(e,t,r,i=n.varKinds.const){const s=this._scope.toName(e);if(this.opts.es5){const e=t instanceof o.Name?t:this.var("_arr",t);return this.forRange("_i",0,o._`${e}.length`,t=>{this.var(s,o._`${e}[${t}]`),r(s)})}return this._for(new P("of",i,s,t),()=>r(s))}forIn(e,t,r,i=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,o._`Object.keys(${t})`,r);const s=this._scope.toName(e);return this._for(new P("in",i,s,t),()=>r(s))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new h(e))}return(e){const t=new k;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const o=new E;if(this._blockNode(o),this.code(e),t){const e=this.name("e");this._currNode=o.catch=new I(e),t(e)}return r&&(this._currNode=o.finally=new C,this.code(r)),this._endBlockNode(I,C)}throw(e){return this._leafNode(new f(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=o.nil,r,n){return this._blockNode(new $(e,t,r)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode($)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=R;const x=N(t.operators.AND);t.and=function(...e){return e.reduce(x)};const j=N(t.operators.OR);function N(e){return(t,r)=>t===o.nil?r:r===o.nil?t:o._`${M(t)} ${e} ${M(r)}`}function M(e){return e instanceof o.Name?e:o._`(${e})`}t.or=function(...e){return e.reduce(j)}},37121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=void 0,t.createSchemaVerifier=function(e){return new r(e)};class r{schemasBaseUrl="https://schema.modelcontextprotocol-identity.io";schemaCache=new Map;constructor(e){e?.schemasBaseUrl&&(this.schemasBaseUrl=e.schemasBaseUrl)}async verifySchema(e,t){const r=[],o=[],n=[];let i;try{i=await this.fetchSchema(e.url)}catch(t){return{schema:e,compliant:!1,compliancePercentage:0,fields:[],issues:[`Failed to fetch schema: ${t instanceof Error?t.message:"Unknown error"}`],warnings:[],timestamp:Date.now()}}const s=this.resolveRef(i,i),a=this.validateAgainstSchema(t,s,i,"");r.push(...a.fields);for(const e of r)"fail"===e.status?o.push(`${e.fieldPath}: ${e.reason}`):"warning"===e.status&&n.push(`${e.fieldPath}: ${e.reason}`);const c=r.filter(e=>e.required),d=c.filter(e=>"pass"===e.status).length,l=c.length>0?d/c.length*100:100;return{schema:e,compliant:0===o.length&&l>=95,compliancePercentage:l,fields:r,issues:o,warnings:n,timestamp:Date.now()}}async verifyAll(e,t){const r=[],o=[];for(const n of e){const e=t.get(n.id);if(!e){o.push(`No implementation found for schema: ${n.id}`);continue}const i=await this.verifySchema(n,e);r.push(i),i.compliant||o.push(`${n.id}: ${i.issues.join(", ")}`)}const n=r.filter(e=>e.compliant).length,i=e.length>0?n/e.length*100:0;return{totalSchemas:e.length,compliantSchemas:n,overallCompliance:i,schemaReports:r,criticalIssues:o,timestamp:Date.now()}}validateAgainstSchema(e,t,r,o){const n=[];if((t=this.resolveRef(t,r)).oneOf||t.anyOf||t.allOf)return this.validateUnion(e,t,r,o);if("object"===t.type&&t.properties){const i=t.required||[];for(const[s,a]of Object.entries(t.properties)){const t=o?`${o}.${s}`:s,c=e?.[s],d=i.includes(s),l=this.checkField(t,c,a,r,d);if(n.push(l),void 0!==c&&"object"===a.type){const e=this.validateAgainstSchema(c,a,r,t);n.push(...e.fields)}}}if("array"===t.type&&e&&Array.isArray(e)){const i=this.validateArray(e,t,r,o);n.push(...i.fields)}return{fields:n}}validateUnion(e,t,r,o){const n=[];if(t.anyOf||t.oneOf){const i=t.anyOf||t.oneOf;let s=!1;for(const t of i){const i=this.resolveRef(t,r);try{if(this.matchesSchema(e,i,r)){const t=this.validateAgainstSchema(e,i,r,o);n.push(...t.fields),s=!0;break}}catch(e){continue}}!s&&o&&n.push({fieldPath:o,present:void 0!==e,expectedType:"oneOf/anyOf options",actualType:typeof e,typeMatches:!1,required:!0,status:"fail",reason:"Value does not match any of the schema options"})}if(t.allOf)for(const i of t.allOf){const t=this.resolveRef(i,r),s=this.validateAgainstSchema(e,t,r,o);n.push(...s.fields)}return{fields:n}}matchesSchema(e,t,r){if((t=this.resolveRef(t,r)).type){const r=Array.isArray(e)?"array":typeof e;if("integer"===t.type&&"number"===r){if(!Number.isInteger(e))return!1}else if(t.type!==r)return!1}if(void 0!==t.const&&e!==t.const)return!1;if(t.enum&&!t.enum.includes(e))return!1;if(t.pattern&&"string"==typeof e&&!new RegExp(t.pattern).test(e))return!1;if("object"===t.type&&t.required)for(const r of t.required)if(!(r in e))return!1;return!0}validateArray(e,t,r,o){const n=[];if(void 0!==t.minItems&&e.length<t.minItems&&n.push({fieldPath:`${o}.length`,present:!0,expectedType:`array with minItems: ${t.minItems}`,actualType:`array with length: ${e.length}`,typeMatches:!1,required:!0,status:"fail",reason:`Array length ${e.length} is less than minItems ${t.minItems}`}),Array.isArray(t.items)){for(let i=0;i<t.items.length;i++){const s=t.items[i],a=e[i],c=`${o}[${i}]`;if(void 0!==a){const e=this.resolveRef(s,r),t=this.validateAgainstSchema(a,e,r,c);n.push(...t.fields)}}if(void 0!==t.additionalItems&&e.length>t.items.length)for(let i=t.items.length;i<e.length;i++){const s=e[i],a=`${o}[${i}]`,c=this.validateAgainstSchema(s,t.additionalItems,r,a);n.push(...c.fields)}}else if(t.items)for(let i=0;i<e.length;i++){const s=e[i],a=`${o}[${i}]`,c=this.resolveRef(t.items,r),d=this.validateAgainstSchema(s,c,r,a);n.push(...d.fields)}if(t.contains){const i=this.resolveRef(t.contains,r);e.some(e=>this.matchesSchema(e,i,r))||n.push({fieldPath:`${o}.contains`,present:!0,expectedType:"array containing matching item",actualType:"array without matching item",typeMatches:!1,required:!0,status:"fail",reason:'Array does not contain any item matching the "contains" schema'})}return{fields:n}}checkField(e,t,r,o,n){r=this.resolveRef(r,o);const i=void 0!==t,s=this.getActualType(t);let a="unknown";return r.type?a=r.type:r.anyOf?a="anyOf":r.oneOf?a="oneOf":r.allOf&&(a="allOf"),n&&!i?{fieldPath:e,present:i,expectedType:a,actualType:s,typeMatches:!1,required:n,status:"fail",reason:"Required field missing"}:n||i?this.matchesSchema(t,r,o)?{fieldPath:e,present:i,expectedType:a,actualType:s,typeMatches:!0,required:n,status:"pass"}:{fieldPath:e,present:i,expectedType:a,actualType:s,typeMatches:!1,required:n,status:"fail",reason:"Type/value mismatch"}:{fieldPath:e,present:i,expectedType:a,actualType:s,typeMatches:!0,required:n,status:"pass"}}getActualType(e){return null===e?"null":Array.isArray(e)?"array":"number"==typeof e&&Number.isInteger(e)?"integer":typeof e}resolveRef(e,t){if(!e.$ref)return e;const r=e.$ref;if(r.startsWith("#/definitions/")){const e=r.substring(14);if(t.definitions&&t.definitions[e])return t.definitions[e]}if(r.startsWith("#/$defs/")){const e=r.substring(8);if(t.$defs&&t.$defs[e])return t.$defs[e]}return"#"===r?t:e}async fetchSchema(e){if(this.schemaCache.has(e))return this.schemaCache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.json();return this.schemaCache.set(e,r),r}catch(t){if(t instanceof Error)throw new Error(`Failed to fetch schema from ${e}: ${t.message}`);throw new Error(`Failed to fetch schema from ${e}: Unknown error`)}}generateReport(e){const t=[];t.push(`\n${"=".repeat(80)}`),t.push(`SCHEMA COMPLIANCE REPORT: ${e.schema.id}`),t.push(`${"=".repeat(80)}\n`),t.push(`Schema: ${e.schema.type} v${e.schema.version}`),t.push(`URL: ${e.schema.url}`),t.push("Status: "+(e.compliant?"✅ COMPLIANT":"❌ NON-COMPLIANT")),t.push(`Compliance: ${e.compliancePercentage.toFixed(1)}%\n`),e.issues.length>0&&(t.push(`\n🚨 ISSUES (${e.issues.length}):`),e.issues.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),e.warnings.length>0&&(t.push(`\n⚠️ WARNINGS (${e.warnings.length}):`),e.warnings.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),t.push("\n📊 FIELD DETAILS:\n");const r=e.fields.filter(e=>e.required),o=r.filter(e=>"pass"===e.status).length,n=r.filter(e=>"fail"===e.status).length,i=e.fields.filter(e=>"warning"===e.status).length;return t.push(` ✅ Pass: ${o}/${r.length} required fields`),t.push(` ❌ Fail: ${n}/${r.length} required fields`),t.push(` ⚠️ Warn: ${i} optional fields`),t.push(` 📝 Total: ${e.fields.length} fields checked\n`),t.push(`${"=".repeat(80)}\n`),t.join("\n")}generateFullReport(e){const t=[];return t.push(`\n${"=".repeat(80)}`),t.push("FULL SCHEMA COMPLIANCE REPORT"),t.push(`${"=".repeat(80)}\n`),t.push(`Total Schemas: ${e.totalSchemas}`),t.push(`Compliant: ${e.compliantSchemas}`),t.push("Non-Compliant: "+(e.totalSchemas-e.compliantSchemas)),t.push(`Overall Compliance: ${e.overallCompliance.toFixed(1)}%\n`),e.criticalIssues.length>0&&(t.push(`\n🚨 CRITICAL ISSUES (${e.criticalIssues.length}):`),e.criticalIssues.slice(0,10).forEach((e,r)=>{t.push(` ${r+1}. ${e}`)}),e.criticalIssues.length>10&&t.push(` ... and ${e.criticalIssues.length-10} more issues`)),t.push("\n📊 SCHEMA BREAKDOWN:\n"),e.schemaReports.forEach(e=>{const r=e.compliant?"✅":"❌",o=e.compliancePercentage.toFixed(1);t.push(` ${r} ${e.schema.id}: ${o}%`)}),t.push(`\n${"=".repeat(80)}\n`),t.join("\n")}}t.SchemaVerifier=r},37578:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},40508:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>o._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:r,data:i,it:s}=e;if((0,n.alwaysValidSchema)(s,r))return;const a=t.name("valid");t.forIn("key",i,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},a),t.if((0,o.not)(a),()=>{e.error(!0),s.allErrors||t.break()})}),e.ok(a)}};t.default=i},42399:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=42399,e.exports=t},42769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthTokenRetrievalService=void 0,t.OAuthTokenRetrievalService=class{config;constructor(e){this.config={...e,logger:e.logger||(()=>{}),retryConfig:{maxRetries:3,retryDelay:1e3,retryBackoff:2,...e.retryConfig}}}async retrieveTokens(e,t){const r=`${this.config.baseUrl}/api/v1/bouncer/delegations/${e}/tokens`;this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens",{delegationId:e,endpoint:r});let o=null,n=0;for(;n<=this.config.retryConfig.maxRetries;)try{const o=await this.config.fetchProvider(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!o.ok){const t=await o.json().catch(()=>({}));if(404===o.status||401===o.status)return this.config.logger("[OAuthTokenRetrievalService] Tokens unavailable",{status:o.status,delegationId:e,error:t}),null;const r=t.error?.message||t.error||t.message||`HTTP ${o.status}`;throw new Error(`Token retrieval failed: ${r}`)}const n=await o.json();if(!n.success)return this.config.logger("[OAuthTokenRetrievalService] Token retrieval error response",{delegationId:e,error:n.error}),null;const i=this.mapToIdpTokens(n.data);return this.config.logger("[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",{delegationId:e,expiresAt:new Date(i.expires_at).toISOString(),hasRefreshToken:!!i.refresh_token}),i}catch(t){if(o=t instanceof Error?t:new Error(String(t)),!(n<this.config.retryConfig.maxRetries))return this.config.logger("[OAuthTokenRetrievalService] Max retries exceeded",{delegationId:e,error:o.message,attempts:n+1}),null;{const e=this.config.retryConfig.retryDelay*Math.pow(this.config.retryConfig.retryBackoff,n);this.config.logger("[OAuthTokenRetrievalService] Retry attempt failed, retrying",{attempt:n+1,maxRetries:this.config.retryConfig.maxRetries,delay:e,error:o.message}),await new Promise(t=>setTimeout(t,e)),n++}}return null}mapToIdpTokens(e){let t;return t=e.oauth_expires_at?new Date(e.oauth_expires_at).getTime():e.oauth_expires_in?Date.now()+1e3*e.oauth_expires_in:Date.now()+36e5,{access_token:e.oauth_access_token,refresh_token:e.oauth_refresh_token||void 0,expires_in:e.oauth_expires_in||void 0,expires_at:t,token_type:e.oauth_token_type||"Bearer",scope:e.oauth_scope||void 0}}}},43439:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(93716),n=r(36556),i=r(94614),s=r(28512),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>n._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:r,parentSchema:a,data:c,errsCount:d,it:l}=e;if(!d)throw new Error("ajv implementation error");const{allErrors:u,opts:h}=l;if(l.props=!0,"all"!==h.removeAdditional&&(0,s.alwaysValidSchema)(l,r))return;const f=(0,o.allSchemaProperties)(a.properties),p=(0,o.allSchemaProperties)(a.patternProperties);function m(e){t.code(n._`delete ${c}[${e}]`)}function g(o){if("all"===h.removeAdditional||h.removeAdditional&&!1===r)m(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(u||t.break());if("object"==typeof r&&!(0,s.alwaysValidSchema)(l,r)){const r=t.name("valid");"failing"===h.removeAdditional?(y(o,r,!1),t.if((0,n.not)(r),()=>{e.reset(),m(o)})):(y(o,r),u||t.if((0,n.not)(r),()=>t.break()))}}}function y(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:s.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",c,r=>{f.length||p.length?t.if(function(r){let i;if(f.length>8){const e=(0,s.schemaRefOrVal)(l,a.properties,"properties");i=(0,o.isOwnProperty)(t,e,r)}else i=f.length?(0,n.or)(...f.map(e=>n._`${r} === ${e}`)):n.nil;return p.length&&(i=(0,n.or)(i,...p.map(t=>n._`${(0,o.usePattern)(e,t)}.test(${r})`))),(0,n.not)(i)}(r),()=>g(r)):g(r)}),e.ok(n._`${d} === ${i.default.errors}`)}};t.default=a},44558:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryDelegationGraphStorage=void 0,t.MemoryDelegationGraphStorage=class{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],o=new Set;for(;r.length>0;){const e=r.shift();if(o.has(e))continue;o.add(e);const n=this.nodes.get(e);if(n)for(const e of n.children)if(!o.has(e)){r.push(e);const o=this.nodes.get(e);o&&t.push(o)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let o=0;for(const t of e){const e=this.getChainSync(t.id);o=Math.max(o,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:o}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}},45395:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerifier=void 0;const o=r(81296),n=r(28717),i=r(51708),s=r(53683);t.ProofVerifier=class{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;constructor(e){this.cryptoService=new o.CryptoService(e.cryptoProvider),this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??120,this.nonceTtlSeconds=e.nonceTtlSeconds??300}async verifyProof(e,t){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const o=r.proof,n=await this.validateNonce(o.meta.nonce,o.meta.did);if(!n.valid)return n;const i=await this.validateTimestamp(o.meta.ts);if(!i.valid)return i;const s=this.buildCanonicalPayload(o.meta),a=(new TextEncoder).encode(s),c=await this.verifySignature(o.jws,t,a,o.meta.kid);return c.valid?(await this.addNonceToCache(o.meta.nonce,o.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:s.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async verifyProofDetached(e,t,r){try{const o=await this.validateProofStructure(e);if(!o.valid)return o;const n=o.proof,i=await this.validateNonce(n.meta.nonce,n.meta.did);if(!i.valid)return i;const s=await this.validateTimestamp(n.meta.ts);if(!s.valid)return s;const a=t instanceof Uint8Array?t:(new TextEncoder).encode(t),c=await this.verifySignature(n.jws,r,a,n.meta.kid);return c.valid?(await this.addNonceToCache(n.meta.nonce,n.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:s.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async validateProofStructure(e){const t=n.DetachedProofSchema.safeParse(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:s.PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error.message}`),details:{zodErrors:t.error.errors}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:s.PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:s.PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,o){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:o,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:s.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:o,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});if(!r.verificationMethod||0===r.verificationMethod.length)throw new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let o;if(t){const n=t.startsWith("#")?t:`#${t}`;if(o=r.verificationMethod.find(t=>t.id===n||t.id===`${e}${n}`),!o)throw new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else o=r.verificationMethod[0];if(!o?.publicKeyJwk)throw new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:o?.id});const n=o.publicKeyJwk;if("OKP"!==n.kty||"Ed25519"!==n.crv||!n.x)throw new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${n.kty}, crv=${n.crv}`,{did:e,kid:t,jwk:{kty:n.kty,crv:n.crv}});return n}catch(r){if(r instanceof s.ProofVerificationError)throw r;throw console.error("[ProofVerifier] Failed to fetch public key from DID:",r),new s.ProofVerificationError(s.PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return(0,i.canonicalize)(t)}}},46171:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDefaultConsoleLogger=t.logger=void 0;var o=r(86587);Object.defineProperty(t,"logger",{enumerable:!0,get:function(){return o.logger}}),Object.defineProperty(t,"createDefaultConsoleLogger",{enumerable:!0,get:function(){return o.createDefaultConsoleLogger}})},46610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitstringManager=void 0,t.isIndexSet=async function(e,t,o){const n=r.base64urlDecode(e),i=await o.decompress(n),s=Math.floor(t/8),a=t%8;return!(s>=i.length)&&!!(i[s]&1<<a)};class r{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const o=Math.ceil(e/8);this.bits=new Uint8Array(o)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),o=e%8;t?this.bits[r]|=1<<o:this.bits[r]&=~(1<<o)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,o){const n=r.base64urlDecode(e),i=await o.decompress(n),s=8*i.length,a=new r(s,t,o);return a.bits=i,a}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return r.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;t+="=".repeat(r);const o=atob(t),n=new Uint8Array(o.length);for(let e=0;e<o.length;e++)n[e]=o.charCodeAt(e);return n}static fromSetBits(e,t,o,n){const i=new r(e,o,n);for(const e of t)i.setBit(e,!0);return i}}t.BitstringManager=r},46780:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},47919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionRegistrationService=void 0,t.createSessionRegistrationService=function(e){return e.apiUrl&&e.apiKey?new n({baseUrl:e.apiUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,logger:e.logger}):(e.logger?.("[SessionRegistration] Missing required config - session registration disabled",{hasApiUrl:!!e.apiUrl,hasApiKey:!!e.apiKey}),null)};const o=r(82906);class n{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,logger:e.logger||(()=>{}),timeoutMs:e.timeoutMs??5e3}}async registerSession(e){const t=e.session_id;try{const r=o.registerSessionRequestSchema.safeParse(e);if(!r.success){const e=`Invalid session registration request: ${r.error.message}`;return this.config.logger("[SessionRegistration] Validation failed",{sessionId:t,error:e}),{success:!1,sessionId:t,error:e}}const n=`${this.config.baseUrl}${o.AGENTSHIELD_ENDPOINTS.SESSIONS}`;this.config.logger("[SessionRegistration] Registering session for dashboard visibility",{sessionId:t,agentDid:e.agent_did,clientName:e.client_info.name,url:n});const i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeoutMs);try{const r=await this.config.fetchProvider.fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),signal:i.signal});if(clearTimeout(s),!r.ok){const e=await r.text().catch(()=>"Unknown error");return this.config.logger("[SessionRegistration] Registration failed",{sessionId:t,status:r.status,error:e}),{success:!1,sessionId:t,error:`HTTP ${r.status}: ${e}`}}const a=await r.json(),c=o.registerSessionResponseSchema.safeParse(a.data||a);return c.success?(this.config.logger("[SessionRegistration] Session now visible in AgentShield dashboard",{sessionId:t,registered:c.data.registered}),{success:!0,sessionId:t}):(this.config.logger("[SessionRegistration] Invalid response format",{sessionId:t,response:a}),{success:!0,sessionId:t})}finally{clearTimeout(s)}}catch(e){if(e instanceof Error&&"AbortError"===e.name)return this.config.logger("[SessionRegistration] Request timed out",{sessionId:t,timeoutMs:this.config.timeoutMs}),{success:!1,sessionId:t,error:"Request timed out"};const r=e instanceof Error?e.message:"Unknown error";return this.config.logger("[SessionRegistration] Unexpected error",{sessionId:t,error:r}),{success:!1,sessionId:t,error:r}}}registerSessionAsync(e){this.registerSession(e).catch(t=>{this.config.logger("[SessionRegistration] Background registration failed",{sessionId:e.session_id,error:t instanceof Error?t.message:"Unknown error"})})}}t.SessionRegistrationService=n},48021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=void 0,t.InMemoryOAuthConfigCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const o=Date.now()+r;this.cache.set(e,{value:t,expiresAt:o})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}},t.NoOpOAuthConfigCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},48079:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return o.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>o._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:n}=e,i="maxProperties"===t?o.operators.GT:o.operators.LT;e.fail$data(o._`Object.keys(${r}).length ${i} ${n}`)}};t.default=n},48505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=void 0;const o=r(27087);class n extends o.StorageProvider{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}t.MemoryStorageProvider=n;class i extends o.NonceCacheProvider{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,o=this.nonces.get(r);return!(!o||Date.now()>o&&(this.nonces.delete(r),1))}async add(e,t,r){const o=r?`nonce:${r}:${e}`:`nonce:${e}`,n=Date.now()+1e3*t;this.nonces.set(o,n)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}t.MemoryNonceCacheProvider=i;class s extends o.IdentityProvider{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#key-1`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return`did:key:z${Buffer.from(e,"base64").toString("base64url").substring(0,32)}`}}t.MemoryIdentityProvider=s},50205:e=>{"use strict";var t=e.exports=function(e,t,o){"function"==typeof t&&(o=t,t={}),r(t,"function"==typeof(o=t.cb||o)?o:o.pre||function(){},o.post||function(){},e,"",e)};function r(e,n,i,s,a,c,d,l,u,h){if(s&&"object"==typeof s&&!Array.isArray(s)){for(var f in n(s,a,c,d,l,u,h),s){var p=s[f];if(Array.isArray(p)){if(f in t.arrayKeywords)for(var m=0;m<p.length;m++)r(e,n,i,p[m],a+"/"+f+"/"+m,c,a,f,s,m)}else if(f in t.propsKeywords){if(p&&"object"==typeof p)for(var g in p)r(e,n,i,p[g],a+"/"+f+"/"+o(g),c,a,f,s,g)}else(f in t.keywords||e.allKeys&&!(f in t.skipKeywords))&&r(e,n,i,p,a+"/"+f,c,a,f,s)}i(s,a,c,d,l,u,h)}}function o(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},50399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthProviderRegistry=void 0,t.OAuthProviderRegistry=class{configService;validator;providers=new Map;_configuredProvider=null;constructor(e,t){this.configService=e,this.validator=t}async loadFromAgentShield(e){const t=await this.configService.getOAuthConfig(e);this.providers.clear(),this._configuredProvider=t.configuredProvider||null;for(const[e,r]of Object.entries(t.providers))this.providers.set(e,r)}getConfiguredProvider(){return this._configuredProvider}getProvider(e){return this.providers.get(e)||null}getAllProviders(){return Array.from(this.providers.values())}hasProvider(e){return this.providers.has(e)}getProviderNames(){return Array.from(this.providers.keys())}registerCustomProvider(e,t){this.validator&&this.validator.validate(t,e),this.providers.set(e,t)}getProviderWithParams(e){return this.getProvider(e)||null}}},51708:(e,t,r)=>{"use strict";r.r(t),r.d(t,{canonicalize:()=>o.d,canonicalizeEx:()=>i});var o=r(77753),n=r(10985);function i(e,t){return(0,n.S)(e,t)}},52058:(e,t)=>{"use strict";function r(e,t){return{validate:e,compare:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(i,s),time:r(c(!0),d),"date-time":r(h(!0),f),"iso-time":r(c(),l),"iso-date-time":r(h(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&g.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(b.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return y.lastIndex=0,y.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=w&&e>=v}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:_},double:{type:"number",validate:_},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(e){const t=o.exec(e);if(!t)return!1;const r=+t[1],i=+t[2],s=+t[3];return i>=1&&i<=12&&s>=1&&s<=(2===i&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:n[i])}function s(e,t){if(e&&t)return e>t?1:e<t?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){const r=a.exec(t);if(!r)return!1;const o=+r[1],n=+r[2],i=+r[3],s=r[4],c="-"===r[5]?-1:1,d=+(r[6]||0),l=+(r[7]||0);if(d>23||l>59||e&&!s)return!1;if(o<=23&&n<=59&&i<60)return!0;const u=n-l*c,h=o-d*c-(u<0?1:0);return(23===h||-1===h)&&(59===u||-1===u)&&i<61}}function d(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),o=new Date("2020-01-01T"+t).valueOf();return r&&o?r-o:void 0}function l(e,t){if(!e||!t)return;const r=a.exec(e),o=a.exec(t);return r&&o?(e=r[1]+r[2]+r[3])>(t=o[1]+o[2]+o[3])?1:e<t?-1:0:void 0}const u=/t|\s/i;function h(e){const t=c(e);return function(e){const r=e.split(u);return 2===r.length&&i(r[0])&&t(r[1])}}function f(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),o=new Date(t).valueOf();return r&&o?r-o:void 0}function p(e,t){if(!e||!t)return;const[r,o]=e.split(u),[n,i]=t.split(u),a=s(r,n);return void 0!==a?a||d(o,i):void 0}const m=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,v=-(2**31),w=2**31-1;function _(){return!0}const b=/[^\\]\\Z/},52643:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=52643,e.exports=t},53210:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(96889),n=r(93716),i=r(28512),s=r(43439),a={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:a,data:c,it:d}=e;"all"===d.opts.removeAdditional&&void 0===a.additionalProperties&&s.default.code(new o.KeywordCxt(d,s.default,"additionalProperties"));const l=(0,n.allSchemaProperties)(r);for(const e of l)d.definedProperties.add(e);d.opts.unevaluated&&l.length&&!0!==d.props&&(d.props=i.mergeEvaluated.props(t,(0,i.toHash)(l),d.props));const u=l.filter(e=>!(0,i.alwaysValidSchema)(d,r[e]));if(0===u.length)return;const h=t.name("valid");for(const r of u)f(r)?p(r):(t.if((0,n.propertyInData)(t,c,r,d.opts.ownProperties)),p(r),d.allErrors||t.else().var(h,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(h);function f(e){return d.opts.useDefaults&&!d.compositeRule&&void 0!==r[e].default}function p(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},h)}}};t.default=a},53683:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=void 0,t.createProofVerificationError=function(e,t,o){return new r(e,t,o)},t.PROOF_VERIFICATION_ERROR_CODES={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class r extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}t.ProofVerificationError=r},53871:function(e,t,r){"use strict";var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||o(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),n(r(17214),t),n(r(98448),t),n(r(32299),t),n(r(75306),t)},54029:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const o=r(99881),n=r(84204),i=r(57747),s=r(36556),a=r(28512);var c;function d(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(o.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(c||(t.DataType=c={})),t.getSchemaTypes=function(e){const t=d(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=d,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:i}=e,a=function(e,t){return t?e.filter(e=>l.has(e)||"array"===t&&"array"===e):[]}(t,i.coerceTypes),d=t.length>0&&!(0===a.length&&1===t.length&&(0,n.schemaHasRulesForType)(e,t[0]));if(d){const n=h(t,o,i.strictNumbers,c.Wrong);r.if(n,()=>{a.length?function(e,t,r){const{gen:o,data:n,opts:i}=e,a=o.let("dataType",s._`typeof ${n}`),c=o.let("coerced",s._`undefined`);"array"===i.coerceTypes&&o.if(s._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,s._`${n}[0]`).assign(a,s._`typeof ${n}`).if(h(t,n,i.strictNumbers),()=>o.assign(c,n))),o.if(s._`${c} !== undefined`);for(const e of r)(l.has(e)||"array"===e&&"array"===i.coerceTypes)&&d(e);function d(e){switch(e){case"string":return void o.elseIf(s._`${a} == "number" || ${a} == "boolean"`).assign(c,s._`"" + ${n}`).elseIf(s._`${n} === null`).assign(c,s._`""`);case"number":return void o.elseIf(s._`${a} == "boolean" || ${n} === null
2
- || (${a} == "string" && ${n} && ${n} == +${n})`).assign(c,s._`+${n}`);case"integer":return void o.elseIf(s._`${a} === "boolean" || ${n} === null
3
- || (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(c,s._`+${n}`);case"boolean":return void o.elseIf(s._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(c,!1).elseIf(s._`${n} === "true" || ${n} === 1`).assign(c,!0);case"null":return o.elseIf(s._`${n} === "" || ${n} === 0 || ${n} === false`),void o.assign(c,null);case"array":o.elseIf(s._`${a} === "string" || ${a} === "number"
4
- || ${a} === "boolean" || ${n} === null`).assign(c,s._`[${n}]`)}}o.else(),p(e),o.endIf(),o.if(s._`${c} !== undefined`,()=>{o.assign(n,c),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(s._`${t} !== undefined`,()=>e.assign(s._`${t}[${r}]`,o))}(e,c)})}(e,t,a):p(e)})}return d};const l=new Set(["string","number","integer","boolean","null"]);function u(e,t,r,o=c.Correct){const n=o===c.Correct?s.operators.EQ:s.operators.NEQ;let i;switch(e){case"null":return s._`${t} ${n} null`;case"array":i=s._`Array.isArray(${t})`;break;case"object":i=s._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=a(s._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=a();break;default:return s._`typeof ${t} ${n} ${e}`}return o===c.Correct?i:(0,s.not)(i);function a(e=s.nil){return(0,s.and)(s._`typeof ${t} == "number"`,e,r?s._`isFinite(${t})`:s.nil)}}function h(e,t,r,o){if(1===e.length)return u(e[0],t,r,o);let n;const i=(0,a.toHash)(e);if(i.array&&i.object){const e=s._`typeof ${t} != "object"`;n=i.null?e:s._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else n=s.nil;i.number&&delete i.integer;for(const e in i)n=(0,s.and)(n,u(e,t,r,o));return n}t.checkDataType=u,t.checkDataTypes=h;const f={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?s._`{type: ${e}}`:s._`{type: ${t}}`};function p(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,a.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:e}}(e);(0,i.reportError)(t,f)}t.reportTypeError=p},55579:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=o.operators,i={maximum:{okStr:"<=",ok:n.LTE,fail:n.GT},minimum:{okStr:">=",ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:e,schemaCode:t})=>o.str`must be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>o._`{comparison: ${i[e].okStr}, limit: ${t}}`},a={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:s,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data(o._`${r} ${i[t].fail} ${n} || isNaN(${r})`)}};t.default=a},55921:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationGraphManager=void 0,t.createDelegationGraph=function(e){return new r(e)};class r{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],o=t[e];if(o.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${o.id} issued by ${o.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(o.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${o.id} parentId=${o.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}t.DelegationGraphManager=r},56935:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(67371);o.code='require("ajv/dist/runtime/equal").default',t.default=o},57747:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const o=r(36556),n=r(28512),i=r(94614);function s(e,t){const r=e.const("err",t);e.if(o._`${i.default.vErrors} === null`,()=>e.assign(i.default.vErrors,o._`[${r}]`),o._`${i.default.vErrors}.push(${r})`),e.code(o._`${i.default.errors}++`)}function a(e,t){const{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw(o._`new ${e.ValidationError}(${t})`):(r.assign(o._`${n}.errors`,t),r.return(!1))}t.keywordError={message:({keyword:e})=>o.str`must pass "${e}" keyword validation`},t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?o.str`"${e}" keyword must be ${t} ($data)`:o.str`"${e}" keyword is invalid ($data)`},t.reportError=function(e,r=t.keywordError,n,i){const{it:c}=e,{gen:l,compositeRule:u,allErrors:h}=c,f=d(e,r,n);(null!=i?i:u||h)?s(l,f):a(c,o._`[${f}]`)},t.reportExtraError=function(e,r=t.keywordError,o){const{it:n}=e,{gen:c,compositeRule:l,allErrors:u}=n;s(c,d(e,r,o)),l||u||a(n,i.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(i.default.errors,t),e.if(o._`${i.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(o._`${i.default.vErrors}.length`,t),()=>e.assign(i.default.vErrors,null)))},t.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:n,errsCount:s,it:a}){if(void 0===s)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",s,i.default.errors,s=>{e.const(c,o._`${i.default.vErrors}[${s}]`),e.if(o._`${c}.instancePath === undefined`,()=>e.assign(o._`${c}.instancePath`,(0,o.strConcat)(i.default.instancePath,a.errorPath))),e.assign(o._`${c}.schemaPath`,o.str`${a.errSchemaPath}/${t}`),a.opts.verbose&&(e.assign(o._`${c}.schema`,r),e.assign(o._`${c}.data`,n))})};const c={keyword:new o.Name("keyword"),schemaPath:new o.Name("schemaPath"),params:new o.Name("params"),propertyName:new o.Name("propertyName"),message:new o.Name("message"),schema:new o.Name("schema"),parentSchema:new o.Name("parentSchema")};function d(e,t,r){const{createErrors:n}=e.it;return!1===n?o._`{}`:function(e,t,r={}){const{gen:n,it:s}=e,a=[l(s,r),u(e,r)];return function(e,{params:t,message:r},n){const{keyword:s,data:a,schemaValue:d,it:l}=e,{opts:u,propertyName:h,topSchemaRef:f,schemaPath:p}=l;n.push([c.keyword,s],[c.params,"function"==typeof t?t(e):t||o._`{}`]),u.messages&&n.push([c.message,"function"==typeof r?r(e):r]),u.verbose&&n.push([c.schema,d],[c.parentSchema,o._`${f}${p}`],[i.default.data,a]),h&&n.push([c.propertyName,h])}(e,t,a),n.object(...a)}(e,t,r)}function l({errorPath:e},{instancePath:t}){const r=t?o.str`${e}${(0,n.getErrorPath)(t,n.Type.Str)}`:e;return[i.default.instancePath,(0,o.strConcat)(i.default.instancePath,r)]}function u({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let s=i?t:o.str`${t}/${e}`;return r&&(s=o.str`${s}${(0,n.getErrorPath)(r,n.Type.Str)}`),[c.schemaPath,s]}},60234:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const o=r(28512),n=r(67371),i=r(50205),s=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&d(e)<=t)};const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(a.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(c))return!0;if("object"==typeof r&&c(r))return!0}return!1}function d(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!s.has(r)&&("object"==typeof e[r]&&(0,o.eachItem)(e[r],e=>t+=d(e)),t===1/0))return 1/0}return t}function l(e,t="",r){!1!==r&&(t=f(t));const o=e.parse(t);return u(e,o)}function u(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=l,t._getFullPath=u;const h=/#\/?$/;function f(e){return e?e.replace(h,""):""}t.normalizeId=f,t.resolveUrl=function(e,t,r){return r=f(r),e.resolve(t,r)};const p=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,s=f(e[r]||t),a={"":s},c=l(o,s,!1),d={},u=new Set;return i(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const i=c+t;let s=a[n];function l(t){const r=this.opts.uriResolver.resolve;if(t=f(s?r(s,t):t),u.has(t))throw m(t);u.add(t);let o=this.refs[t];return"string"==typeof o&&(o=this.refs[o]),"object"==typeof o?h(e,o.schema,t):t!==f(i)&&("#"===t[0]?(h(e,d[t],t),d[t]=e):this.refs[t]=i),t}function g(e){if("string"==typeof e){if(!p.test(e))throw new Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[r]&&(s=l.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),a[t]=s}),d;function h(e,t,r){if(void 0!==t&&!n(e,t))throw m(r)}function m(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},60647:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(93716),n=r(36556),i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n.str`must match pattern "${e}"`,params:({schemaCode:e})=>n._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:i,schemaCode:s,it:a}=e,c=a.opts.unicodeRegExp?"u":"",d=r?n._`(new RegExp(${s}, ${c}))`:(0,o.usePattern)(e,i);e.fail$data(n._`!${d}.test(${t})`)}};t.default=i},61403:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(t.DiscrError=r={}))},62175:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthService=t.defaultSecretResolver=void 0,t.defaultSecretResolver={async resolveSecret(e){if("undefined"!=typeof process&&process.env)return process.env[e]}},t.OAuthService=class{config;constructor(e){this.config={configService:e.configService,fetchProvider:e.fetchProvider,agentShieldApiUrl:e.agentShieldApiUrl,agentShieldApiKey:e.agentShieldApiKey,projectId:e.projectId,logger:e.logger||(()=>{}),secretResolver:e.secretResolver||t.defaultSecretResolver}}async resolveClientSecret(e){if(e.metadata?.clientSecretName){const t=e.metadata.clientSecretName;this.config.logger("[OAuthService] Resolving client secret by name",{secretName:t,version:e.metadata.clientSecretVersion});const r=await this.config.secretResolver.resolveSecret(t);if(r)return this.config.logger("[OAuthService] Client secret resolved successfully",{secretName:t}),r;this.config.logger("[OAuthService] Client secret not found in secure storage",{secretName:t})}if(e.clientSecret)return this.config.logger("[OAuthService] DEPRECATED: Using legacy clientSecret field - migrate to metadata.clientSecretName for better security",{telemetry:{event:"oauth.deprecated_client_secret_used",hasMetadata:!!e.metadata,hasSecretName:!!e.metadata?.clientSecretName}}),e.clientSecret}async exchangeToken(e,t,r,o){const n=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];if(!n)throw new Error(`Provider "${e}" not configured for project "${this.config.projectId}"`);if(n.supportsPKCE&&!n.proxyMode){if(!r)throw new Error(`Provider "${e}" requires PKCE code_verifier for token exchange`);return this.exchangeTokenPKCE(n,t,r,o||"")}if(n.proxyMode)return this.exchangeTokenProxy(n,t,r,o||"");throw new Error(`Provider "${e}" configuration is invalid: must support PKCE or use proxy mode`)}async exchangeTokenPKCE(e,t,r,o){const n=await this.resolveClientSecret(e);this.config.logger("[OAuthService] Exchanging token with PKCE",{provider:e.authorizationUrl,tokenUrl:e.tokenUrl,hasClientSecret:!!n,resolvedViaSecretName:!!e.metadata?.clientSecretName});const i={grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e.clientId,code_verifier:r};n&&(i.client_secret=n);const s=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(i).toString()});if(!s.ok){const t=await s.text().catch(()=>"Unknown error");let r;try{r=JSON.parse(t)}catch{r={error:t}}const o=r.error_description||r.error||t;throw this.config.logger("[OAuthService] Token exchange failed",{status:s.status,error:o,provider:e.tokenUrl}),new Error(`Token exchange failed: ${o} (${s.status})`)}const a=await s.json();if(a.error)throw this.config.logger("[OAuthService] Token exchange returned error (200 status)",{error:a.error,errorDescription:a.error_description,errorUri:a.error_uri,provider:e.tokenUrl,responseKeys:Object.keys(a)}),new Error(`Token exchange failed: ${a.error_description||a.error}`);if(!a.access_token)throw this.config.logger("[OAuthService] Token response missing access_token",{responseKeys:Object.keys(a),provider:e.tokenUrl}),new Error("Token response missing access_token");const c=a.expires_in||3600,d=Date.now()+1e3*c,l={access_token:a.access_token,refresh_token:a.refresh_token,expires_in:c,expires_at:d,token_type:a.token_type||"Bearer",scope:a.scope};return this.config.logger("[OAuthService] Token exchange successful",{provider:e.tokenUrl,expiresAt:new Date(d).toISOString(),hasRefreshToken:!!l.refresh_token}),l}async exchangeTokenProxy(e,t,r,o){const n=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Exchanging token via proxy",{proxyUrl:n,provider:e.authorizationUrl,hasCodeVerifier:!!r,supportsPKCE:e.supportsPKCE});const i={grant_type:"authorization_code",code:t,redirect_uri:o||"",provider:e.authorizationUrl,project_id:this.config.projectId};e.supportsPKCE&&r&&(i.code_verifier=r);const s=await this.config.fetchProvider.fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify(i)});if(!s.ok){const e=await s.text().catch(()=>"Unknown error");let t;try{t=JSON.parse(e)}catch{t={error:e}}const r=t.error_description||t.error||e;throw this.config.logger("[OAuthService] Proxy token exchange failed",{status:s.status,error:r,proxyUrl:n}),new Error(`Proxy token exchange failed: ${r} (${s.status})`)}const a=await s.json(),c=a.data||a;if(!c.access_token)throw new Error("Proxy token response missing access_token");const d=c.expires_in||3600,l=Date.now()+1e3*d,u={access_token:c.access_token,refresh_token:c.refresh_token,expires_in:d,expires_at:l,token_type:c.token_type||"Bearer",scope:c.scope};return this.config.logger("[OAuthService] Proxy token exchange successful",{proxyUrl:n,expiresAt:new Date(l).toISOString(),hasRefreshToken:!!u.refresh_token}),u}async refreshToken(e,t){const r=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];return r?r.supportsPKCE&&!r.proxyMode?this.refreshTokenPKCE(r,t):r.proxyMode?this.refreshTokenProxy(r,t):null:(this.config.logger("[OAuthService] Provider not found for refresh",{provider:e}),null)}async refreshTokenPKCE(e,t){this.config.logger("[OAuthService] Refreshing token with PKCE",{provider:e.tokenUrl});try{const r=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId}).toString()});if(!r.ok)return this.config.logger("[OAuthService] Token refresh failed",{status:r.status,provider:e.tokenUrl}),null;const o=await r.json();if(!o.access_token)return this.config.logger("[OAuthService] Token refresh response missing access_token"),null;const n=o.expires_in||3600,i=Date.now()+1e3*n,s={access_token:o.access_token,refresh_token:o.refresh_token||t,expires_in:n,expires_at:i,token_type:o.token_type||"Bearer",scope:o.scope};return this.config.logger("[OAuthService] Token refresh successful",{provider:e.tokenUrl,expiresAt:new Date(i).toISOString()}),s}catch(t){return this.config.logger("[OAuthService] Token refresh error",{error:t instanceof Error?t.message:String(t),provider:e.tokenUrl}),null}}async refreshTokenProxy(e,t){const r=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Refreshing token via proxy",{proxyUrl:r,provider:e.authorizationUrl});try{const o=await this.config.fetchProvider.fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,provider:e.authorizationUrl,project_id:this.config.projectId})});if(!o.ok)return this.config.logger("[OAuthService] Proxy token refresh failed",{status:o.status,proxyUrl:r}),null;const n=await o.json(),i=n.data||n;if(!i.access_token)return this.config.logger("[OAuthService] Proxy token refresh response missing access_token"),null;const s=i.expires_in||3600,a=Date.now()+1e3*s,c={access_token:i.access_token,refresh_token:i.refresh_token||t,expires_in:s,expires_at:a,token_type:i.token_type||"Bearer",scope:i.scope};return this.config.logger("[OAuthService] Proxy token refresh successful",{proxyUrl:r,expiresAt:new Date(a).toISOString()}),c}catch(e){return this.config.logger("[OAuthService] Proxy token refresh error",{error:e instanceof Error?e.message:String(e),proxyUrl:r}),null}}}},62408:e=>{"use strict";e.exports=require("@kya-os/contracts")},62898:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>o.str`must match format "${e}"`,params:({schemaCode:e})=>o._`{format: ${e}}`},code(e,t){const{gen:r,data:n,$data:i,schema:s,schemaCode:a,it:c}=e,{opts:d,errSchemaPath:l,schemaEnv:u,self:h}=c;d.validateFormats&&(i?function(){const i=r.scopeValue("formats",{ref:h.formats,code:d.code.formats}),s=r.const("fDef",o._`${i}[${a}]`),c=r.let("fType"),l=r.let("format");r.if(o._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(c,o._`${s}.type || "string"`).assign(l,o._`${s}.validate`),()=>r.assign(c,o._`"string"`).assign(l,s)),e.fail$data((0,o.or)(!1===d.strictSchema?o.nil:o._`${a} && !${l}`,function(){const e=u.$async?o._`(${s}.async ? await ${l}(${n}) : ${l}(${n}))`:o._`${l}(${n})`,r=o._`(typeof ${l} == "function" ? ${e} : ${l}.test(${n}))`;return o._`${l} && ${l} !== true && ${c} === ${t} && !${r}`}()))}():function(){const i=h.formats[s];if(!i)return void function(){if(!1!==d.strictSchema)throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${l}"`}h.logger.warn(e())}();if(!0===i)return;const[a,c,f]=function(e){const t=e instanceof RegExp?(0,o.regexpCode)(e):d.code.formats?o._`${d.code.formats}${(0,o.getProperty)(s)}`:void 0,n=r.scopeValue("formats",{key:s,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,n]:[e.type||"string",e.validate,o._`${n}.validate`]}(i);a===t&&e.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!u.$async)throw new Error("async format in sync schema");return o._`await ${f}(${n})`}return"function"==typeof c?o._`${f}(${n})`:o._`${f}.test(${n})`}())}())}};t.default=n},63146:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEd25519DidKey=a,t.extractPublicKeyFromDidKey=c,t.publicKeyToJwk=d,t.createDidKeyResolver=function(){return{resolve:async e=>{if(!a(e))return null;const t=c(e);if(!t)return null;const r=d(t),o=e.replace("did:key:","");return{id:e,verificationMethod:[{id:`${e}#keys-1`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:o}],authentication:[`${e}#keys-1`],assertionMethod:[`${e}#keys-1`]}}}},t.resolveDidKeySync=function(e){if(!a(e))return null;const t=c(e);if(!t)return null;const r=d(t),o=e.replace("did:key:","");return{id:e,verificationMethod:[{id:`${e}#keys-1`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:o}],authentication:[`${e}#keys-1`],assertionMethod:[`${e}#keys-1`]}};const o=r(69459),n=r(98448),i=new Uint8Array([237,1]),s=32;function a(e){return e.startsWith("did:key:z6Mk")}function c(e){if(!e.startsWith("did:key:z"))return null;try{const t=e.replace("did:key:","").slice(1),r=(0,o.base58Decode)(t);return r.length<i.length+s||r[0]!==i[0]||r[1]!==i[1]?null:r.slice(i.length)}catch{return null}}function d(e){return{kty:"OKP",crv:"Ed25519",x:(0,n.base64urlEncodeFromBytes)(e)}}},63278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(28512),n={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:n}=e;if((0,o.alwaysValidSchema)(n,r))return void e.fail();const i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=n},63969:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=function e(t){if(null===t)return"null";if("boolean"==typeof t)return t.toString();if("number"==typeof t){if(!isFinite(t))throw new Error("Cannot canonicalize non-finite number");return JSON.stringify(t)}if("string"==typeof t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(t=>e(t)).join(",")+"]";if("object"==typeof t)return"{"+Object.keys(t).sort().map(r=>{const o=e(t[r]);return JSON.stringify(r)+":"+o}).join(",")+"}";throw new Error("Cannot canonicalize type: "+typeof t)},t.createUnsignedVCJWT=function(e,t={}){const r={alg:"EdDSA",typ:"JWT"};t.keyId&&(r.kid=t.keyId);const n="string"==typeof e.issuer?e.issuer:e.issuer?.id,i=e.credentialSubject?.id;let s,a;e.expirationDate&&"string"==typeof e.expirationDate&&(s=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(a=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const c={...e};delete c.proof;const d={iss:n,vc:c};i&&(d.sub=i),s&&(d.exp=s),a&&(d.iat=a),e.id&&"string"==typeof e.id&&(d.jti=e.id);const l=(0,o.base64urlEncodeFromString)(JSON.stringify(r)),u=(0,o.base64urlEncodeFromString)(JSON.stringify(d));return{header:r,payload:d,encodedHeader:l,encodedPayload:u,signingInput:`${l}.${u}`}},t.completeVCJWT=function(e,t){return`${e}.${t}`},t.parseVCJWT=function(e){const t=e.split(".");if(3!==t.length)return null;try{const e=n(t[0]),r=n(t[1]);return{header:JSON.parse(e),payload:JSON.parse(r),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}};const o=r(98448);function n(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return"undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("utf-8")}},64057:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(55579),n=r(19812),i=r(21378),s=r(60647),a=r(48079),c=r(9240),d=r(91128),l=r(81628),u=r(8762),h=r(25344),f=[o.default,n.default,i.default,s.default,a.default,c.default,d.default,l.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,h.default];t.default=f},65067:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserDidManager=void 0,t.UserDidManager=class{config;sessionDidCache=new Map;sessionKeyPairCache=new Map;constructor(e){this.config=e}async getKeyPairForSession(e,t){if(this.sessionKeyPairCache.has(e))return this.sessionKeyPairCache.get(e);if(t?.provider&&t?.subject&&this.config.storage?.getKeyPairByOAuth)try{const r=await this.config.storage.getKeyPairByOAuth(t.provider,t.subject);if(r)return this.sessionKeyPairCache.set(e,r),r}catch(e){console.warn("[UserDidManager] OAuth key pair lookup failed:",e)}if(this.config.storage?.getKeyPair)try{const t=await this.config.storage.getKeyPair(e);if(t)return this.sessionKeyPairCache.set(e,t),t}catch(e){console.warn("[UserDidManager] Session key pair lookup failed:",e)}return null}async getOrCreateUserDid(e,t){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(t&&t.provider&&t.subject&&this.config.storage?.getByOAuth)try{const r=await this.config.storage.getByOAuth(t.provider,t.subject);if(r){if(console.error("[UserDidManager] Found persistent user DID from OAuth mapping:",{provider:t.provider,userDid:r.substring(0,20)+"..."}),this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Failed to cache persistent DID in session storage:",e)}return r}}catch(e){console.warn("[UserDidManager] OAuth lookup failed, falling back to session storage:",e)}if(this.config.storage)try{const r=await this.config.storage.get(e);if(r){if(this.sessionDidCache.set(e,r),t&&t.provider&&t.subject&&this.config.storage.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.error("[UserDidManager] Created persistent OAuth mapping for existing user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}}catch(e){console.warn("[UserDidManager] Storage.get failed:",e)}return null}async setUserDidForSession(e,t,r){if(this.sessionDidCache.set(e,t),this.config.storage)try{await this.config.storage.set(e,t,1800)}catch(e){console.warn("[UserDidManager] Failed to store user DID in session storage:",e)}if(r?.provider&&r?.subject&&this.config.storage?.setByOAuth)try{await this.config.storage.setByOAuth(r.provider,r.subject,t,7776e3),console.error("[UserDidManager] Created OAuth → DID mapping:",{provider:r.provider,userDid:t.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}}async generateUserDid(){return(await this.generateUserDidWithKeyPair()).did}async generateUserDidWithKeyPair(){this.config.useDidWeb&&this.config.didWebBaseUrl&&console.warn("[UserDidManager] did:web not yet implemented, using did:key");const e=await this.config.crypto.generateKeyPair(),t=this.base64ToBytes(e.publicKey),r=this.generateDidKeyFromPublicKey(t),o=`${r}#keys-1`;return{did:r,publicKey:e.publicKey,privateKey:e.privateKey,keyId:o}}generateDidKeyFromPublicKey(e){const t=new Uint8Array([237,1]),r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),`did:key:z${this.base58Encode(r)}`}base58Encode(e){let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let r="";for(;t>0;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(t,"base64"));{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}}async getUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage){const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}return null}async clearUserDid(e){if(this.sessionDidCache.delete(e),this.config.storage)try{await this.config.storage.delete(e)}catch(e){console.warn("[UserDidManager] Storage.delete failed, continuing:",e)}}clearCache(){this.sessionDidCache.clear()}}},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var o,n,i;if(Array.isArray(t)){if((o=t.length)!=r.length)return!1;for(n=o;0!==n--;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((o=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(n=o;0!==n--;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=o;0!==n--;){var s=i[n];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r}},68252:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderResolver=t.CredentialAuthModeError=t.ConsentOnlyModeError=void 0;class r extends Error{toolProtection;constructor(e){super("Tool is configured for consent-only mode (no OAuth provider required)"),this.toolProtection=e,this.name="ConsentOnlyModeError"}}t.ConsentOnlyModeError=r;class o extends Error{toolProtection;provider;constructor(e,t){super(`Tool requires credential authentication with provider "${t}"`),this.toolProtection=e,this.name="CredentialAuthModeError",this.provider=t}}t.CredentialAuthModeError=o,t.ProviderResolver=class{registry;configService;constructor(e,t){this.registry=e,this.configService=t}isConsentOnlyMode(e){return"none"===e.authorization?.type}isCredentialAuthMode(e){return"password"===e.authorization?.type?{isCredential:!0,provider:e.authorization.provider||"credentials"}:{isCredential:!1}}async resolveProvider(e,t){if(this.isConsentOnlyMode(e))throw console.error("[ProviderResolver] Tool is consent-only mode (authorization.type=none), skipping OAuth resolution"),new r(e);const n=this.isCredentialAuthMode(e);if(n.isCredential)throw console.error(`[ProviderResolver] Tool requires credential auth (authorization.type=password), provider="${n.provider}"`),new o(e,n.provider);if(e.oauthProvider){if(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),!this.registry.hasProvider(e.oauthProvider))throw new Error(`Provider "${e.oauthProvider}" not configured for project "${t}". Add provider in project settings.`);return e.oauthProvider}const i=this.inferProviderFromScopes(e.requiredScopes||[]);if(i&&(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),this.registry.hasProvider(i)))return console.error(`[ProviderResolver] Inferred provider "${i}" from scopes`),i;await this.registry.loadFromAgentShield(t);const s=this.registry.getConfiguredProvider();if(s&&this.registry.hasProvider(s))return console.warn(`[ProviderResolver] Tool does not specify oauthProvider. Using project-configured provider "${s}" as fallback. Consider explicitly setting oauthProvider in tool protection config.`),s;throw new Error(`Tool requires OAuth but no provider is configured for project "${t}". Configure an OAuth provider in AgentShield dashboard.`)}inferProviderFromScopes(e){if(!e||0===e.length)return null;const t=e.map(e=>e.split(":")[0].toLowerCase()),r={github:"github",google:"google",gmail:"google",calendar:"google",microsoft:"microsoft",outlook:"microsoft",slack:"slack",auth0:"auth0",okta:"okta"},o=new Set(t.map(e=>r[e]).filter(Boolean));return 1===o.size?Array.from(o)[0]:null}}},69459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.base58Encode=function(e){if(0===e.length)return"";let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let o="";for(;t>0;)o=r[Number(t%BigInt(58))]+o,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)o="1"+o;return o},t.base58Decode=function(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const r of e){const e=o.get(r);if(void 0===e)throw new Error(`Invalid base58 character: ${r}`);t=t*BigInt(58)+BigInt(e)}const r=[];for(;t>0;)r.unshift(Number(t%BigInt(256))),t/=BigInt(256);let n=0;for(const t of e){if("1"!==t)break;n++}const i=new Uint8Array(n+r.length);return i.set(r,n),i},t.isValidBase58=function(e){if(0===e.length)return!0;for(const t of e)if(!o.has(t))return!1;return!0};const r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",o=new Map;for(let e=0;e<r.length;e++)o.set(r[e],e)},72114:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolContextBuilder=void 0;const o=r(27399),n=r(68252);t.ToolContextBuilder=class{config;constructor(e){this.config={tokenResolver:e.tokenResolver,configService:e.configService,providerResolver:e.providerResolver,projectId:e.projectId,logger:e.logger||(()=>{})}}async buildContext(e,t,r,i,s){if(!s?.requiredScopes?.length||!t)return;let a;try{a=await this.resolveProvider(s)}catch(r){if(r instanceof n.ConsentOnlyModeError||r instanceof n.CredentialAuthModeError)throw this.config.logger("[ToolContextBuilder] Special auth mode detected, re-throwing",{toolName:e,errorType:r.name,message:r.message}),r;return void this.config.logger("[ToolContextBuilder] Provider not resolved",{toolName:e,userDid:t.substring(0,20)+"...",error:r instanceof Error?r.message:String(r)})}const c=await this.config.tokenResolver.resolveTokenDataFromDid(t,a,s.requiredScopes);if(!c){if(i)return this.config.logger("[ToolContextBuilder] IDP token not found, but delegation exists - returning minimal context",{toolName:e,userDid:t.substring(0,20)+"...",provider:a,scopes:s.requiredScopes,note:"Tool can execute with delegation-only authorization"}),{provider:a,scopes:s.requiredScopes,userDid:t,sessionId:r,delegationToken:i};throw this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError",{toolName:e,userDid:t.substring(0,20)+"...",provider:a,scopes:s.requiredScopes}),new o.OAuthRequiredError({toolName:e,requiredScopes:s.requiredScopes,provider:a,oauthUrl:"",userDid:t,sessionId:r})}const d=this.buildAuthHeaders(c),l={idpToken:c.access_token,idpHeaders:d,provider:a,scopes:s.requiredScopes,userDid:t,sessionId:r,delegationToken:i,userId:c.userId};return this.config.logger("[ToolContextBuilder] Context built successfully",{toolName:e,userDid:t.substring(0,20)+"...",provider:a,hasToken:!!c.access_token,hasUserId:!!c.userId,tokenUsage:c.tokenUsage,headerKeys:Object.keys(d)}),l}buildAuthHeaders(e){const t={},r=e.tokenUsage||"bearer",o=e.access_token;switch(r){case"cookie":e.cookieFormat?t.Cookie=e.cookieFormat.replace(/\{\{token\}\}/g,o):t.Cookie=o;break;case"bearer":default:t.Authorization=`Bearer ${o}`;break;case"header":t[e.tokenHeader||"X-Session-Token"]=o}return e.apiHeaders&&Object.assign(t,e.apiHeaders),t}async resolveProvider(e){try{const t=await this.config.providerResolver.resolveProvider(e,this.config.projectId);return this.config.logger("[ToolContextBuilder] Provider resolved",{provider:t}),t}catch(e){throw this.config.logger("[ToolContextBuilder] Provider resolution failed",{error:e instanceof Error?e.message:String(e),projectId:this.config.projectId}),e}}}},74319:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const o=r(17285),n=r(8181),i=r(82278),s=r(37578),a=["/properties"],c="http://json-schema.org/draft-07/schema";class d extends o.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,c,!1),this.refs["http://json-schema.org/schema"]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}}t.Ajv=d,e.exports=t=d,e.exports.Ajv=d,Object.defineProperty(t,"__esModule",{value:!0}),t.default=d;var l=r(96889);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=r(36556);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=r(29645);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var f=r(218);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return f.default}})},75078:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?o.str`must contain at least ${e} valid item(s)`:o.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?o._`{minContains: ${e}}`:o._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:i,data:s,it:a}=e;let c,d;const{minContains:l,maxContains:u}=i;a.opts.next?(c=void 0===l?1:l,d=u):c=1;const h=t.const("len",o._`${s}.length`);if(e.setParams({min:c,max:d}),void 0===d&&0===c)return void(0,n.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==d&&c>d)return(0,n.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,n.alwaysValidSchema)(a,r)){let t=o._`${h} >= ${c}`;return void 0!==d&&(t=o._`${t} && ${h} <= ${d}`),void e.pass(t)}a.items=!0;const f=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);m(e,()=>t.if(e,()=>function(e){t.code(o._`${e}++`),void 0===d?t.if(o._`${e} >= ${c}`,()=>t.assign(f,!0).break()):(t.if(o._`${e} > ${d}`,()=>t.assign(f,!1).break()),1===c?t.assign(f,!0):t.if(o._`${e} >= ${c}`,()=>t.assign(f,!0)))}(r)))}function m(r,o){t.forRange("i",0,h,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:n.Type.Num,compositeRule:!0},r),o()})}void 0===d&&1===c?m(f,()=>t.if(f,()=>t.break())):0===c?(t.let(f,!0),void 0!==d&&t.if(o._`${s}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset())}};t.default=i},75306:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isValidDid=n,t.getDidMethod=function(e){if(!n(e))return null;const t=e.match(/^did:([^:]+):/);return t?t[1]:null},t.normalizeDid=i,t.compareDids=function(e,t){return i(e)===i(t)},t.getServerDid=function(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t},t.extractAgentId=s,t.extractAgentSlug=function(e){return s(e)},t.generateDidKeyFromBytes=c,t.generateDidKeyFromBase64=function(e){return c(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))};const o=r(69459);function n(e){return"string"==typeof e&&e.startsWith("did:")}function i(e){return e.trim()}function s(e){const t=e.split(":");return t[t.length-1]}const a=new Uint8Array([237,1]);function c(e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),`did:key:z${(0,o.base58Encode)(t)}`}},76899:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const o=r(36556),n=r(28512);function i(e,t,r){const{gen:i,compositeRule:s,data:a,opts:c}=e;if(void 0===r)return;const d=o._`${a}${(0,o.getProperty)(t)}`;if(s)return void(0,n.checkStrictMode)(e,`default is ignored for: ${d}`);let l=o._`${d} === undefined`;"empty"===c.useDefaults&&(l=o._`${l} || ${d} === null || ${d} === ""`),i.if(l,o._`${d} = ${(0,o.stringify)(r)}`)}t.assignDefaults=function(e,t){const{properties:r,items:o}=e.schema;if("object"===t&&r)for(const t in r)i(e,t,r[t].default);else"array"===t&&Array.isArray(o)&&o.forEach((t,r)=>i(e,r,t.default))}},77100:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const o=r(11175);class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var i;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(i||(t.UsedValueState=i={})),t.varKinds={const:new o.Name("const"),let:new o.Name("let"),var:new o.Name("var")};class s{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof o.Name?e:this.name(e)}name(e){return new o.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}t.Scope=s;class a extends o.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=o._`.${new o.Name(t)}[${r}]`}}t.ValueScopeName=a;const c=o._`\n`;t.ValueScope=class extends s{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:o.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const o=this.toName(e),{prefix:n}=o,i=null!==(r=t.key)&&void 0!==r?r:t.ref;let s=this._values[n];if(s){const e=s.get(i);if(e)return e}else s=this._values[n]=new Map;s.set(i,o);const a=this._scope[n]||(this._scope[n]=[]),c=a.length;return a[c]=t.ref,o.setValue(t,{property:n,itemIndex:c}),o}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw new Error(`CodeGen: name "${t}" has no value`);return o._`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,r,s={},a){let c=o.nil;for(const d in e){const l=e[d];if(!l)continue;const u=s[d]=s[d]||new Map;l.forEach(e=>{if(u.has(e))return;u.set(e,i.Started);let s=r(e);if(s){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;c=o._`${c}${r} ${e} = ${s};${this.opts._n}`}else{if(!(s=null==a?void 0:a(e)))throw new n(e);c=o._`${c}${s}${this.opts._n}`}u.set(e,i.Completed)})}return c}}},77311:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasMergedToolProtections=t.extractToolProtections=t.getToolProtection=t.fetchRemoteConfig=t.ProviderRuntimeConfigBuilder=void 0,t.createProviderRuntimeConfig=function(e,t){return(new o).withProviders(e).withEnvironment(t?.environment||"development").withSession(t?.session||{}).withIdentity(t?.identity||{enabled:!1,environment:"development"}).withProofing(t?.proofing||{enabled:!1}).withDelegation(t?.delegation||{enabled:!1,verifier:{type:"memory"}}).withAudit(t?.audit||{enabled:!1}).withWellKnown(t?.wellKnown||{enabled:!0}).build()};class o{config={environment:"development"};withProviders(e){return Object.assign(this.config,e),this}withEnvironment(e){return this.config.environment=e,this}withSession(e){return this.config.session=e,this}withIdentity(e){return this.config.identity=e,this}withProofing(e){return this.config.proofing=e,this}withDelegation(e){return this.config.delegation=e,this}withToolProtectionService(e){return this.config.toolProtectionService=e,this}withToolProtection(e){return this.config.toolProtection=e,this}withAudit(e){return this.config.audit=e,this}withWellKnown(e){return this.config.wellKnown=e,this}build(){const e=["cryptoProvider","clockProvider","fetchProvider","storageProvider","nonceCacheProvider","identityProvider"];for(const t of e)if(!(t in this.config))throw new Error(`Missing required provider: ${t}`);return{environment:"development",session:{timestampSkewSeconds:120,ttlMinutes:30},...this.config}}}t.ProviderRuntimeConfigBuilder=o;var n=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return n.fetchRemoteConfig}}),Object.defineProperty(t,"getToolProtection",{enumerable:!0,get:function(){return n.getToolProtection}}),Object.defineProperty(t,"extractToolProtections",{enumerable:!0,get:function(){return n.extractToolProtections}}),Object.defineProperty(t,"hasMergedToolProtections",{enumerable:!0,get:function(){return n.hasMergedToolProtections}})},77460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialVerifier=void 0,t.createDelegationVerifier=function(e){return new n(e)};const o=r(62408);class n{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheTtl;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const o=Date.now(),n=this.validateBasicProperties(e),i=Date.now()-o;if(!n.valid)return{valid:!1,reason:n.reason,stage:"basic",metrics:{basicCheckMs:i,totalMs:Date.now()-r},checks:{basicValid:!1}};const s=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),a=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([s,a]),l=c.durationMs||0,u=d.durationMs||0,h=n.valid&&c.valid&&d.valid,f={valid:h,reason:h?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:i,signatureCheckMs:l,statusCheckMs:u,totalMs:Date.now()-r},checks:{basicValid:n.valid,signatureValid:c.valid,statusValid:d.valid}};return f.valid&&e.id&&this.setInCache(e.id,f),f}validateBasicProperties(e){const t=(0,o.validateDelegationCredential)(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error.message}`};if((0,o.isDelegationCredentialExpired)(e))return{valid:!1,reason:"Delegation credential expired"};if((0,o.isDelegationCredentialNotYetValid)(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;return"revoked"===r.status?{valid:!1,reason:"Delegation status is revoked"}:"expired"===r.status?{valid:!1,reason:"Delegation status is expired"}:r.issuerDid&&r.subjectDid?e.proof?{valid:!0}:{valid:!1,reason:"Missing proof"}:{valid:!1,reason:"Missing issuer or subject DID"}}async verifySignature(e,t){const r=Date.now();try{const o="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!0,reason:"No DID resolver or signature verifier available, skipping signature verification",durationMs:Date.now()-r};const n=await t.resolve(o);if(!n)return{valid:!1,reason:`Could not resolve issuer DID: ${o}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const i=e.proof.verificationMethod;if(!i)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const s=this.findVerificationMethod(n,i);if(!s)return{valid:!1,reason:`Verification method ${i} not found`,durationMs:Date.now()-r};const a=s.publicKeyJwk;if(!a)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,a);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!0,reason:"No status list resolver available, skipping status check",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl})}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}t.DelegationCredentialVerifier=n},77753:(e,t,r)=>{"use strict";r.d(t,{d:()=>n});var o=r(10985);function n(e,t){return(0,o.S)(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}},78322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationErrorFormatter=void 0,t.createDelegationErrorFormatter=function(e){return new o(e)};const r={message:"Authorization required.\n\n[Authorize {toolName}]({consentUrl})\n\nRetry after authorizing.",noUrlMessage:'Authorization required for "{toolName}" but no consent URL is available.\n\nPlease contact the administrator to configure delegation for this tool.',oauthMessage:"Authorization required.\n\n[Sign in with {provider}]({oauthUrl})\n\nRetry after authorizing.",noOAuthUrlMessage:'Authorization required for "{toolName}" but no {provider} URL is available.\n\nPlease contact the administrator to configure OAuth for this tool.',supportsMarkdown:!0};class o{config;constructor(e){this.config=e}setConfig(e){this.config=e}format(e){const{toolName:t,consentUrl:o,scopes:n,clientId:i}=e,s=this.getTemplate(i),a=this.buildUrl(o,s);let c;if(a){const e=s.message??r.message;c=this.interpolate(e,{toolName:t,consentUrl:a,scopes:n?.join(", ")??""}),!1===s.supportsMarkdown&&(c=this.stripMarkdownLinks(c))}else{const e=s.noUrlMessage??r.noUrlMessage;c=this.interpolate(e,{toolName:t,consentUrl:"",scopes:n?.join(", ")??""})}return{message:c,consentUrl:a}}formatOAuth(e){const{toolName:t,oauthUrl:o,provider:n="OAuth",scopes:i,clientId:s}=e,a=this.getTemplate(s),c=this.buildUrl(o,a);let d;if(c){const e=a.oauthMessage??r.oauthMessage;d=this.interpolate(e,{toolName:t,oauthUrl:c,provider:n,scopes:i?.join(", ")??""}),!1===a.supportsMarkdown&&(d=this.stripMarkdownLinks(d))}else{const e=a.noOAuthUrlMessage??r.noOAuthUrlMessage;d=this.interpolate(e,{toolName:t,oauthUrl:"",provider:n,scopes:i?.join(", ")??""})}return{message:d,oauthUrl:c}}getTemplate(e){const t=this.config?.default??{};return e&&this.config?.clients?.[e]?{...r,...t,...this.config.clients[e]}:{...r,...t}}buildUrl(e,t){if(e){if(!t.extraParams||0===Object.keys(t.extraParams).length)return e;try{const r=new URL(e);for(const[e,o]of Object.entries(t.extraParams))r.searchParams.set(e,o);return r.toString()}catch{return e}}}interpolate(e,t){let r=e;for(const[e,o]of Object.entries(t))r=r.replace(new RegExp(`\\{${e}\\}`,"g"),()=>o);return r}stripMarkdownLinks(e){return e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1: $2")}}t.DelegationErrorFormatter=o},79135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const o=r(36556),n=r(28512),i=r(93716),s={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return a(e,"additionalItems",t);r.items=!0,(0,n.alwaysValidSchema)(r,t)||e.ok((0,i.validateArray)(e))}};function a(e,t,r=e.schema){const{gen:i,parentSchema:s,data:a,keyword:c,it:d}=e;!function(e){const{opts:o,errSchemaPath:i}=d,s=r.length,a=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(o.strictTuples&&!a){const e=`"${c}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${i}"`;(0,n.checkStrictMode)(d,e,o.strictTuples)}}(s),d.opts.unevaluated&&r.length&&!0!==d.items&&(d.items=n.mergeEvaluated.items(i,r.length,d.items));const l=i.name("valid"),u=i.const("len",o._`${a}.length`);r.forEach((t,r)=>{(0,n.alwaysValidSchema)(d,t)||(i.if(o._`${u} > ${r}`,()=>e.subschema({keyword:c,schemaProp:r,dataProp:r},l)),e.ok(l))})}t.validateTuple=a,t.default=s},81296:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoService=void 0;const o=r(98448);t.CryptoService=class{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return console.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,n,i]=t;let s,a,c;try{s=JSON.parse((0,o.base64urlDecodeToString)(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(n)try{a=JSON.parse((0,o.base64urlDecodeToString)(n))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{c=(0,o.base64urlDecodeToBytes)(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:s,payload:a,signatureBytes:c,signingInput:`${r}.${n}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return console.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return console.error("[CryptoService] Key ID mismatch"),!1;let n;try{n=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return console.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return console.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];n={header:JSON.parse((0,o.base64urlDecodeToString)(e)),payload:void 0,signatureBytes:(0,o.base64urlDecodeToBytes)(t),signingInput:""}}catch{return console.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=r?.alg||"EdDSA";if(n.header.alg!==i)return console.error(`[CryptoService] Unsupported algorithm: ${n.header.alg}, expected ${i}`),!1;let s,a,c;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let n;n=r.detachedPayload instanceof Uint8Array?(0,o.base64urlEncodeFromBytes)(r.detachedPayload):(0,o.base64urlEncodeFromBytes)((new TextEncoder).encode(r.detachedPayload)),s=`${t}.${n}`,a=(new TextEncoder).encode(s)}else{if(!n.signingInput)return console.error("[CryptoService] Missing signing input for compact JWS"),!1;s=n.signingInput,a=(new TextEncoder).encode(s)}try{c=this.jwkToBase64PublicKey(t)}catch(e){return console.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(a,n.signatureBytes,c)}catch(e){return console.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=(0,o.base64urlDecodeToBytes)(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return(0,o.bytesToBase64)(t)}}},81628:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(54029),n=r(36556),i=r(28512),s=r(56935),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>n.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>n._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:a,schema:c,parentSchema:d,schemaCode:l,it:u}=e;if(!a&&!c)return;const h=t.let("valid"),f=d.items?(0,o.getSchemaTypes)(d.items):[];function p(i,s){const a=t.name("item"),c=(0,o.checkDataTypes)(f,a,u.opts.strictNumbers,o.DataType.Wrong),d=t.const("indices",n._`{}`);t.for(n._`;${i}--;`,()=>{t.let(a,n._`${r}[${i}]`),t.if(c,n._`continue`),f.length>1&&t.if(n._`typeof ${a} == "string"`,n._`${a} += "_"`),t.if(n._`typeof ${d}[${a}] == "number"`,()=>{t.assign(s,n._`${d}[${a}]`),e.error(),t.assign(h,!1).break()}).code(n._`${d}[${a}] = ${i}`)})}function m(o,a){const c=(0,i.useFunc)(t,s.default),d=t.name("outer");t.label(d).for(n._`;${o}--;`,()=>t.for(n._`${a} = ${o}; ${a}--;`,()=>t.if(n._`${c}(${r}[${o}], ${r}[${a}])`,()=>{e.error(),t.assign(h,!1).break(d)})))}e.block$data(h,function(){const o=t.let("i",n._`${r}.length`),i=t.let("j");e.setParams({i:o,j:i}),t.assign(h,!0),t.if(n._`${o} > 1`,()=>(f.length>0&&!f.some(e=>"object"===e||"array"===e)?p:m)(o,i))},n._`${l} === false`),e.ok(h)}};t.default=a},82200:e=>{"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},82278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(61403),i=r(9198),s=r(218),a=r(28512),c={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>o._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:c,parentSchema:d,it:l}=e,{oneOf:u}=d;if(!l.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const f=t.let("valid",!1),p=t.const("tag",o._`${r}${(0,o.getProperty)(h)}`);function m(r){const n=t.name("valid"),i=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(i,o.Name),n}t.if(o._`typeof ${p} == "string"`,()=>function(){const r=function(){var e;const t={},r=n(d);let o=!0;for(let t=0;t<u.length;t++){let d=u[t];if((null==d?void 0:d.$ref)&&!(0,a.schemaHasRulesButRef)(d,l.self.RULES)){const e=d.$ref;if(d=i.resolveRef.call(l.self,l.schemaEnv.root,l.baseId,e),d instanceof i.SchemaEnv&&(d=d.schema),void 0===d)throw new s.default(l.opts.uriResolver,l.baseId,e)}const f=null===(e=null==d?void 0:d.properties)||void 0===e?void 0:e[h];if("object"!=typeof f)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);o=o&&(r||n(d)),c(f,t)}if(!o)throw new Error(`discriminator: "${h}" must be required`);return t;function n({required:e}){return Array.isArray(e)&&e.includes(h)}function c(e,t){if(e.const)f(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const r of e.enum)f(r,t)}}function f(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(o._`${p} === ${e}`),t.assign(f,m(r[e]));t.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:p,tagName:h}),t.endIf()}(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:p,tagName:h})),e.ok(f)}};t.default=c},82811:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=async function(e,t){const{apiUrl:r,apiKey:n,projectId:i,agentDid:s,cacheTtl:a=3e5,fetchProvider:c}=e,d=i?`config:project:${i}`:s?`config:agent:${s}`:null;if(t&&d)try{const e=await t.get(d);if(e)try{const t=JSON.parse(e);if(t.expiresAt>Date.now())return t.config}catch{}}catch(e){console.warn("[RemoteConfig] Cache read failed:",e)}try{if(!i)return console.error("[RemoteConfig] projectId is required for user-scoped delegation. Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). Please configure AGENTSHIELD_PROJECT_ID environment variable."),null;const e=`${r}${o.AGENTSHIELD_ENDPOINTS.CONFIG(i)}`,s=await c(e,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}});if(!s.ok)return console.warn(`[RemoteConfig] API returned ${s.status}: ${s.statusText}`),null;const l=await s.json(),u=l.config||l.data?.config||(l.success?l.data:null);if(!u)return console.warn("[RemoteConfig] No config found in API response"),null;if(t&&d)try{await t.set(d,JSON.stringify({config:u,expiresAt:Date.now()+a}),a)}catch(e){console.warn("[RemoteConfig] Cache write failed:",e)}return u}catch(e){return console.warn("[RemoteConfig] Failed to fetch config:",e),null}},t.getToolProtection=function(e,t){const r=e?.toolProtection?.tools;if(!r)return null;let o=r[t];return!o&&r["*"]&&(o=r["*"]),o&&o.requiresDelegation?o:null},t.extractToolProtections=function(e){return e?.toolProtection?.tools?e.toolProtection.tools:{}},t.hasMergedToolProtections=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return void 0!==t.toolProtection&&"object"==typeof t.toolProtection&&null!==t.toolProtection&&"tools"in t.toolProtection&&"object"==typeof t.toolProtection.tools&&null!==t.toolProtection.tools},t.getPolicy=i,t.extractPolicy=function(e){return e?.policy?e.policy:structuredClone(n.DEFAULT_POLICY_CONFIG)},t.hasMergedPolicy=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return void 0!==t.policy&&"object"==typeof t.policy&&null!==t.policy},t.isPolicyEnabled=function(e){const t=i(e);return t?.enabled??!0};const o=r(82906),n=r(62408);function i(e){return e?.policy?e.policy:null}},82906:e=>{"use strict";e.exports=require("@kya-os/contracts/agentshield-api")},84204:(e,t)=>{"use strict";function r(e,t){return t.rules.some(t=>o(e,t))}function o(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:e,self:t},o){const n=t.RULES.types[o];return n&&!0!==n&&r(e,n)},t.shouldUseGroup=r,t.shouldUseRule=o},85601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=void 0,t.InMemoryToolProtectionCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const o=Date.now()+r;this.cache.set(e,{value:t,expiresAt:o})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expiresAt&&this.cache.delete(t)}getStale(e){const t=this.cache.get(e);return t?t.value:null}getExpiresAt(e){const t=this.cache.get(e);return t?t.expiresAt:null}},t.NoOpToolProtectionCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},86464:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},86587:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.createDefaultConsoleLogger=o;const r={debug:10,info:20,warn:30,error:40};function o(){let e="info",t=!1;function o(o,...n){if(function(t){return r[t]>=r[e]}(o))if(t)console.error(...n);else switch(o){case"debug":"function"==typeof console.debug?console.debug(...n):console.log(...n);break;case"info":"function"==typeof console.info?console.info(...n):console.log(...n);break;case"warn":"function"==typeof console.warn?console.warn(...n):console.error(...n);break;case"error":console.error(...n)}}return{configure(r={}){r.level&&(e=r.level),!0===r.forceStderr?t=!0:!1===r.forceStderr?t=!1:"stdio"===r.transport?t=!0:"sse"!==r.transport&&"http"!==r.transport||(t=!1)},debug:(...e)=>o("debug",...e),info:(...e)=>o("info",...e),warn:(...e)=>o("warn",...e),error:(...e)=>o("error",...e)}}t.logger=o()},87394:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const o=r(36556),n=r(28512),i=r(93716);t.error={message:({params:{property:e,depsCount:t,deps:r}})=>{const n=1===t?"property":"properties";return o.str`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>o._`{property: ${e},
5
- missingProperty: ${n},
1
+ (()=>{var e={202:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdpTokenResolver=void 0,t.IdpTokenResolver=class{config;constructor(e){this.config={tokenStorage:e.tokenStorage,oauthService:e.oauthService,logger:e.logger||(()=>{})}}async resolveTokenFromDid(e,t,r){const n=await this.resolveTokenDataFromDid(e,t,r);return n?.access_token??null}async resolveTokenDataFromDid(e,t,r){const n=await this.config.tokenStorage.getToken(e,t,r);if(!n)return this.config.logger("[IdpTokenResolver] Token not found",{userDid:e.substring(0,20)+"...",provider:t,scopes:r}),null;const i=Date.now();if(n.expires_at<i){if(this.config.logger("[IdpTokenResolver] Token expired, attempting refresh",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(n.expires_at).toISOString(),hasRefreshToken:!!n.refresh_token}),n.refresh_token){const i=await this.config.oauthService.refreshToken(t,n.refresh_token);if(i){const o={...i,tokenUsage:n.tokenUsage,tokenHeader:n.tokenHeader,cookieFormat:n.cookieFormat,apiHeaders:n.apiHeaders};return await this.config.tokenStorage.storeToken(e,t,r,o),this.config.logger("[IdpTokenResolver] Token refreshed successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(i.expires_at).toISOString()}),o}return this.config.logger("[IdpTokenResolver] Token refresh failed",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token expired and no refresh token",{userDid:e.substring(0,20)+"...",provider:t}),null}return this.config.logger("[IdpTokenResolver] Token resolved successfully",{userDid:e.substring(0,20)+"...",provider:t,expiresAt:new Date(n.expires_at).toISOString(),tokenUsage:n.tokenUsage}),n}}},238:(e,t)=>{"use strict";function r(e,t){return t.rules.some(t=>n(e,t))}function n(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:e,self:t},n){const i=t.RULES.types[n];return i&&!0!==i&&r(e,i)},t.shouldUseGroup=r,t.shouldUseRule=n},689:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodeProtectedHeader=function(e){let t;if("string"==typeof e){const r=e.split(".");3!==r.length&&5!==r.length||([t]=r)}else if("object"==typeof e&&e){if(!("protected"in e))throw new TypeError("Token does not contain a Protected Header");t=e.protected}try{if("string"!=typeof t||!t)throw new Error;const e=JSON.parse(i.decoder.decode((0,n.decode)(t)));if(!(0,o.default)(e))throw new Error;return e}catch{throw new TypeError("Invalid Token or Protected Header formatting")}};const n=r(7300),i=r(45935),o=r(71661)},3051:e=>{"use strict";e.exports=require("@kya-os/contracts/runtime")},3508:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=t.encodeBase64=t.decodeBase64=void 0;const n=r(4573),i=r(45935);t.encode=e=>n.Buffer.from(e).toString("base64url"),t.decodeBase64=e=>new Uint8Array(n.Buffer.from(e,"base64")),t.encodeBase64=e=>n.Buffer.from(e).toString("base64"),t.decode=e=>new Uint8Array(n.Buffer.from(function(e){let t=e;return t instanceof Uint8Array&&(t=i.decoder.decode(t)),t}(e),"base64url"))},3826:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const n=r(38994),i=r(67218);t.getSubschema=function(e,{keyword:t,schemaProp:r,schema:o,schemaPath:a,errSchemaPath:s,topSchemaRef:c}){if(void 0!==t&&void 0!==o)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const o=e.schema[t];return void 0===r?{schema:o,schemaPath:n._`${e.schemaPath}${(0,n.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:o[r],schemaPath:n._`${e.schemaPath}${(0,n.getProperty)(t)}${(0,n.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,i.escapeFragment)(r)}`}}if(void 0!==o){if(void 0===a||void 0===s||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:a,topSchemaRef:c,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:r,dataPropType:o,data:a,dataTypes:s,propertyName:c}){if(void 0!==a&&void 0!==r)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=t;if(void 0!==r){const{errorPath:a,dataPathArr:s,opts:c}=t;d(u.let("data",n._`${t.data}${(0,n.getProperty)(r)}`,!0)),e.errorPath=n.str`${a}${(0,i.getErrorPath)(r,o,c.jsPropertySyntax)}`,e.parentDataProperty=n._`${r}`,e.dataPathArr=[...s,e.parentDataProperty]}function d(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}void 0!==a&&(d(a instanceof n.Name?a:u.let("data",a,!0)),void 0!==c&&(e.propertyName=c)),s&&(e.dataTypes=s)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){void 0!==n&&(e.compositeRule=n),void 0!==i&&(e.createErrors=i),void 0!==o&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}},4220:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(89008);class i extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,n.resolveUrl)(e,t,r),this.missingSchema=(0,n.normalizeId)((0,n.getFullPath)(e,this.missingRef))}}t.default=i},4268:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598);let i;t.default=e=>(i||=new Set((0,n.getCiphers)()),i.has(e))},4283:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cryptoRuntime=t.base64url=t.generateSecret=t.generateKeyPair=t.errors=t.decodeJwt=t.decodeProtectedHeader=t.importJWK=t.importX509=t.importPKCS8=t.importSPKI=t.exportJWK=t.exportSPKI=t.exportPKCS8=t.UnsecuredJWT=t.experimental_jwksCache=t.jwksCache=t.createRemoteJWKSet=t.createLocalJWKSet=t.EmbeddedJWK=t.calculateJwkThumbprintUri=t.calculateJwkThumbprint=t.EncryptJWT=t.SignJWT=t.GeneralSign=t.FlattenedSign=t.CompactSign=t.FlattenedEncrypt=t.CompactEncrypt=t.jwtDecrypt=t.jwtVerify=t.generalVerify=t.flattenedVerify=t.compactVerify=t.GeneralEncrypt=t.generalDecrypt=t.flattenedDecrypt=t.compactDecrypt=void 0;var n=r(58621);Object.defineProperty(t,"compactDecrypt",{enumerable:!0,get:function(){return n.compactDecrypt}});var i=r(70331);Object.defineProperty(t,"flattenedDecrypt",{enumerable:!0,get:function(){return i.flattenedDecrypt}});var o=r(54992);Object.defineProperty(t,"generalDecrypt",{enumerable:!0,get:function(){return o.generalDecrypt}});var a=r(74372);Object.defineProperty(t,"GeneralEncrypt",{enumerable:!0,get:function(){return a.GeneralEncrypt}});var s=r(39409);Object.defineProperty(t,"compactVerify",{enumerable:!0,get:function(){return s.compactVerify}});var c=r(55403);Object.defineProperty(t,"flattenedVerify",{enumerable:!0,get:function(){return c.flattenedVerify}});var u=r(14186);Object.defineProperty(t,"generalVerify",{enumerable:!0,get:function(){return u.generalVerify}});var d=r(12556);Object.defineProperty(t,"jwtVerify",{enumerable:!0,get:function(){return d.jwtVerify}});var l=r(60808);Object.defineProperty(t,"jwtDecrypt",{enumerable:!0,get:function(){return l.jwtDecrypt}});var p=r(30005);Object.defineProperty(t,"CompactEncrypt",{enumerable:!0,get:function(){return p.CompactEncrypt}});var f=r(92599);Object.defineProperty(t,"FlattenedEncrypt",{enumerable:!0,get:function(){return f.FlattenedEncrypt}});var h=r(15497);Object.defineProperty(t,"CompactSign",{enumerable:!0,get:function(){return h.CompactSign}});var m=r(30131);Object.defineProperty(t,"FlattenedSign",{enumerable:!0,get:function(){return m.FlattenedSign}});var g=r(61494);Object.defineProperty(t,"GeneralSign",{enumerable:!0,get:function(){return g.GeneralSign}});var v=r(71016);Object.defineProperty(t,"SignJWT",{enumerable:!0,get:function(){return v.SignJWT}});var y=r(31276);Object.defineProperty(t,"EncryptJWT",{enumerable:!0,get:function(){return y.EncryptJWT}});var _=r(33645);Object.defineProperty(t,"calculateJwkThumbprint",{enumerable:!0,get:function(){return _.calculateJwkThumbprint}}),Object.defineProperty(t,"calculateJwkThumbprintUri",{enumerable:!0,get:function(){return _.calculateJwkThumbprintUri}});var b=r(88660);Object.defineProperty(t,"EmbeddedJWK",{enumerable:!0,get:function(){return b.EmbeddedJWK}});var w=r(22562);Object.defineProperty(t,"createLocalJWKSet",{enumerable:!0,get:function(){return w.createLocalJWKSet}});var $=r(84559);Object.defineProperty(t,"createRemoteJWKSet",{enumerable:!0,get:function(){return $.createRemoteJWKSet}}),Object.defineProperty(t,"jwksCache",{enumerable:!0,get:function(){return $.jwksCache}}),Object.defineProperty(t,"experimental_jwksCache",{enumerable:!0,get:function(){return $.experimental_jwksCache}});var S=r(58459);Object.defineProperty(t,"UnsecuredJWT",{enumerable:!0,get:function(){return S.UnsecuredJWT}});var k=r(72545);Object.defineProperty(t,"exportPKCS8",{enumerable:!0,get:function(){return k.exportPKCS8}}),Object.defineProperty(t,"exportSPKI",{enumerable:!0,get:function(){return k.exportSPKI}}),Object.defineProperty(t,"exportJWK",{enumerable:!0,get:function(){return k.exportJWK}});var I=r(68846);Object.defineProperty(t,"importSPKI",{enumerable:!0,get:function(){return I.importSPKI}}),Object.defineProperty(t,"importPKCS8",{enumerable:!0,get:function(){return I.importPKCS8}}),Object.defineProperty(t,"importX509",{enumerable:!0,get:function(){return I.importX509}}),Object.defineProperty(t,"importJWK",{enumerable:!0,get:function(){return I.importJWK}});var P=r(689);Object.defineProperty(t,"decodeProtectedHeader",{enumerable:!0,get:function(){return P.decodeProtectedHeader}});var E=r(74218);Object.defineProperty(t,"decodeJwt",{enumerable:!0,get:function(){return E.decodeJwt}}),t.errors=r(39069);var x=r(14339);Object.defineProperty(t,"generateKeyPair",{enumerable:!0,get:function(){return x.generateKeyPair}});var O=r(88915);Object.defineProperty(t,"generateSecret",{enumerable:!0,get:function(){return O.generateSecret}}),t.base64url=r(7300);var T=r(55116);Object.defineProperty(t,"cryptoRuntime",{enumerable:!0,get:function(){return T.default}})},4573:e=>{"use strict";e.exports=require("node:buffer")},4901:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionServiceError=t.DelegationRequiredError=void 0;class r extends Error{toolName;requiredScopes;consentUrl;resumeToken;interceptedCall;constructor(e,t,r,n,i){super(`Delegation required for tool "${e}"`),this.toolName=e,this.requiredScopes=t,this.consentUrl=r,this.name="DelegationRequiredError",this.interceptedCall=n,this.resumeToken=i}}t.DelegationRequiredError=r;class n extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ToolProtectionServiceError"}}t.ToolProtectionServiceError=n},5019:(e,t,r)=>{"use strict";const{normalizeIPv6:n,removeDotSegments:i,recomposeAuthority:o,normalizeComponentEncoding:a,isIPv4:s,nonSimpleDomain:c}=r(96214),{SCHEMES:u,getSchemeHandler:d}=r(99147);function l(e,t,r,n){const o={};return n||(e=h(p(e,r),r),t=h(p(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=i(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=i(t.path||""),o.query=t.query):(t.path?("/"===t.path[0]?o.path=i(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=i(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function p(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],s=d(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),void 0!==r.path&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==n.reference&&r.scheme&&a.push(r.scheme,":");const c=o(r);if(void 0!==c&&("suffix"!==n.reference&&a.push("//"),a.push(c),r.path&&"/"!==r.path[0]&&a.push("/")),void 0!==r.path){let e=r.path;n.absolutePath||s&&s.absolutePath||(e=i(e)),void 0===c&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),a.push(e)}return void 0!==r.query&&a.push("?",r.query),void 0!==r.fragment&&a.push("#",r.fragment),a.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(e,t){const r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const a=e.match(f);if(a){if(i.scheme=a[1],i.userinfo=a[3],i.host=a[4],i.port=parseInt(a[5],10),i.path=a[6]||"",i.query=a[7],i.fragment=a[8],isNaN(i.port)&&(i.port=a[5]),i.host)if(!1===s(i.host)){const e=n(i.host);i.host=e.host.toLowerCase(),o=e.isIPV6}else o=!0;void 0!==i.scheme||void 0!==i.userinfo||void 0!==i.host||void 0!==i.port||void 0!==i.query||i.path?void 0===i.scheme?i.reference="relative":void 0===i.fragment?i.reference="absolute":i.reference="uri":i.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==i.reference&&(i.error=i.error||"URI is not a "+r.reference+" reference.");const t=d(r.scheme||i.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&!1===o&&c(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==i.scheme&&(i.scheme=unescape(i.scheme)),void 0!==i.host&&(i.host=unescape(i.host))),i.path&&(i.path=escape(unescape(i.path))),i.fragment&&(i.fragment=encodeURI(decodeURIComponent(i.fragment)))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}const m={SCHEMES:u,normalize:function(e,t){return"string"==typeof e?e=p(h(e,t),t):"object"==typeof e&&(e=h(p(e,t),t)),e},resolve:function(e,t,r){const n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=l(h(e,n),h(t,n),n,!0);return n.skipEscape=!0,p(i,n)},resolveComponent:l,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=p(a(h(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=p(a(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=p(a(h(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=p(a(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:p,parse:h};e.exports=m,e.exports.default=m,e.exports.fastUri=m},5153:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o=r(24954),a=r(30714),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>n.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>n._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:s}=r;n.items=!0,(0,i.alwaysValidSchema)(n,t)||(s?(0,a.validateAdditionalItems)(e,s):e.ok((0,o.validateArray)(e)))}};t.default=s},5368:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>n._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:r,parentSchema:o,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&o.discriminator)return;const s=r,c=t.let("valid",!1),u=t.let("passing",null),d=t.name("_valid");e.setParams({passing:u}),t.block(function(){s.forEach((r,o)=>{let s;(0,i.alwaysValidSchema)(a,r)?t.var(d,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},d),o>0&&t.if(n._`${d} && ${c}`).assign(c,!1).assign(u,n._`[${u}, ${o}]`).else(),t.if(d,()=>{t.assign(c,!0),t.assign(u,o),s&&e.mergeEvaluated(s,n.Name)})})}),e.result(c,()=>e.reset(),()=>e.error(!0))}};t.default=o},5888:(e,t)=>{"use strict";function r(e,t){return{validate:e,compare:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(o,a),time:r(c(!0),u),"date-time":r(p(!0),f),"iso-time":r(c(),d),"iso-date-time":r(p(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&g.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return v.lastIndex=0,v.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=_&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:b},double:{type:"number",validate:b},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,d),"iso-date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,h),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(e){const t=n.exec(e);if(!t)return!1;const r=+t[1],o=+t[2],a=+t[3];return o>=1&&o<=12&&a>=1&&a<=(2===o&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:i[o])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){const r=s.exec(t);if(!r)return!1;const n=+r[1],i=+r[2],o=+r[3],a=r[4],c="-"===r[5]?-1:1,u=+(r[6]||0),d=+(r[7]||0);if(u>23||d>59||e&&!a)return!1;if(n<=23&&i<=59&&o<60)return!0;const l=i-d*c,p=n-u*c-(l<0?1:0);return(23===p||-1===p)&&(59===l||-1===l)&&o<61}}function u(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();return r&&n?r-n:void 0}function d(e,t){if(!e||!t)return;const r=s.exec(e),n=s.exec(t);return r&&n?(e=r[1]+r[2]+r[3])>(t=n[1]+n[2]+n[3])?1:e<t?-1:0:void 0}const l=/t|\s/i;function p(e){const t=c(e);return function(e){const r=e.split(l);return 2===r.length&&o(r[0])&&t(r[1])}}function f(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),n=new Date(t).valueOf();return r&&n?r-n:void 0}function h(e,t){if(!e||!t)return;const[r,n]=e.split(l),[i,o]=t.split(l),s=a(r,i);return void 0!==s?s||u(n,o):void 0}const m=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-(2**31),_=2**31-1;function b(){return!0}const w=/[^\\]\\Z/},6013:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(67371);n.code='require("ajv/dist/runtime/equal").default',t.default=n},6093:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrap=async function(e,t,r,i){const a=e.slice(0,7),s=await(0,n.default)(a,r,t,i,new Uint8Array(0));return{encryptedKey:s.ciphertext,iv:(0,o.encode)(s.iv),tag:(0,o.encode)(s.tag)}},t.unwrap=async function(e,t,r,n,o){const a=e.slice(0,7);return(0,i.default)(a,t,r,n,o,new Uint8Array(0))};const n=r(19265),i=r(44089),o=r(3508)},6247:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}},7300:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0;const n=r(3508);t.encode=n.encode,t.decode=n.decode},7318:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStatusListStorage=void 0,t.MemoryStatusListStorage=class{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}},7456:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')},7673:(e,t,r)=>{"use strict";r(33346),r(37527)},7918:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decrypt=t.encrypt=void 0;const n=r(57975),i=r(77598),o=r(84641),a=r(45935),s=r(3508),c=r(72425),u=r(78195),d=r(99135),l=r(60322),p=r(29994),f=r(71759),h=r(58242),m=(0,n.promisify)(i.pbkdf2);function g(e,t){if((0,p.default)(e))return e.export();if(e instanceof Uint8Array)return e;if((0,d.isCryptoKey)(e))return(0,l.checkEncCryptoKey)(e,t,"deriveBits","deriveKey"),i.KeyObject.from(e).export();throw new TypeError((0,f.default)(e,...h.types,"Uint8Array"))}t.encrypt=async(e,t,r,n=2048,i=(0,o.default)(new Uint8Array(16)))=>{(0,u.default)(i);const d=(0,a.p2s)(e,i),l=parseInt(e.slice(13,16),10)>>3,p=g(t,e),f=await m(p,d,n,l,`sha${e.slice(8,11)}`);return{encryptedKey:await(0,c.wrap)(e.slice(-6),f,r),p2c:n,p2s:(0,s.encode)(i)}},t.decrypt=async(e,t,r,n,i)=>{(0,u.default)(i);const o=(0,a.p2s)(e,i),s=parseInt(e.slice(13,16),10)>>3,d=g(t,e),l=await m(d,o,n,s,`sha${e.slice(8,11)}`);return(0,c.unwrap)(e.slice(-6),l,r)}},8102:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>n.str`must match "${e.ifClause}" schema`,params:({params:e})=>n._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,i.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const s=a(o,"then"),c=a(o,"else");if(!s&&!c)return;const u=t.let("valid",!0),d=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);e.mergeEvaluated(t)}(),e.reset(),s&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(d,l("then",r),l("else",r))}else s?t.if(d,l("then")):t.if((0,n.not)(d),l("else"));function l(r,i){return()=>{const o=e.subschema({keyword:r},d);t.assign(u,d),e.mergeValidEvaluated(o,u),i?t.assign(i,n._`${r}`):e.setParams({ifClause:r})}}e.pass(u,()=>e.error(!0))}};function a(e,t){const r=e.schema[t];return void 0!==r&&!(0,i.alwaysValidSchema)(e,r)}t.default=o},8956:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="node:crypto"},9066:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){let r,c,u,d;if(t instanceof n.KeyObject)r=t.asymmetricKeyType,c=t.asymmetricKeyDetails;else switch(u=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,a.default)(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:n}=c,i=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${i}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==n&&n>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");(0,a.default)(t,e),d={padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const n=(0,i.default)(t),o=s.get(e);if(n!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${n}`);d={dsaEncoding:"ieee-p1363"};break}default:throw new o.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return u?{format:"jwk",key:t,...d}:d?{...d,key:t}:t};const n=r(77598),i=r(90862),o=r(39069),a=r(68423),s=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]])},9249:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionService=void 0;const n=r(85601);t.ToolProtectionService=class{config;cache;constructor(e,t){this.config=e,this.cache=t}getProjectId(){return this.config.projectId}async getStaleCache(e){if(!1===this.config.allowStaleCache)return null;if(!(this.cache instanceof n.InMemoryToolProtectionCache))return null;const t=this.cache.getStale(e);if(!t)return null;const r=this.cache.getExpiresAt(e);if(!r)return null;const i=Date.now(),o=this.config.maxStaleCacheAge??864e5;return i>r&&i-r<=o?(this.config.debug&&console.error("[ToolProtectionService] Using stale cache",{cacheKey:e,expiredAt:new Date(r).toISOString(),staleAgeMs:i-r,maxStaleAgeMs:o}),t):null}async getToolProtectionConfig(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`,r=await this.cache.get(t);if(r){const n=this.config.cacheTtl??3e5,i=new Date(Date.now()+n).toISOString();return this.config.debug&&console.error("[ToolProtectionService] Cache hit",{source:"cache",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",toolCount:Object.keys(r.toolProtections).length,protectedTools:Object.entries(r.toolProtections).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),cacheTtlMs:n,cachedUntil:i}),r}this.config.debug&&console.error("[ToolProtectionService] Cache miss, fetching from API",{source:"api-fetch-start",cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",apiUrl:this.config.apiUrl,endpoint:this.config.projectId?`/api/v1/bouncer/projects/${this.config.projectId}/config`:`/api/v1/bouncer/config?agent_did=${e}`});try{const r=await this.fetchFromApi(e);this.config.debug&&console.error("[ToolProtectionService] API response received",{source:"api-fetch-complete",agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",responseKeys:Object.keys(r),dataKeys:r.data?Object.keys(r.data):[],rawConfig:r.data?.config||null,rawConfigToolProtection:r.data?.config?.toolProtection||null,responseMetadata:r.metadata||null});const n=this.parseToolProtectionsFromResponse(r);this.config.debug&&Object.keys(n).length>0&&console.error("[ToolProtectionService] Parsed tool protections from merged config",{toolCount:Object.keys(n).length,tools:Object.keys(n)});const i={};if(this.config.localConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.localConfig.toolProtections)){if(!t||"object"!=typeof t||0===Object.keys(t).length){this.config.debug&&console.error("[ToolProtectionService] Skipping empty/invalid local config entry",{tool:e});continue}const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[],...t.oauthProvider&&{oauthProvider:t.oauthProvider},...t.riskLevel&&{riskLevel:t.riskLevel},...t.authorization&&{authorization:t.authorization}};i[e]=r,this.config.debug&&console.error("[ToolProtectionService] Applied local config as base",{tool:e,localConfig:r})}for(const[e,t]of Object.entries(n))i[e]=t,this.config.debug&&this.config.localConfig?.toolProtections?.[e]&&console.error("[ToolProtectionService] Remote config overrides local config",{tool:e,remoteConfig:t});const o={toolProtections:i},a=this.config.cacheTtl??3e5,s=new Date(Date.now()+a);return await this.cache.set(t,o,a),console.error("[ToolProtectionService] Config loaded from API",{source:"api",toolCount:Object.keys(i).length,protectedTools:Object.entries(i).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",cacheTtlMs:a,cacheExpiresAt:s.toISOString()}),this.config.debug&&console.error("[ToolProtectionService] API fetch successful, config cached",{source:"cache-write",agentDid:e.slice(0,20)+"...",cacheKey:t,toolCount:Object.keys(i).length,tools:Object.entries(i).map(([e,t])=>({name:e,requiresDelegation:t.requiresDelegation,scopeCount:(t.requiredScopes||[]).length})),ttlMs:a,ttlMinutes:Math.round(a/6e4),expiresAt:s.toISOString(),expiresIn:`${Math.round(a/1e3)}s`}),o}catch(r){const n=r instanceof Error?r.message:String(r);if(n.includes("API key is missing or empty"))throw r;if(n.includes("projectId is required"))throw r;if(n.includes("Failed to fetch bouncer config:")&&(429!==r.status||!this.config.offlineFallbackConfig))throw r;if(n.includes("Failed to parse API response:"))throw r;if(n.includes("API returned success: false"))throw r;this.config.debug&&console.error("[ToolProtectionService] API fetch failed",{agentDid:e.slice(0,20)+"...",error:n});const i=await this.getStaleCache(t);if(i)return console.warn("[ToolProtectionService] API fetch failed, using stale cache",{agentDid:e.slice(0,20)+"...",error:n,cacheKey:t}),i;if(this.config.offlineFallbackConfig){console.warn("[ToolProtectionService] API fetch failed, using offline fallback config",{agentDid:e.slice(0,20)+"...",error:n});const r=this.config.cacheTtl??3e5;return await this.cache.set(t,this.config.offlineFallbackConfig,r),this.config.offlineFallbackConfig}if("deny-all"===(this.config.failSafeBehavior??"deny-all")){console.error("[ToolProtectionService] API fetch failed, no offline fallback, failing closed (deny-all)",{agentDid:e.slice(0,20)+"...",error:n,cacheKey:t});const r={toolProtections:{"*":{requiresDelegation:!0,requiredScopes:[]}}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}{console.warn("[ToolProtectionService] API fetch failed, no offline fallback, failing open (allow-all)",{agentDid:e.slice(0,20)+"...",error:n,cacheKey:t});const r={toolProtections:{}},i=this.config.cacheTtl??3e5;return await this.cache.set(t,r,i),r}}}async checkToolProtection(e,t){const r=await this.getToolProtectionConfig(t);let n=r.toolProtections[e];return!n&&r.toolProtections["*"]&&(n=r.toolProtections["*"]),(this.config.debug||!n||n.requiresDelegation)&&console.error("[ToolProtectionService] Protection check",{tool:e,agentDid:t.slice(0,20)+"...",found:!!n,isWildcard:n===r.toolProtections["*"],requiresDelegation:n?.requiresDelegation??!1,availableTools:Object.keys(r.toolProtections)}),n&&n.requiresDelegation?n:null}async fetchFromApi(e,t){let r,n=!1;if(!this.config.projectId){const e=new Error("[ToolProtectionService] projectId is required for user-scoped delegation. Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). Please configure AGENTSHIELD_PROJECT_ID environment variable.");throw console.error("[ToolProtectionService]",e.message),e}if(r=`${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/config`,n=!0,t?.bypassCDNCache){const e=r.includes("?")?"&":"?";r=`${r}${e}_t=${Date.now()}`}const i=this.config.apiKey?(()=>{const e=this.config.apiKey.split("_");return e.length>=2?`${e[0]}_${e[1]}...`:`${this.config.apiKey.substring(0,8)}...`})():"(empty)",o=this.config.apiKey?.length||0;if(this.config.debug&&console.error("[ToolProtectionService] Fetching from API:",r,{method:"projects/{projectId}/config (merged)",projectId:this.config.projectId||"none",apiKeyPresent:!!this.config.apiKey,apiKeyLength:o,apiKeyMasked:i}),!this.config.apiKey||""===this.config.apiKey.trim()){const e="API key is missing or empty";throw this.config.debug&&console.error("[ToolProtectionService]",e,{apiKeyPresent:!!this.config.apiKey,apiKeyLength:o}),new Error(`ToolProtectionService: ${e}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`)}const a={"Content-Type":"application/json"};a["X-API-Key"]=this.config.apiKey,this.config.projectId&&(a["X-Project-Id"]=this.config.projectId),t?.bypassCDNCache&&(a["Cache-Control"]="no-cache, no-store, must-revalidate",a.Pragma="no-cache");const s=await fetch(r,{method:"GET",headers:a});if(!s.ok){const e=await s.text().catch(()=>"Unknown error"),t=new Error(`Failed to fetch bouncer config: ${s.status} ${s.statusText} - ${e}`);throw t.status=s.status,t}let c;try{c=await s.json()}catch(e){throw new Error(`Failed to parse API response: ${e instanceof Error?e.message:String(e)}`)}if(!c.success)throw new Error("API returned success: false");return c}parseToolProtectionsFromResponse(e){const t={},r=e.data.config?.toolProtection?.tools;if(!r)return t;for(const[e,n]of Object.entries(r)){const r=n.requiresDelegation??n.requires_delegation??!1,i=n.requiredScopes??n.required_scopes??n.scopes??[],o=n.oauthProvider??n.oauth_provider??void 0,a=n.riskLevel??n.risk_level??void 0,s=a&&["low","medium","high","critical"].includes(a)?a:void 0,c=n.authorization;t[e]={requiresDelegation:r,requiredScopes:i,...o&&{oauthProvider:o},...s&&{riskLevel:s},...c&&{authorization:c}}}return t}async clearCache(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;this.config.debug&&console.error("[ToolProtectionService] Clearing cache",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t)}async clearAndRefresh(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;console.error("[ToolProtectionService] clearAndRefresh starting",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t),console.error("[ToolProtectionService] Cache entry deleted",{cacheKey:t});try{const r=await this.fetchFromApi(e,{bypassCDNCache:!0}),n=this.parseToolProtectionsFromResponse(r),i={};if(this.config.localConfig?.toolProtections)for(const[e,t]of Object.entries(this.config.localConfig.toolProtections))if(t&&"object"==typeof t&&Object.keys(t).length>0){const r={requiresDelegation:t.requiresDelegation??!1,requiredScopes:t.requiredScopes??[],...t.oauthProvider&&{oauthProvider:t.oauthProvider},...t.riskLevel&&{riskLevel:t.riskLevel},...t.authorization&&{authorization:t.authorization}};i[e]=r}for(const[e,t]of Object.entries(n))i[e]=t;const o={toolProtections:i},a=this.config.cacheTtl??3e5;return await this.cache.set(t,o,a),console.error("[ToolProtectionService] Fresh config fetched and cached",{cacheKey:t,toolCount:Object.keys(i).length,protectedTools:Object.entries(i).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),source:"api"}),{config:o,cacheKey:t,source:"api"}}catch(e){return console.warn("[ToolProtectionService] API fetch failed during refresh, using offline fallback",{error:e instanceof Error?e.message:String(e),cacheKey:t}),{config:this.config.offlineFallbackConfig||{toolProtections:{}},cacheKey:t,source:"fallback"}}}}},10114:e=>{"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},11300:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCHEMA_REGISTRY=void 0,t.getAllSchemas=function(){return t.SCHEMA_REGISTRY},t.getSchemasByCategory=function(e){const r={vc:["verifiable-credential","verifiable-presentation","statuslist2021-credential","statuslist2021-credential-subject"],delegation:["delegation-credential","delegation-record","delegation-constraints","delegation-chain","delegation-creation-request","delegation-verification-result"],handshake:["handshake-request","session-context","nonce-cache-config","nonce-cache-entry"],proof:["detached-proof","proof-meta","proof","proof-w3c","audit-record","canonical-hashes"],registry:["registration-input","registration-result","agent-status","claim-token","delegation-request","delegation-response","registry-delegation","mirror-status","receipt"],runtime:["authorization-display","needs-authorization-error","runtime-error"],cli:["register-output"],tlkrc:["rotation-chain","rotation-event"],verifier:["verify-page"],"well-known":["well-known-agent"]}[e]||[];return t.SCHEMA_REGISTRY.filter(e=>r.includes(e.id))},t.getSchemaById=function(e){return t.SCHEMA_REGISTRY.find(t=>t.id===e)},t.getCriticalSchemas=function(){const e=["verifiable-credential","statuslist2021-credential","delegation-credential","delegation-record","delegation-constraints","detached-proof","proof-meta","handshake-request","session-context","audit-record"];return t.SCHEMA_REGISTRY.filter(t=>e.includes(t.id))},t.getSchemaStats=function(){const e={},n={};for(const i of t.SCHEMA_REGISTRY){const t=i.url.replace(r+"/","").split("/")[0]||"unknown";e[t]=(e[t]||0)+1,n[i.version]=(n[i.version]||0)+1}return{total:t.SCHEMA_REGISTRY.length,byCategory:e,byVersion:n}};const r="https://schema.modelcontextprotocol-identity.io/xmcp-i";t.SCHEMA_REGISTRY=[{id:"verifiable-credential",url:`${r}/vc/verifiable-credential.v1.0.0.json`,version:"1.0.0",type:"VerifiableCredential",description:"W3C Verifiable Credential Data Model"},{id:"verifiable-presentation",url:`${r}/vc/verifiable-presentation.v1.0.0.json`,version:"1.0.0",type:"VerifiablePresentation",description:"W3C Verifiable Presentation"},{id:"statuslist2021-credential",url:`${r}/vc/statuslist-2021-credential.v1.0.0.json`,version:"1.0.0",type:"StatusList2021Credential",description:"StatusList2021 Credential for efficient revocation"},{id:"statuslist2021-credential-subject",url:`${r}/vc/statuslist-2021-credential-subject.v1.0.0.json`,version:"1.0.0",type:"StatusList2021CredentialSubject",description:"StatusList2021 Credential Subject"},{id:"delegation-credential",url:`${r}/credentials/delegation/v1.0.0.json`,version:"1.0.0",type:"DelegationCredential",description:"W3C VC-based delegation credential"},{id:"delegation-record",url:`${r}/delegation/delegation-record.v1.0.0.json`,version:"1.0.0",type:"DelegationRecord",description:"Internal delegation record"},{id:"delegation-constraints",url:`${r}/delegation/constraints.v1.0.0.json`,version:"1.0.0",type:"DelegationConstraints",description:"CRISP constraints for delegations"},{id:"delegation-chain",url:`${r}/delegation/delegation-chain.v1.0.0.json`,version:"1.0.0",type:"DelegationChain",description:"Delegation chain for hierarchy tracking"},{id:"delegation-creation-request",url:`${r}/delegation/delegation-creation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationCreationRequest",description:"Request to create a delegation"},{id:"delegation-verification-result",url:`${r}/delegation/delegation-verification-result.v1.0.0.json`,version:"1.0.0",type:"DelegationVerificationResult",description:"Result of delegation verification"},{id:"handshake-request",url:`${r}/handshake/handshake-request.v1.0.0.json`,version:"1.0.0",type:"HandshakeRequest",description:"MCP-I handshake request"},{id:"session-context",url:`${r}/handshake/session-context.v1.0.0.json`,version:"1.0.0",type:"SessionContext",description:"MCP-I session context"},{id:"nonce-cache-config",url:`${r}/handshake/nonce-cache-config.v1.0.0.json`,version:"1.0.0",type:"NonceCacheConfig",description:"Nonce cache configuration"},{id:"nonce-cache-entry",url:`${r}/handshake/nonce-cache-entry.v1.0.0.json`,version:"1.0.0",type:"NonceCacheEntry",description:"Nonce cache entry for replay protection"},{id:"detached-proof",url:`${r}/proof/detached-proof.v1.0.0.json`,version:"1.0.0",type:"DetachedProof",description:"MCP-I detached proof with JWS"},{id:"proof-meta",url:`${r}/proof/proof-meta.v1.0.0.json`,version:"1.0.0",type:"ProofMeta",description:"Metadata for MCP-I proofs"},{id:"proof",url:`${r}/proof/v1.0.0.json`,version:"1.0.0",type:"Proof",description:"Generic proof structure"},{id:"proof-w3c",url:`${r}/proof/w3c/v1.0.0.json`,version:"1.0.0",type:"W3CProof",description:"W3C-compliant proof"},{id:"audit-record",url:`${r}/proof/audit-record.v1.0.0.json`,version:"1.0.0",type:"AuditRecord",description:"Audit trail record"},{id:"canonical-hashes",url:`${r}/proof/canonical-hashes.v1.0.0.json`,version:"1.0.0",type:"CanonicalHashes",description:"Canonical hashes for proof generation"},{id:"registration-input",url:`${r}/registry/registration-input.v1.0.0.json`,version:"1.0.0",type:"RegistrationInput",description:"Agent registration input"},{id:"registration-result",url:`${r}/registry/registration-result.v1.0.0.json`,version:"1.0.0",type:"RegistrationResult",description:"Agent registration result"},{id:"agent-status",url:`${r}/registry/agent-status.v1.0.0.json`,version:"1.0.0",type:"AgentStatus",description:"Agent status information"},{id:"claim-token",url:`${r}/registry/claim-token.v1.0.0.json`,version:"1.0.0",type:"ClaimToken",description:"Token for claiming agent ownership"},{id:"delegation-request",url:`${r}/registry/delegation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationRequest",description:"Registry delegation request"},{id:"delegation-response",url:`${r}/registry/delegation-response.v1.0.0.json`,version:"1.0.0",type:"DelegationResponse",description:"Registry delegation response"},{id:"registry-delegation",url:`${r}/registry/delegation.v1.0.0.json`,version:"1.0.0",type:"RegistryDelegation",description:"Registry delegation object"},{id:"mirror-status",url:`${r}/registry/mirror-status.v1.0.0.json`,version:"1.0.0",type:"MirrorStatus",description:"Registry mirror status"},{id:"receipt",url:`${r}/registry/receipt.v1.0.0.json`,version:"1.0.0",type:"Receipt",description:"Registry receipt"},{id:"authorization-display",url:`${r}/runtime/authorization-display.v1.0.0.json`,version:"1.0.0",type:"AuthorizationDisplay",description:"Authorization display information"},{id:"needs-authorization-error",url:`${r}/runtime/needs-authorization-error.v1.0.0.json`,version:"1.0.0",type:"NeedsAuthorizationError",description:"Error indicating authorization is needed"},{id:"runtime-error",url:`${r}/runtime/runtime-error.v1.0.0.json`,version:"1.0.0",type:"RuntimeError",description:"Generic runtime error"},{id:"register-output",url:`${r}/cli/register-output/v1.0.0.json`,version:"1.0.0",type:"RegisterOutput",description:"CLI registration output"},{id:"rotation-chain",url:`${r}/tlkrc/rotation-chain.v1.0.0.json`,version:"1.0.0",type:"RotationChain",description:"Key rotation chain"},{id:"rotation-event",url:`${r}/tlkrc/rotation-event.v1.0.0.json`,version:"1.0.0",type:"RotationEvent",description:"Key rotation event"},{id:"verify-page",url:`${r}/verifier/verify-page/v1.0.0.json`,version:"1.0.0",type:"VerifyPage",description:"Verifier page response"},{id:"well-known-agent",url:`${r}/well-known/agent/v1.0.0.json`,version:"1.0.0",type:"WellKnownAgent",description:"Agent well-known metadata"}]},11755:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PolicyService=void 0;const n=r(62408);class i{config;policy;constructor(e,t){this.policy=e??structuredClone(n.DEFAULT_POLICY_CONFIG),this.config=t??{}}setPolicy(e){this.policy=e}getPolicy(){return this.policy}isEnabled(){return this.policy.enabled??!0}evaluate(e){if(!this.isEnabled())return{action:"allow",reason:"Policy enforcement disabled",matchType:"default"};const t=this.checkAllowList(e);if(t)return this.config.debug&&console.error("[PolicyService] Allow list match",{context:this.sanitizeContext(e),match:t}),{action:"allow",reason:`Allowed: ${t.reason??"On allow list"}`,matchType:"allow-list"};const r=this.checkDenyList(e);if(r)return this.config.debug&&console.error("[PolicyService] Deny list match",{context:this.sanitizeContext(e),match:r}),{action:"block",reason:r.reason??"On deny list",matchType:"deny-list"};const n=this.checkThresholds(e);if(n)return this.config.debug&&console.error("[PolicyService] Threshold match",{context:this.sanitizeContext(e),result:n}),n;const i=this.evaluateRules(e);return i?(this.config.debug&&console.error("[PolicyService] Rule match",{context:this.sanitizeContext(e),result:i}),i):{action:this.policy.defaultAction??"allow",reason:"No matching rules, using default action",matchType:"default",redirectUrl:"redirect"===this.policy.defaultAction?this.policy.redirectUrl:void 0}}checkAllowList(e){if(!this.policy.allowList?.length)return null;for(const t of this.policy.allowList)if(this.matchesListEntry(e,t))return t;return null}checkDenyList(e){if(!this.policy.denyList?.length)return null;for(const t of this.policy.denyList)if(!1!==t.active&&!(t.expiresAt&&new Date(t.expiresAt)<new Date)&&this.matchesListEntry(e,t))return t;return null}matchesListEntry(e,t){return!!(t.clientDid&&e.clientDid===t.clientDid||t.agentDid&&e.agentDid===t.agentDid||t.clientName&&e.agentName?.toLowerCase()===t.clientName.toLowerCase()||t.agentType&&e.agentType===t.agentType)}checkThresholds(e){const t=this.policy.thresholds;return t?t.trustSignedRequests&&e.signatureVerified||void 0!==e.reputationScore&&e.reputationScore>=t.trustedReputationThreshold?null:void 0!==e.confidence&&e.confidence>=t.confidenceThreshold?{action:t.confidenceAction,reason:`Detection confidence (${e.confidence}) exceeds threshold (${t.confidenceThreshold})`,matchType:"threshold",redirectUrl:"redirect"===t.confidenceAction?this.policy.redirectUrl:void 0}:t.minReputationScore>0&&void 0!==e.reputationScore&&e.reputationScore<t.minReputationScore?{action:t.lowReputationAction,reason:`Reputation score (${e.reputationScore}) below minimum (${t.minReputationScore})`,matchType:"threshold",redirectUrl:"redirect"===t.lowReputationAction?this.policy.redirectUrl:void 0}:null:null}evaluateRules(e){const t=this.policy.rules;if(!t?.length)return null;const r=[...t].filter(e=>!1!==e.enabled).sort((e,t)=>(e.priority??100)-(t.priority??100));for(const t of r)if(this.matchesRule(e,t))return{action:t.action,reason:t.description??t.name,ruleId:t.id,ruleName:t.name,redirectUrl:"redirect"===t.action?t.redirectUrl:void 0,message:t.message,matchType:"rule"};return null}matchesRule(e,t){return t.conditions.every(t=>this.matchesCondition(e,t))}matchesCondition(e,t){const r=this.getContextValue(e,t.field),n=t.value;if(null==r)return"notEquals"===t.operator||"notIn"===t.operator||"notContains"===t.operator;switch(t.operator){case"equals":return this.compareEqual(r,n,t.caseInsensitive);case"notEquals":return!this.compareEqual(r,n,t.caseInsensitive);case"contains":return"string"==typeof r&&"string"==typeof n&&(t.caseInsensitive?r.toLowerCase().includes(n.toLowerCase()):r.includes(n));case"notContains":return"string"!=typeof r||"string"!=typeof n||(t.caseInsensitive?!r.toLowerCase().includes(n.toLowerCase()):!r.includes(n));case"startsWith":return"string"==typeof r&&"string"==typeof n&&(t.caseInsensitive?r.toLowerCase().startsWith(n.toLowerCase()):r.startsWith(n));case"endsWith":return"string"==typeof r&&"string"==typeof n&&(t.caseInsensitive?r.toLowerCase().endsWith(n.toLowerCase()):r.endsWith(n));case"greaterThan":return"number"==typeof r&&"number"==typeof n&&r>n;case"lessThan":return"number"==typeof r&&"number"==typeof n&&r<n;case"greaterThanOrEquals":return"number"==typeof r&&"number"==typeof n&&r>=n;case"lessThanOrEquals":return"number"==typeof r&&"number"==typeof n&&r<=n;case"matches":if("string"!=typeof r||"string"!=typeof n)return!1;try{const e=t.caseInsensitive?"i":"";return new RegExp(n,e).test(r)}catch{return!1}case"in":return!!Array.isArray(n)&&n.some(e=>this.compareEqual(r,e,t.caseInsensitive));case"notIn":return!Array.isArray(n)||!n.some(e=>this.compareEqual(r,e,t.caseInsensitive));default:return!1}}getContextValue(e,t){switch(t){case"agentType":return e.agentType;case"agentName":return e.agentName;case"agentVendor":return e.agentVendor;case"clientDid":return e.clientDid;case"agentDid":return e.agentDid;case"confidence":return e.confidence;case"reputationScore":return e.reputationScore;case"riskLevel":return e.riskLevel;case"path":return e.path;case"method":return e.method;case"origin":return e.origin;case"userAgent":return e.userAgent;case"signatureVerified":return e.signatureVerified;case"isAuthenticated":return e.isAuthenticated;case"hasValidDelegation":return e.hasValidDelegation;default:return}}compareEqual(e,t,r){return"string"==typeof e&&"string"==typeof t&&r?e.toLowerCase()===t.toLowerCase():e===t}sanitizeContext(e){return{agentType:e.agentType,agentName:e.agentName,agentVendor:e.agentVendor,clientDid:e.clientDid?`${e.clientDid.slice(0,20)}...`:void 0,agentDid:e.agentDid?`${e.agentDid.slice(0,20)}...`:void 0,confidence:e.confidence,reputationScore:e.reputationScore,riskLevel:e.riskLevel,path:e.path,method:e.method,signatureVerified:e.signatureVerified,isAuthenticated:e.isAuthenticated,hasValidDelegation:e.hasValidDelegation}}}t.PolicyService=i,t.default=i},11858:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(26419),i=r(38994),o=r(67218),a=r(6013),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>i.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>i._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:s,schema:c,parentSchema:u,schemaCode:d,it:l}=e;if(!s&&!c)return;const p=t.let("valid"),f=u.items?(0,n.getSchemaTypes)(u.items):[];function h(o,a){const s=t.name("item"),c=(0,n.checkDataTypes)(f,s,l.opts.strictNumbers,n.DataType.Wrong),u=t.const("indices",i._`{}`);t.for(i._`;${o}--;`,()=>{t.let(s,i._`${r}[${o}]`),t.if(c,i._`continue`),f.length>1&&t.if(i._`typeof ${s} == "string"`,i._`${s} += "_"`),t.if(i._`typeof ${u}[${s}] == "number"`,()=>{t.assign(a,i._`${u}[${s}]`),e.error(),t.assign(p,!1).break()}).code(i._`${u}[${s}] = ${o}`)})}function m(n,s){const c=(0,o.useFunc)(t,a.default),u=t.name("outer");t.label(u).for(i._`;${n}--;`,()=>t.for(i._`${s} = ${n}; ${s}--;`,()=>t.if(i._`${c}(${r}[${n}], ${r}[${s}])`,()=>{e.error(),t.assign(p,!1).break(u)})))}e.block$data(p,function(){const n=t.let("i",i._`${r}.length`),o=t.let("j");e.setParams({i:n,j:o}),t.assign(p,!0),t.if(i._`${n} > 1`,()=>(f.length>0&&!f.some(e=>"object"===e||"array"===e)?h:m)(n,o))},i._`${d} === false`),e.ok(p)}};t.default=s},12003:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(67218),i={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=t.name("valid");r.forEach((t,r)=>{if((0,n.alwaysValidSchema)(i,t))return;const a=e.subschema({keyword:"allOf",schemaProp:r},o);e.ok(o),e.mergeEvaluated(a)})}};t.default=i},12189:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:i}=e,o="maxProperties"===t?n.operators.GT:n.operators.LT;e.fail$data(n._`Object.keys(${r}).length ${o} ${i}`)}};t.default=i},12556:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.jwtVerify=async function(e,t,r){const a=await(0,n.compactVerify)(e,t,r);if(a.protectedHeader.crit?.includes("b64")&&!1===a.protectedHeader.b64)throw new o.JWTInvalid("JWTs MUST NOT use unencoded payload");const s={payload:(0,i.default)(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...s,key:a.key}:s};const n=r(39409),i=r(52691),o=r(39069)},12930:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(37067),i=r(44708),o=r(78474),a=r(39069),s=r(45935);t.default=async(e,t,r)=>{let c;switch(e.protocol){case"https:":c=i.get;break;case"http:":c=n.get;break;default:throw new TypeError("Unsupported URL protocol.")}const{agent:u,headers:d}=r,l=c(e.href,{agent:u,timeout:t,headers:d}),[p]=await Promise.race([(0,o.once)(l,"response"),(0,o.once)(l,"timeout")]);if(!p)throw l.destroy(),new a.JWKSTimeout;if(200!==p.statusCode)throw new a.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");const f=[];for await(const e of p)f.push(e);try{return JSON.parse(s.decoder.decode((0,s.concat)(...f)))}catch{throw new a.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}}},14074:(e,t,r)=>{"use strict";function n(e,t,r){function n(r,n){var i;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(i=r._zod).traits??(i.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in a.prototype)e in r||Object.defineProperty(r,e,{value:a.prototype[e].bind(r)});r._zod.constr=a,r._zod.def=n}const i=r?.Parent??Object;class o extends i{}function a(e){var t;const i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}r.d(t,{$ps:()=>Fe,Dqv:()=>De,CQL:()=>Ne,sFi:()=>Ke,CI7:()=>Ce,CnV:()=>Ae,bl8:()=>be,Zu1:()=>we,t$E:()=>pt,QPK:()=>H,b03:()=>vt,rvF:()=>st,P0p:()=>Xe,Oyg:()=>ze,qGO:()=>ge,cG4:()=>ye,VOE:()=>rt,a$H:()=>u,Zc9:()=>he,Lc$:()=>Oe,ZyE:()=>Te,v1L:()=>Pe,KoL:()=>Ie,$Nv:()=>xe,Ax8:()=>Ee,LJA:()=>Ye,h80:()=>Re,GYt:()=>ke,nuC:()=>nt,Pyd:()=>_e,Umr:()=>Le,N$X:()=>dt,x89:()=>Je,ZQr:()=>at,vzu:()=>Ue,Iab:()=>Me,L8f:()=>qe,igI:()=>ot,_mk:()=>ft,VFw:()=>ut,Sbs:()=>mt,hax:()=>tt,$vM:()=>pe,EYA:()=>fe,Wc_:()=>it,W4S:()=>le,g5t:()=>$e,VYh:()=>ve,Znh:()=>me,L8w:()=>Ge,GPR:()=>Ze,TFq:()=>Se,xIx:()=>n,dZg:()=>br,rty:()=>Jt,cUp:()=>Zt,_Le:()=>Xt,UyX:()=>Mt,gPm:()=>Kt,fsu:()=>At,BjO:()=>jt,FOv:()=>wr,KBX:()=>Lt,Mue:()=>St,aCo:()=>Tt,ERr:()=>hr,TxR:()=>nr,qmM:()=>ir,tB6:()=>kt,dRF:()=>pr,LKT:()=>Gt,NyF:()=>Rt,$O6:()=>Ut,dbS:()=>Ht,G1$:()=>Ft,f25:()=>qt,KnZ:()=>Vt,rkn:()=>Wt,_zn:()=>zt,YAm:()=>cr,hH9:()=>dr,AuJ:()=>tr,Zm2:()=>rr,Ebs:()=>ar,m9B:()=>sr,HiR:()=>or,Dl9:()=>Ct,G8g:()=>er,loG:()=>gr,jwX:()=>Yt,F7R:()=>Bt,bS9:()=>mr,Tjm:()=>f,Rb:()=>h,fUZ:()=>$r,Fkv:()=>ur,Ody:()=>m,wGr:()=>v,$S2:()=>fr,Rle:()=>$t,Ilv:()=>yr,xYx:()=>_r,WN0:()=>vr,CtB:()=>Dt,emL:()=>Qt,qFb:()=>lr,Fnx:()=>Ot,Bem:()=>It,nA:()=>Pt,pYI:()=>Et,wAW:()=>xt,Pwh:()=>Nt,o8B:()=>s.clone,$WB:()=>a,JMU:()=>l,Wk_:()=>p,fd:()=>wt,xLC:()=>g,ZSL:()=>s}),Symbol("zod_brand");class i extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const o={};function a(e){return e&&Object.assign(o,e),o}var s=r(33346);const c=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,s.jsonStringifyReplacer,2),enumerable:!0})},u=n("$ZodError",c),d=n("$ZodError",c,{Parent:Error});function l(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function p(e,t){const r=t||function(e){return e.message},n={_errors:[]},i=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>i({issues:e}));else if("invalid_key"===t.code)i({issues:t.issues});else if("invalid_element"===t.code)i({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,i=0;for(;i<t.path.length;){const n=t.path[i];i===t.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(r(t))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return i(e),n}const f=e=>(t,r,n,o)=>{const c=n?Object.assign(n,{async:!1}):{async:!1},u=t._zod.run({value:r,issues:[]},c);if(u instanceof Promise)throw new i;if(u.issues.length){const t=new(o?.Err??e)(u.issues.map(e=>s.finalizeIssue(e,c,a())));throw s.captureStackTrace(t,o?.callee),t}return u.value},h=e=>async(t,r,n,i)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let c=t._zod.run({value:r,issues:[]},o);if(c instanceof Promise&&(c=await c),c.issues.length){const t=new(i?.Err??e)(c.issues.map(e=>s.finalizeIssue(e,o,a())));throw s.captureStackTrace(t,i?.callee),t}return c.value},m=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},c=t._zod.run({value:r,issues:[]},o);if(c instanceof Promise)throw new i;return c.issues.length?{success:!1,error:new(e??u)(c.issues.map(e=>s.finalizeIssue(e,o,a())))}:{success:!0,data:c.value}},g=m(d),v=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>s.finalizeIssue(e,i,a())))}:{success:!0,data:o.value}},y=v(d),_=/^[cC][^\s-]{8,}$/,b=/^[0-9a-z]+$/,w=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$=/^[0-9a-vA-V]{20}$/,S=/^[A-Za-z0-9]{27}$/,k=/^[a-zA-Z0-9_-]{21}$/,I=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,P=/^([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})$/,E=e=>e?new 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)$/,x=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,O=/^(?:(?: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])$/,T=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,C=/^((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])$/,A=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,j=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,D=/^[A-Za-z0-9_-]*$/,N=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,z=/^\+(?:[0-9]){6,14}[0-9]$/,R="(?:(?:\\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])))",U=new RegExp(`^${R}$`);function M(e){const 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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const K=/^\d+$/,J=/^-?\d+(?:\.\d+)?/i,Z=/true|false/i,L=/null/i,W=/^[^A-Z]*$/,F=/^[^a-z]*$/,H=n("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),V={number:"number",bigint:"bigint",object:"date"},q=n("$ZodCheckLessThan",(e,t)=>{H.init(e,t);const r=V[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),B=n("$ZodCheckGreaterThan",(e,t)=>{H.init(e,t);const r=V[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),G=n("$ZodCheckMultipleOf",(e,t)=>{H.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===s.floatSafeRemainder(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),X=n("$ZodCheckNumberFormat",(e,t)=>{H.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=s.NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=o,r&&(n.pattern=K)}),e._zod.check=a=>{const s=a.value;if(r){if(!Number.isInteger(s))return void a.issues.push({expected:n,format:t.format,code:"invalid_type",input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),Y=n("$ZodCheckMaxLength",(e,t)=>{H.init(e,t),e._zod.when=e=>{const t=e.value;return!s.nullish(t)&&void 0!==t.length},e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const i=s.getLengthableOrigin(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Q=n("$ZodCheckMinLength",(e,t)=>{H.init(e,t),e._zod.when=e=>{const t=e.value;return!s.nullish(t)&&void 0!==t.length},e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=s.getLengthableOrigin(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ee=n("$ZodCheckLengthEquals",(e,t)=>{H.init(e,t),e._zod.when=e=>{const t=e.value;return!s.nullish(t)&&void 0!==t.length},e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const o=s.getLengthableOrigin(n),a=i>t.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},input:r.value,inst:e,continue:!t.abort})}}),te=n("$ZodCheckStringFormat",(e,t)=>{var r;H.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),(r=e._zod).check??(r.check=r=>{if(!t.pattern)throw new Error("Not implemented.");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})})}),re=n("$ZodCheckRegex",(e,t)=>{te.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})}}),ne=n("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=W),te.init(e,t)}),ie=n("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=F),te.init(e,t)}),oe=n("$ZodCheckIncludes",(e,t)=>{H.init(e,t);const r=s.escapeRegex(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),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})}}),ae=n("$ZodCheckStartsWith",(e,t)=>{H.init(e,t);const r=new RegExp(`^${s.escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),se=n("$ZodCheckEndsWith",(e,t)=>{H.init(e,t);const r=new RegExp(`.*${s.escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),ce=n("$ZodCheckOverwrite",(e,t)=>{H.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ue{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const de={major:4,minor:0,patch:0},le=n("$ZodType",(e,t)=>{var r;e??(e={}),s.defineLazy(e._zod,"id",()=>t.type+"_"+s.randomString(10)),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=de;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,o=s.aborted(e);for(const a of t){if(a._zod.when){if(!a._zod.when(e))continue}else if(o)continue;const t=e.issues.length,c=a._zod.check(e);if(c instanceof Promise&&!1===r?.async)throw new i;if(n||c instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await c,e.issues.length!==t&&(o||(o=s.aborted(e,t)))});else{if(e.issues.length===t)continue;o||(o=s.aborted(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,o)=>{const a=e._zod.parse(r,o);if(a instanceof Promise){if(!1===o.async)throw new i;return a.then(e=>t(e,n,o))}return t(a,n,o)}}e["~standard"]={validate:t=>{try{const r=g(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return y(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),pe=n("$ZodString",(e,t)=>{var r;le.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),fe=n("$ZodStringFormat",(e,t)=>{te.init(e,t),pe.init(e,t)}),he=n("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=P),fe.init(e,t)}),me=n("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=E(e))}else t.pattern??(t.pattern=E());fe.init(e,t)}),ge=n("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=x),fe.init(e,t)}),ve=n("$ZodURL",(e,t)=>{fe.init(e,t),e._zod.check=r=>{try{const n=new URL(r.value);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:N.source,input:r.value,inst:e,continue:!t.abort})),void(t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})))}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ye=n("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),fe.init(e,t)}),_e=n("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=k),fe.init(e,t)}),be=n("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=_),fe.init(e,t)}),we=n("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=b),fe.init(e,t)}),$e=n("$ZodULID",(e,t)=>{t.pattern??(t.pattern=w),fe.init(e,t)}),Se=n("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$),fe.init(e,t)}),ke=n("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=S),fe.init(e,t)}),Ie=n("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=M({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${R}T(?:${n})$`)}(t)),fe.init(e,t),e._zod.check}),Pe=n("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=U),fe.init(e,t)}),Ee=n("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${M(t)}$`)),fe.init(e,t),e._zod.check}),xe=n("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=I),fe.init(e,t)}),Oe=n("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=O),fe.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),Te=n("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=T),fe.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ce=n("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=C),fe.init(e,t)}),Ae=n("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=A),fe.init(e,t),e._zod.check=r=>{const[n,i]=r.value.split("/");try{if(!i)throw new Error;const e=Number(i);if(`${e}`!==i)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function je(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const De=n("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=j),fe.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{je(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Ne=n("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=D),fe.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!D.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return je(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})}}),ze=n("$ZodE164",(e,t)=>{t.pattern??(t.pattern=z),fe.init(e,t)}),Re=n("$ZodJWT",(e,t)=>{fe.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r,i=JSON.parse(atob(n));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ue=n("$ZodNumber",(e,t)=>{le.init(e,t),e._zod.pattern=e._zod.bag.pattern??J,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),Me=n("$ZodNumber",(e,t)=>{X.init(e,t),Ue.init(e,t)}),Ke=n("$ZodBoolean",(e,t)=>{le.init(e,t),e._zod.pattern=Z,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),Je=n("$ZodNull",(e,t)=>{le.init(e,t),e._zod.pattern=L,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const{value:n}=t;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),Ze=n("$ZodUnknown",(e,t)=>{le.init(e,t),e._zod.parse=e=>e}),Le=n("$ZodNever",(e,t)=>{le.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function We(e,t,r){e.issues.length&&t.issues.push(...s.prefixIssues(r,e.issues)),t.value[r]=e.value}const Fe=n("$ZodArray",(e,t)=>{le.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const a=i[e],s=t.element._zod.run({value:a,issues:[]},n);s instanceof Promise?o.push(s.then(t=>We(t,r,e))):We(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function He(e,t,r){e.issues.length&&t.issues.push(...s.prefixIssues(r,e.issues)),t.value[r]=e.value}function Ve(e,t,r,n){e.issues.length?void 0===n[r]?t.value[r]=r in n?void 0:e.value:t.issues.push(...s.prefixIssues(r,e.issues)):void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const qe=n("$ZodObject",(e,t)=>{le.init(e,t);const r=s.cached(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof le))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=s.optionalKeys(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});let n;s.defineLazy(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const i=s.isObject,a=!o.jitless,c=s.allowsEval,u=a&&c.value,{catchall:d}=t;let l;e._zod.parse=(o,c)=>{l??(l=r.value);const p=o.value;if(!i(p))return o.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),o;const f=[];if(a&&u&&!1===c?.async&&!0!==c.jitless)n||(n=(e=>{const t=new ue(["shape","payload","ctx"]),{keys:n,optionalKeys:i}=r.value,o=e=>{const t=s.esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const a=Object.create(null);for(const e of n)a[e]=s.randomString(15);t.write("const newResult = {}");for(const e of n)if(i.has(e)){const r=a[e];t.write(`const ${r} = ${o(e)};`);const n=s.esc(e);t.write(`\n if (${r}.issues.length) {\n if (input[${n}] === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${n} in input) newResult[${n}] = undefined;\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}else{const r=a[e];t.write(`const ${r} = ${o(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s.esc(e)}, ...iss.path] : [${s.esc(e)}]\n })));`),t.write(`newResult[${s.esc(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const c=t.compile();return(t,r)=>c(e,t,r)})(t.shape)),o=n(o,c);else{o.value={};const e=l.shape;for(const t of l.keys){const r=e[t],n=r._zod.run({value:p[t],issues:[]},c),i="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?f.push(n.then(e=>i?Ve(e,o,t,p):He(e,o,t))):i?Ve(n,o,t,p):He(n,o,t)}}if(!d)return f.length?Promise.all(f).then(()=>o):o;const h=[],m=l.keySet,g=d._zod,v=g.def.type;for(const e of Object.keys(p)){if(m.has(e))continue;if("never"===v){h.push(e);continue}const t=g.run({value:p[e],issues:[]},c);t instanceof Promise?f.push(t.then(t=>He(t,o,e))):He(t,o,e)}return h.length&&o.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),f.length?Promise.all(f).then(()=>o):o}});function Be(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>s.finalizeIssue(e,n,a())))}),t}const Ge=n("$ZodUnion",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),s.defineLazy(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>s.cleanRegex(e.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let i=!1;const o=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},n);if(t instanceof Promise)o.push(t),i=!0;else{if(0===t.issues.length)return t;o.push(t)}}return i?Promise.all(o).then(t=>Be(t,r,e,n)):Be(o,r,e,n)}}),Xe=n("$ZodDiscriminatedUnion",(e,t)=>{Ge.init(e,t);const r=e._zod.parse;s.defineLazy(e._zod,"propValues",()=>{const e={};for(const r of t.options){const n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(const n of r)e[t].add(n)}}return e});const n=s.cached(()=>{const e=t.options,r=new Map;for(const n of e){const e=n._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,o)=>{const a=i.value;if(!s.isObject(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;const c=n.value.get(a?.[t.discriminator]);return c?c._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),i)}}),Ye=n("$ZodIntersection",(e,t)=>{le.init(e,t),e._zod.parse=(e,r)=>{const{value:n}=e,i=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,r])=>et(e,t,r)):et(e,i,o)}});function Qe(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(s.isPlainObject(e)&&s.isPlainObject(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=Qe(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=Qe(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function et(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),s.aborted(e))return e;const n=Qe(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const tt=n("$ZodRecord",(e,t)=>{le.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!s.isPlainObject(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const o=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:i[e],issues:[]},n);a instanceof Promise?o.push(a.then(t=>{t.issues.length&&r.issues.push(...s.prefixIssues(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...s.prefixIssues(e,a.issues)),r.value[e]=a.value)}let c;for(const e in i)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{r.value={};for(const c of Reflect.ownKeys(i)){if("__proto__"===c)continue;const u=t.keyType._zod.run({value:c,issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(e=>s.finalizeIssue(e,n,a())),input:c,path:[c],inst:e}),r.value[u.value]=u.value;continue}const d=t.valueType._zod.run({value:i[c],issues:[]},n);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...s.prefixIssues(c,e.issues)),r.value[u.value]=e.value})):(d.issues.length&&r.issues.push(...s.prefixIssues(c,d.issues)),r.value[u.value]=d.value)}}return o.length?Promise.all(o).then(()=>r):r}}),rt=n("$ZodEnum",(e,t)=>{le.init(e,t);const r=s.getEnumValues(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>s.propertyKeyTypes.has(typeof e)).map(e=>"string"==typeof e?s.escapeRegex(e):e.toString()).join("|")})$`),e._zod.parse=(t,n)=>{const i=t.value;return e._zod.values.has(i)||t.issues.push({code:"invalid_value",values:r,input:i,inst:e}),t}}),nt=n("$ZodLiteral",(e,t)=>{le.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?s.escapeRegex(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,n)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),it=n("$ZodTransform",(e,t)=>{le.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new i;return e.value=n,e}}),ot=n("$ZodOptional",(e,t)=>{le.init(e,t),e._zod.optin="optional",e._zod.optout="optional",s.defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),s.defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${s.cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>void 0===e.value?e:t.innerType._zod.run(e,r)}),at=n("$ZodNullable",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),s.defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),s.defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${s.cleanRegex(e.source)}|null)$`):void 0}),s.defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),st=n("$ZodDefault",(e,t)=>{le.init(e,t),e._zod.optin="optional",s.defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>ct(e,t)):ct(n,t)}});function ct(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const ut=n("$ZodPrefault",(e,t)=>{le.init(e,t),e._zod.optin="optional",s.defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),dt=n("$ZodNonOptional",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>lt(t,e)):lt(i,e)}});function lt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const pt=n("$ZodCatch",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),s.defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),s.defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>s.finalizeIssue(e,r,a()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>s.finalizeIssue(e,r,a()))},input:e.value}),e.issues=[]),e)}}),ft=n("$ZodPipe",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"values",()=>t.in._zod.values),s.defineLazy(e._zod,"optin",()=>t.in._zod.optin),s.defineLazy(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>ht(e,t,r)):ht(n,t,r)}});function ht(e,t,r){return s.aborted(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const mt=n("$ZodReadonly",(e,t)=>{le.init(e,t),s.defineLazy(e._zod,"propValues",()=>t.innerType._zod.propValues),s.defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),s.defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(gt):gt(n)}});function gt(e){return e.value=Object.freeze(e.value),e}const vt=n("$ZodCustom",(e,t)=>{H.init(e,t),le.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>yt(t,r,n,e));yt(i,r,n,e)}});function yt(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(s.issue(e))}}r(7673),Symbol("ZodOutput"),Symbol("ZodInput");class _t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function bt(){return new _t}const wt=bt();function $t(e,t){return new e({type:"string",...s.normalizeParams(t)})}function St(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...s.normalizeParams(t)})}function kt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function It(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Pt(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...s.normalizeParams(t)})}function Et(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...s.normalizeParams(t)})}function xt(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...s.normalizeParams(t)})}function Ot(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Tt(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Ct(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function At(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function jt(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Dt(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Nt(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function zt(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Rt(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Ut(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Mt(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Kt(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Jt(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Zt(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Lt(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Wt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...s.normalizeParams(t)})}function Ft(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...s.normalizeParams(t)})}function Ht(e,t){return new e({type:"string",format:"date",check:"string_format",...s.normalizeParams(t)})}function Vt(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...s.normalizeParams(t)})}function qt(e,t){return new e({type:"string",format:"duration",check:"string_format",...s.normalizeParams(t)})}function Bt(e,t){return new e({type:"number",checks:[],...s.normalizeParams(t)})}function Gt(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...s.normalizeParams(t)})}function Xt(e,t){return new e({type:"boolean",...s.normalizeParams(t)})}function Yt(e,t){return new e({type:"null",...s.normalizeParams(t)})}function Qt(e){return new e({type:"unknown"})}function er(e,t){return new e({type:"never",...s.normalizeParams(t)})}function tr(e,t){return new q({check:"less_than",...s.normalizeParams(t),value:e,inclusive:!1})}function rr(e,t){return new q({check:"less_than",...s.normalizeParams(t),value:e,inclusive:!0})}function nr(e,t){return new B({check:"greater_than",...s.normalizeParams(t),value:e,inclusive:!1})}function ir(e,t){return new B({check:"greater_than",...s.normalizeParams(t),value:e,inclusive:!0})}function or(e,t){return new G({check:"multiple_of",...s.normalizeParams(t),value:e})}function ar(e,t){return new Y({check:"max_length",...s.normalizeParams(t),maximum:e})}function sr(e,t){return new Q({check:"min_length",...s.normalizeParams(t),minimum:e})}function cr(e,t){return new ee({check:"length_equals",...s.normalizeParams(t),length:e})}function ur(e,t){return new re({check:"string_format",format:"regex",...s.normalizeParams(t),pattern:e})}function dr(e){return new ne({check:"string_format",format:"lowercase",...s.normalizeParams(e)})}function lr(e){return new ie({check:"string_format",format:"uppercase",...s.normalizeParams(e)})}function pr(e,t){return new oe({check:"string_format",format:"includes",...s.normalizeParams(t),includes:e})}function fr(e,t){return new ae({check:"string_format",format:"starts_with",...s.normalizeParams(t),prefix:e})}function hr(e,t){return new se({check:"string_format",format:"ends_with",...s.normalizeParams(t),suffix:e})}function mr(e){return new ce({check:"overwrite",tx:e})}function gr(e){return mr(t=>t.normalize(e))}function vr(){return mr(e=>e.trim())}function yr(){return mr(e=>e.toLowerCase())}function _r(){return mr(e=>e.toUpperCase())}function br(e,t,r){return new e({type:"array",element:t,...s.normalizeParams(r)})}function wr(e,t,r){const n=s.normalizeParams(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function $r(e,t,r){return new e({type:"custom",check:"custom",fn:t,...s.normalizeParams(r)})}},14186:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generalVerify=async function(e,t,r){if(!(0,o.default)(e))throw new i.JWSInvalid("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(o.default))throw new i.JWSInvalid("JWS Signatures missing or incorrect type");for(const i of e.signatures)try{return await(0,n.flattenedVerify)({header:i.header,payload:e.payload,protected:i.protected,signature:i.signature},t,r)}catch{}throw new i.JWSSignatureVerificationFailed};const n=r(55403),i=r(39069),o=r(71661)},14339:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateKeyPair=async function(e,t){return(0,n.generateKeyPair)(e,t)};const n=r(37329)},15141:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(t.DiscrError=r={}))},15497:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CompactSign=void 0;const n=r(30131);t.CompactSign=class{_flattened;constructor(e){this._flattened=new n.FlattenedSign(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}},15860:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const n=r(38994),i=r(67218),o=r(24954);t.error={message:({params:{property:e,depsCount:t,deps:r}})=>{const i=1===t?"property":"properties";return n.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>n._`{property: ${e},
2
+ missingProperty: ${i},
6
3
  depsCount: ${t},
7
- deps: ${r}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e)"__proto__"!==o&&((Array.isArray(e[o])?t:r)[o]=e[o]);return[t,r]}(e);a(e,t),c(e,r)}};function a(e,t=e.schema){const{gen:r,data:n,it:s}=e;if(0===Object.keys(t).length)return;const a=r.let("missing");for(const c in t){const d=t[c];if(0===d.length)continue;const l=(0,i.propertyInData)(r,n,c,s.opts.ownProperties);e.setParams({property:c,depsCount:d.length,deps:d.join(", ")}),s.allErrors?r.if(l,()=>{for(const t of d)(0,i.checkReportMissingProp)(e,t)}):(r.if(o._`${l} && (${(0,i.checkMissingProp)(e,d,a)})`),(0,i.reportMissingProp)(e,a),r.else())}}function c(e,t=e.schema){const{gen:r,data:o,keyword:s,it:a}=e,c=r.name("valid");for(const d in t)(0,n.alwaysValidSchema)(a,t[d])||(r.if((0,i.propertyInData)(r,o,d,a.opts.ownProperties),()=>{const t=e.subschema({keyword:s,schemaProp:d},c);e.mergeValidEvaluated(t,c)},()=>r.var(c,!0)),e.ok(c))}t.validatePropertyDeps=a,t.validateSchemaDeps=c,t.default=s},91128:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return o.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>o._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:n}=e,i="maxItems"===t?o.operators.GT:o.operators.LT;e.fail$data(o._`${r}.length ${i} ${n}`)}};t.default=n},92182:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StorageKeyHelpers=void 0,t.createStorageProviders=async function(e){const t=!1!==e.fallbackToMemory;if(e.redisUrl)try{const t="redis",o=await r(52643)(t).catch(()=>null);if(!o)throw new Error("Redis package not available");const{createClient:n}=o,i=n({url:e.redisUrl,socket:{connectTimeout:5e3}});await i.connect(),await i.ping();return{storageProvider:new c(i),nonceCacheProvider:new d(i)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to connect to Redis, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.kvNamespace)try{const t=await async function(e){try{const t="@kya-os/mcp-i-cloudflare/providers/storage",{KVStorageProvider:o,KVNonceCacheProvider:n}=await r(42399)(t);return{storage:new o(e),nonceCache:new n(e)}}catch(e){throw new Error(`Failed to import Cloudflare storage providers: ${e instanceof Error?e.message:String(e)}`)}}(e.kvNamespace);return{storageProvider:t.storage,nonceCacheProvider:t.nonceCache}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize KV, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.durableObjectState)try{return{storageProvider:new s(e.durableObjectState),nonceCacheProvider:new a(e.durableObjectState)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize Durable Objects, falling back to memory:",e instanceof Error?e.message:String(e))}if(t)return{storageProvider:new n.MemoryStorageProvider,nonceCacheProvider:new n.MemoryNonceCacheProvider};throw new Error("No storage provider configured and fallbackToMemory is false")},t.migrateLegacyKeys=async function(e,t,r,o=100){let n=0;try{const i=await r.list(e);for(const e of i){const i=t(e);if(!i)continue;if(await r.exists(i))continue;const s=await r.get(e);s&&(await r.set(i,s),n++,n%o===0&&await new Promise(e=>setTimeout(e,0)))}}catch(e){throw console.error("[StorageService] Migration error:",e),e}return n};const o=r(27087),n=r(48505);class i{static buildDelegationKey(e,t,r){return`delegation:${e}:${t}:${r}`}static buildSessionKey(e){return`session:${e}`}static buildNonceKey(e,t){return`nonce:${e}:${t}`}static parseDelegationKey(e){if(!e.startsWith("delegation:"))return null;const t=e.slice(11),r=t.lastIndexOf(":");if(-1===r)return null;const o=t.slice(r+1);if(!o)return null;const n=t.slice(0,r),i=n.indexOf("did:");if(0!==i)return null;const s=n.indexOf(":",i+4);if(-1===s)return null;const a=n.indexOf("did:",s+1);if(-1===a)return null;const c=n.slice(0,a),d=n.slice(a),l=c.endsWith(":")?c.slice(0,-1):c;return l&&d?{userDid:l,agentDid:d,projectId:o}:null}}t.StorageKeyHelpers=i;class s extends o.StorageProvider{state;constructor(e){super(),this.state=e}async get(e){return await this.state.storage.get(e)??null}async set(e,t){await this.state.storage.put(e,t)}async delete(e){await this.state.storage.delete(e)}async exists(e){return void 0!==await this.state.storage.get(e)}async list(e){const t=await this.state.storage.list(e?{prefix:e}:void 0);return Array.from(t.keys())}}class a extends o.NonceCacheProvider{state;constructor(e){super(),this.state=e}async has(e,t){const r=t?i.buildNonceKey(t,e):`nonce:${e}`,o=await this.state.storage.get(r);if(!o)return!1;const n=parseInt(o,10);return Date.now()<n}async add(e,t,r){const o=r?i.buildNonceKey(r,e):`nonce:${e}`,n=Date.now()+1e3*t;await this.state.storage.put(o,n.toString())}async cleanup(){}async destroy(){}}class c extends o.StorageProvider{redis;constructor(e){super(),this.redis=e}async get(e){return await this.redis.get(e)}async set(e,t){await this.redis.set(e,t)}async delete(e){await this.redis.del(e)}async exists(e){return 1===await this.redis.exists(e)}async list(e){const t=e?`${e}*`:"*";return await this.redis.keys(t)}}class d extends o.NonceCacheProvider{redis;keyPrefix;constructor(e,t="nonce:"){super(),this.redis=e,this.keyPrefix=t}async has(e,t){const r=t?i.buildNonceKey(t,e):`${this.keyPrefix}${e}`;return 1===await this.redis.exists(r)}async add(e,t,r){const o=r?i.buildNonceKey(r,e):`${this.keyPrefix}${e}`;await this.redis.setEx(o,t,"1")}async cleanup(){}async destroy(){}}},93591:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(28440),n=r(19315),i=r(79135),s=r(6447),a=r(75078),c=r(87394),d=r(40508),l=r(43439),u=r(53210),h=r(29880),f=r(63278),p=r(15988),m=r(14218),g=r(94741),y=r(99352),v=r(20925);t.default=function(e=!1){const t=[f.default,p.default,m.default,g.default,y.default,v.default,d.default,l.default,c.default,u.default,h.default];return e?t.push(n.default,s.default):t.push(o.default,i.default),t.push(a.default),t}},93716:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const o=r(36556),n=r(28512),i=r(94614),s=r(28512);function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:o._`Object.prototype.hasOwnProperty`})}function c(e,t,r){return o._`${a(e)}.call(${t}, ${r})`}function d(e,t,r,n){const i=o._`${t}${(0,o.getProperty)(r)} === undefined`;return n?(0,o.or)(i,(0,o.not)(c(e,t,r))):i}function l(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:r,data:n,it:i}=e;r.if(d(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:o._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:r}},n,i){return(0,o.or)(...n.map(n=>(0,o.and)(d(e,t,n,r.ownProperties),o._`${i} = ${n}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=a,t.isOwnProperty=c,t.propertyInData=function(e,t,r,n){const i=o._`${t}${(0,o.getProperty)(r)} !== undefined`;return n?o._`${i} && ${c(e,t,r)}`:i},t.noPropertyInData=d,t.allSchemaProperties=l,t.schemaProperties=function(e,t){return l(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:a},it:c},d,l,u){const h=u?o._`${e}, ${t}, ${n}${s}`:t,f=[[i.default.instancePath,(0,o.strConcat)(i.default.instancePath,a)],[i.default.parentData,c.parentData],[i.default.parentDataProperty,c.parentDataProperty],[i.default.rootData,i.default.rootData]];c.opts.dynamicRef&&f.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);const p=o._`${h}, ${r.object(...f)}`;return l!==o.nil?o._`${d}.call(${l}, ${p})`:o._`${d}(${p})`};const u=o._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},r){const n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,a=i(r,n);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:o._`${"new RegExp"===i.code?u:(0,s.useFunc)(e,i)}(${r}, ${n})`})},t.validateArray=function(e){const{gen:t,data:r,keyword:i,it:s}=e,a=t.name("valid");if(s.allErrors){const e=t.let("valid",!0);return c(()=>t.assign(e,!1)),e}return t.var(a,!0),c(()=>t.break()),a;function c(s){const c=t.const("len",o._`${r}.length`);t.forRange("i",0,c,r=>{e.subschema({keyword:i,dataProp:r,dataPropType:n.Type.Num},a),t.if((0,o.not)(a),s)})}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:i,it:s}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(e=>(0,n.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;const a=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((r,n)=>{const s=e.subschema({keyword:i,schemaProp:n,compositeRule:!0},c);t.assign(a,o._`${a} || ${c}`),e.mergeValidEvaluated(s,c)||t.if((0,o.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}},94614:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n={data:new o.Name("data"),valCxt:new o.Name("valCxt"),instancePath:new o.Name("instancePath"),parentData:new o.Name("parentData"),parentDataProperty:new o.Name("parentDataProperty"),rootData:new o.Name("rootData"),dynamicAnchors:new o.Name("dynamicAnchors"),vErrors:new o.Name("vErrors"),errors:new o.Name("errors"),this:new o.Name("this"),self:new o.Name("self"),scope:new o.Name("scope"),json:new o.Name("json"),jsonPos:new o.Name("jsonPos"),jsonLen:new o.Name("jsonLen"),jsonPart:new o.Name("jsonPart")};t.default=n},94741:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(28512),n={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const i=t.name("valid");r.forEach((t,r)=>{if((0,o.alwaysValidSchema)(n,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},i);e.ok(i),e.mergeEvaluated(s)})}};t.default=n},94766:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderValidator=t.ProviderValidationError=void 0;const r=["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method"];class o extends Error{field;constructor(e,t){super(e),this.field=t,this.name="ProviderValidationError"}}t.ProviderValidationError=o,t.ProviderValidator=class{validate(e,t){if(!e.clientId||0===e.clientId.trim().length)throw new o(`Provider "${t}" must have a clientId`,"clientId");if(!e.authorizationUrl||0===e.authorizationUrl.trim().length)throw new o(`Provider "${t}" must have an authorizationUrl`,"authorizationUrl");if(!e.tokenUrl||0===e.tokenUrl.trim().length)throw new o(`Provider "${t}" must have a tokenUrl`,"tokenUrl");if(this.validateUrl(e.authorizationUrl,t,"authorizationUrl"),this.validateUrl(e.tokenUrl,t,"tokenUrl"),e.userInfoUrl&&this.validateUrl(e.userInfoUrl,t,"userInfoUrl"),e.proxyMode&&!e.requiresClientSecret)throw new o(`Provider "${t}" with proxyMode=true must have requiresClientSecret=true`,"proxyMode");e.customParams&&this.validateCustomParams(e.customParams,t)}validateUrl(e,t,r){try{const n=new URL(e);if("http:"!==n.protocol&&"https:"!==n.protocol)throw new o(`Provider "${t}" ${r} must use HTTP or HTTPS protocol`,r)}catch(e){if(e instanceof o)throw e;throw new o(`Provider "${t}" ${r} is not a valid URL: ${e instanceof Error?e.message:String(e)}`,r)}}validateCustomParams(e,t){for(const[n,i]of Object.entries(e)){const e=n.toLowerCase();if(r.includes(e))throw new o(`Provider "${t}" custom parameter "${n}" conflicts with reserved OAuth parameter. Reserved parameters: ${r.join(", ")}`,`customParams.${n}`);if(!i||0===i.trim().length)throw new o(`Provider "${t}" custom parameter "${n}" has empty value`,`customParams.${n}`)}}async testProvider(e,t){try{const r=await t(e.authorizationUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return r.ok||405===r.status}catch(e){return!1}}}},95014:(e,t)=>{"use strict";function r(e){const t=e.length;let r,o=0,n=0;for(;n<t;)o++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return o}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'},95277:function(e,t,r){"use strict";var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||o(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.createStatusListManager=t.StatusList2021Manager=t.createDelegationVerifier=t.DelegationCredentialVerifier=t.createDelegationIssuer=t.DelegationCredentialIssuer=t.createDelegationErrorFormatter=t.DelegationErrorFormatter=t.OAuthRequiredError=t.DelegationRequiredError=t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=t.createProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=t.ProofVerificationError=t.migrateLegacyKeys=t.StorageKeyHelpers=t.createStorageProviders=t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=t.BatchDelegationService=t.OAuthTokenRetrievalService=t.ProviderValidationError=t.ProviderValidator=t.CredentialAuthModeError=t.ConsentOnlyModeError=t.ProviderResolver=t.OAuthProviderRegistry=t.ToolContextBuilder=t.defaultSecretResolver=t.OAuthService=t.OAuthConfigService=t.createSessionRegistrationService=t.SessionRegistrationService=t.authorizationMatches=t.AccessControlApiService=t.ProofVerifier=t.CryptoService=t.PolicyService=t.ToolProtectionService=t.MCPIRuntimeBase=t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.createDefaultConsoleLogger=t.logger=t.IdpTokenResolver=t.UserDidManager=t.isPolicyEnabled=t.hasMergedPolicy=t.extractPolicy=t.getPolicy=t.hasMergedToolProtections=t.extractToolProtections=t.getToolProtection=t.fetchRemoteConfig=t.bytesToBase64=t.base64urlDecodeToString=t.base64urlDecodeToBytes=t.base64urlEncodeFromString=t.base64urlEncodeFromBytes=t.parseVCJWT=t.completeVCJWT=t.createUnsignedVCJWT=t.canonicalizeJSON=t.getSchemaStats=t.getCriticalSchemas=t.getSchemaById=t.getSchemasByCategory=t.getAllSchemas=t.SCHEMA_REGISTRY=t.createSchemaVerifier=t.SchemaVerifier=t.isValidBase58=t.base58Decode=t.base58Encode=t.resolveDidKeySync=t.publicKeyToJwk=t.extractPublicKeyFromDidKey=t.isEd25519DidKey=t.createDidKeyResolver=t.MemoryDelegationGraphStorage=t.MemoryStatusListStorage=t.createCascadingRevocationManager=t.CascadingRevocationManager=t.createDelegationGraph=t.DelegationGraphManager=t.isIndexSet=t.BitstringManager=void 0;var i=r(27087);Object.defineProperty(t,"CryptoProvider",{enumerable:!0,get:function(){return i.CryptoProvider}}),Object.defineProperty(t,"ClockProvider",{enumerable:!0,get:function(){return i.ClockProvider}}),Object.defineProperty(t,"FetchProvider",{enumerable:!0,get:function(){return i.FetchProvider}}),Object.defineProperty(t,"StorageProvider",{enumerable:!0,get:function(){return i.StorageProvider}}),Object.defineProperty(t,"NonceCacheProvider",{enumerable:!0,get:function(){return i.NonceCacheProvider}}),Object.defineProperty(t,"IdentityProvider",{enumerable:!0,get:function(){return i.IdentityProvider}});var s=r(48505);Object.defineProperty(t,"MemoryStorageProvider",{enumerable:!0,get:function(){return s.MemoryStorageProvider}}),Object.defineProperty(t,"MemoryNonceCacheProvider",{enumerable:!0,get:function(){return s.MemoryNonceCacheProvider}}),Object.defineProperty(t,"MemoryIdentityProvider",{enumerable:!0,get:function(){return s.MemoryIdentityProvider}});var a=r(23137);Object.defineProperty(t,"MCPIRuntimeBase",{enumerable:!0,get:function(){return a.MCPIRuntimeBase}}),n(r(53871),t);var c=r(9249);Object.defineProperty(t,"ToolProtectionService",{enumerable:!0,get:function(){return c.ToolProtectionService}});var d=r(11755);Object.defineProperty(t,"PolicyService",{enumerable:!0,get:function(){return d.PolicyService}});var l=r(81296);Object.defineProperty(t,"CryptoService",{enumerable:!0,get:function(){return l.CryptoService}});var u=r(45395);Object.defineProperty(t,"ProofVerifier",{enumerable:!0,get:function(){return u.ProofVerifier}});var h=r(36255);Object.defineProperty(t,"AccessControlApiService",{enumerable:!0,get:function(){return h.AccessControlApiService}}),Object.defineProperty(t,"authorizationMatches",{enumerable:!0,get:function(){return h.authorizationMatches}});var f=r(47919);Object.defineProperty(t,"SessionRegistrationService",{enumerable:!0,get:function(){return f.SessionRegistrationService}}),Object.defineProperty(t,"createSessionRegistrationService",{enumerable:!0,get:function(){return f.createSessionRegistrationService}});var p=r(97405);Object.defineProperty(t,"OAuthConfigService",{enumerable:!0,get:function(){return p.OAuthConfigService}});var m=r(62175);Object.defineProperty(t,"OAuthService",{enumerable:!0,get:function(){return m.OAuthService}}),Object.defineProperty(t,"defaultSecretResolver",{enumerable:!0,get:function(){return m.defaultSecretResolver}});var g=r(72114);Object.defineProperty(t,"ToolContextBuilder",{enumerable:!0,get:function(){return g.ToolContextBuilder}});var y=r(50399);Object.defineProperty(t,"OAuthProviderRegistry",{enumerable:!0,get:function(){return y.OAuthProviderRegistry}});var v=r(68252);Object.defineProperty(t,"ProviderResolver",{enumerable:!0,get:function(){return v.ProviderResolver}}),Object.defineProperty(t,"ConsentOnlyModeError",{enumerable:!0,get:function(){return v.ConsentOnlyModeError}}),Object.defineProperty(t,"CredentialAuthModeError",{enumerable:!0,get:function(){return v.CredentialAuthModeError}});var w=r(94766);Object.defineProperty(t,"ProviderValidator",{enumerable:!0,get:function(){return w.ProviderValidator}}),Object.defineProperty(t,"ProviderValidationError",{enumerable:!0,get:function(){return w.ProviderValidationError}});var _=r(42769);Object.defineProperty(t,"OAuthTokenRetrievalService",{enumerable:!0,get:function(){return _.OAuthTokenRetrievalService}});var b=r(30124);Object.defineProperty(t,"BatchDelegationService",{enumerable:!0,get:function(){return b.BatchDelegationService}});var S=r(48021);Object.defineProperty(t,"InMemoryOAuthConfigCache",{enumerable:!0,get:function(){return S.InMemoryOAuthConfigCache}}),Object.defineProperty(t,"NoOpOAuthConfigCache",{enumerable:!0,get:function(){return S.NoOpOAuthConfigCache}});var P=r(92182);Object.defineProperty(t,"createStorageProviders",{enumerable:!0,get:function(){return P.createStorageProviders}}),Object.defineProperty(t,"StorageKeyHelpers",{enumerable:!0,get:function(){return P.StorageKeyHelpers}}),Object.defineProperty(t,"migrateLegacyKeys",{enumerable:!0,get:function(){return P.migrateLegacyKeys}});var $=r(53683);Object.defineProperty(t,"ProofVerificationError",{enumerable:!0,get:function(){return $.ProofVerificationError}}),Object.defineProperty(t,"PROOF_VERIFICATION_ERROR_CODES",{enumerable:!0,get:function(){return $.PROOF_VERIFICATION_ERROR_CODES}}),Object.defineProperty(t,"createProofVerificationError",{enumerable:!0,get:function(){return $.createProofVerificationError}});var k=r(85601);Object.defineProperty(t,"InMemoryToolProtectionCache",{enumerable:!0,get:function(){return k.InMemoryToolProtectionCache}}),Object.defineProperty(t,"NoOpToolProtectionCache",{enumerable:!0,get:function(){return k.NoOpToolProtectionCache}});var E=r(4901);Object.defineProperty(t,"DelegationRequiredError",{enumerable:!0,get:function(){return E.DelegationRequiredError}});var I=r(27399);Object.defineProperty(t,"OAuthRequiredError",{enumerable:!0,get:function(){return I.OAuthRequiredError}});var C=r(78322);Object.defineProperty(t,"DelegationErrorFormatter",{enumerable:!0,get:function(){return C.DelegationErrorFormatter}}),Object.defineProperty(t,"createDelegationErrorFormatter",{enumerable:!0,get:function(){return C.createDelegationErrorFormatter}});var T=r(30845);Object.defineProperty(t,"DelegationCredentialIssuer",{enumerable:!0,get:function(){return T.DelegationCredentialIssuer}}),Object.defineProperty(t,"createDelegationIssuer",{enumerable:!0,get:function(){return T.createDelegationIssuer}});var O=r(77460);Object.defineProperty(t,"DelegationCredentialVerifier",{enumerable:!0,get:function(){return O.DelegationCredentialVerifier}}),Object.defineProperty(t,"createDelegationVerifier",{enumerable:!0,get:function(){return O.createDelegationVerifier}});var D=r(98358);Object.defineProperty(t,"StatusList2021Manager",{enumerable:!0,get:function(){return D.StatusList2021Manager}}),Object.defineProperty(t,"createStatusListManager",{enumerable:!0,get:function(){return D.createStatusListManager}});var A=r(46610);Object.defineProperty(t,"BitstringManager",{enumerable:!0,get:function(){return A.BitstringManager}}),Object.defineProperty(t,"isIndexSet",{enumerable:!0,get:function(){return A.isIndexSet}});var R=r(55921);Object.defineProperty(t,"DelegationGraphManager",{enumerable:!0,get:function(){return R.DelegationGraphManager}}),Object.defineProperty(t,"createDelegationGraph",{enumerable:!0,get:function(){return R.createDelegationGraph}});var x=r(24886);Object.defineProperty(t,"CascadingRevocationManager",{enumerable:!0,get:function(){return x.CascadingRevocationManager}}),Object.defineProperty(t,"createCascadingRevocationManager",{enumerable:!0,get:function(){return x.createCascadingRevocationManager}});var j=r(7318);Object.defineProperty(t,"MemoryStatusListStorage",{enumerable:!0,get:function(){return j.MemoryStatusListStorage}});var N=r(44558);Object.defineProperty(t,"MemoryDelegationGraphStorage",{enumerable:!0,get:function(){return N.MemoryDelegationGraphStorage}});var M=r(63146);Object.defineProperty(t,"createDidKeyResolver",{enumerable:!0,get:function(){return M.createDidKeyResolver}}),Object.defineProperty(t,"isEd25519DidKey",{enumerable:!0,get:function(){return M.isEd25519DidKey}}),Object.defineProperty(t,"extractPublicKeyFromDidKey",{enumerable:!0,get:function(){return M.extractPublicKeyFromDidKey}}),Object.defineProperty(t,"publicKeyToJwk",{enumerable:!0,get:function(){return M.publicKeyToJwk}}),Object.defineProperty(t,"resolveDidKeySync",{enumerable:!0,get:function(){return M.resolveDidKeySync}});var z=r(69459);Object.defineProperty(t,"base58Encode",{enumerable:!0,get:function(){return z.base58Encode}}),Object.defineProperty(t,"base58Decode",{enumerable:!0,get:function(){return z.base58Decode}}),Object.defineProperty(t,"isValidBase58",{enumerable:!0,get:function(){return z.isValidBase58}});var U=r(37121);Object.defineProperty(t,"SchemaVerifier",{enumerable:!0,get:function(){return U.SchemaVerifier}}),Object.defineProperty(t,"createSchemaVerifier",{enumerable:!0,get:function(){return U.createSchemaVerifier}});var q=r(11300);Object.defineProperty(t,"SCHEMA_REGISTRY",{enumerable:!0,get:function(){return q.SCHEMA_REGISTRY}}),Object.defineProperty(t,"getAllSchemas",{enumerable:!0,get:function(){return q.getAllSchemas}}),Object.defineProperty(t,"getSchemasByCategory",{enumerable:!0,get:function(){return q.getSchemasByCategory}}),Object.defineProperty(t,"getSchemaById",{enumerable:!0,get:function(){return q.getSchemaById}}),Object.defineProperty(t,"getCriticalSchemas",{enumerable:!0,get:function(){return q.getCriticalSchemas}}),Object.defineProperty(t,"getSchemaStats",{enumerable:!0,get:function(){return q.getSchemaStats}});var K=r(63969);Object.defineProperty(t,"canonicalizeJSON",{enumerable:!0,get:function(){return K.canonicalizeJSON}}),Object.defineProperty(t,"createUnsignedVCJWT",{enumerable:!0,get:function(){return K.createUnsignedVCJWT}}),Object.defineProperty(t,"completeVCJWT",{enumerable:!0,get:function(){return K.completeVCJWT}}),Object.defineProperty(t,"parseVCJWT",{enumerable:!0,get:function(){return K.parseVCJWT}});var V=r(98448);Object.defineProperty(t,"base64urlEncodeFromBytes",{enumerable:!0,get:function(){return V.base64urlEncodeFromBytes}}),Object.defineProperty(t,"base64urlEncodeFromString",{enumerable:!0,get:function(){return V.base64urlEncodeFromString}}),Object.defineProperty(t,"base64urlDecodeToBytes",{enumerable:!0,get:function(){return V.base64urlDecodeToBytes}}),Object.defineProperty(t,"base64urlDecodeToString",{enumerable:!0,get:function(){return V.base64urlDecodeToString}}),Object.defineProperty(t,"bytesToBase64",{enumerable:!0,get:function(){return V.bytesToBase64}}),n(r(77311),t);var L=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return L.fetchRemoteConfig}}),Object.defineProperty(t,"getToolProtection",{enumerable:!0,get:function(){return L.getToolProtection}}),Object.defineProperty(t,"extractToolProtections",{enumerable:!0,get:function(){return L.extractToolProtections}}),Object.defineProperty(t,"hasMergedToolProtections",{enumerable:!0,get:function(){return L.hasMergedToolProtections}}),Object.defineProperty(t,"getPolicy",{enumerable:!0,get:function(){return L.getPolicy}}),Object.defineProperty(t,"extractPolicy",{enumerable:!0,get:function(){return L.extractPolicy}}),Object.defineProperty(t,"hasMergedPolicy",{enumerable:!0,get:function(){return L.hasMergedPolicy}}),Object.defineProperty(t,"isPolicyEnabled",{enumerable:!0,get:function(){return L.isPolicyEnabled}});var F=r(65067);Object.defineProperty(t,"UserDidManager",{enumerable:!0,get:function(){return F.UserDidManager}});var H=r(202);Object.defineProperty(t,"IdpTokenResolver",{enumerable:!0,get:function(){return H.IdpTokenResolver}});var B=r(46171);Object.defineProperty(t,"logger",{enumerable:!0,get:function(){return B.logger}}),Object.defineProperty(t,"createDefaultConsoleLogger",{enumerable:!0,get:function(){return B.createDefaultConsoleLogger}})},96214:e=>{"use strict";const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function o(e){let t="",r=0,o=0;for(o=0;o<e.length;o++)if(r=e[o].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[o];break}for(o+=1;o<e.length;o++){if(r=e[o].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[o]}return t}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function i(e){return e.length=0,!0}function s(e,t,r){if(e.length){const n=o(e);if(""===n)return r.error=!0,!1;t.push(n),e.length=0}return!0}function a(e){if(function(e){let t=0;for(let r=0;r<e.length;r++)":"===e[r]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},n=[],a=[];let c=!1,d=!1,l=s;for(let o=0;o<e.length;o++){const s=e[o];if("["!==s&&"]"!==s)if(":"!==s)if("%"===s){if(!l(a,n,r))break;l=i}else a.push(s);else{if(!0===c&&(d=!0),!l(a,n,r))break;if(++t>7){r.error=!0;break}o>0&&":"===e[o-1]&&(c=!0),n.push(":")}}return a.length&&(l===i?r.zone=a.join(""):d?n.push(a.join("")):n.push(o(a))),r.address=n.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}e.exports={nonSimpleDomain:n,recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let o=unescape(e.host);if(!r(o)){const t=a(o);o=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(o)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let o=-1,n=0;for(;n=t.length;){if(1===n){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===n){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===n&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(o=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,o)),t=t.slice(o)}return r.join("")},isIPv4:r,isUUID:t,normalizeIPv6:a,stringArrayToHexStripped:o}},96889:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const o=r(2882),n=r(54029),i=r(84204),s=r(54029),a=r(76899),c=r(1074),d=r(24456),l=r(36556),u=r(94614),h=r(60234),f=r(28512),p=r(57747);function m({gen:e,validateName:t,schema:r,schemaEnv:o,opts:n},i){n.code.es5?e.func(t,l._`${u.default.data}, ${u.default.valCxt}`,o.$async,()=>{e.code(l._`"use strict"; ${g(r,n)}`),function(e,t){e.if(u.default.valCxt,()=>{e.var(u.default.instancePath,l._`${u.default.valCxt}.${u.default.instancePath}`),e.var(u.default.parentData,l._`${u.default.valCxt}.${u.default.parentData}`),e.var(u.default.parentDataProperty,l._`${u.default.valCxt}.${u.default.parentDataProperty}`),e.var(u.default.rootData,l._`${u.default.valCxt}.${u.default.rootData}`),t.dynamicRef&&e.var(u.default.dynamicAnchors,l._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{e.var(u.default.instancePath,l._`""`),e.var(u.default.parentData,l._`undefined`),e.var(u.default.parentDataProperty,l._`undefined`),e.var(u.default.rootData,u.default.data),t.dynamicRef&&e.var(u.default.dynamicAnchors,l._`{}`)})}(e,n),e.code(i)}):e.func(t,l._`${u.default.data}, ${function(e){return l._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${e.dynamicRef?l._`, ${u.default.dynamicAnchors}={}`:l.nil}}={}`}(n)}`,o.$async,()=>e.code(g(r,n)).code(i))}function g(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?l._`/*# sourceURL=${r} */`:l.nil}function y({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function v(e){return"boolean"!=typeof e.schema}function w(e){(0,f.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:o,self:n}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,f.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function _(e,t){if(e.opts.jtd)return S(e,[],!1,t);const r=(0,n.getSchemaTypes)(e.schema);S(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function b({gen:e,schemaEnv:t,schema:r,errSchemaPath:o,opts:n}){const i=r.$comment;if(!0===n.$comment)e.code(l._`${u.default.self}.logger.log(${i})`);else if("function"==typeof n.$comment){const r=l.str`${o}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(l._`${u.default.self}.opts.$comment(${i}, ${r}, ${n}.schema)`)}}function S(e,t,r,o){const{gen:n,schema:a,data:c,allErrors:d,opts:h,self:p}=e,{RULES:m}=p;function g(f){(0,i.shouldUseGroup)(a,f)&&(f.type?(n.if((0,s.checkDataType)(f.type,c,h.strictNumbers)),P(e,f),1===t.length&&t[0]===f.type&&r&&(n.else(),(0,s.reportTypeError)(e)),n.endIf()):P(e,f),d||n.if(l._`${u.default.errors} === ${o||0}`))}!a.$ref||!h.ignoreKeywordsWithRef&&(0,f.schemaHasRulesButRef)(a,m)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{$(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const o of e.dataTypes)$(t,o)?r.push(o):t.includes("integer")&&"number"===o&&r.push("integer");e.dataTypes=r}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const o in r){const n=r[o];if("object"==typeof n&&(0,i.shouldUseRule)(e.schema,n)){const{type:r}=n.definition;r.length&&!r.some(e=>{return o=e,(r=t).includes(o)||"number"===o&&r.includes("integer");var r,o})&&k(e,`missing type "${r.join(",")}" for keyword "${o}"`)}}}(e,e.dataTypes))}(e,t),n.block(()=>{for(const e of m.rules)g(e);g(m.post)})):n.block(()=>I(e,"$ref",m.all.$ref.definition))}function P(e,t){const{gen:r,schema:o,opts:{useDefaults:n}}=e;n&&(0,a.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,i.shouldUseRule)(o,r)&&I(e,r.keyword,r.definition,t.type)})}function $(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,f.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){v(e)&&(w(e),y(e))?function(e){const{schema:t,opts:r,gen:o}=e;m(e,()=>{r.$comment&&t.$comment&&b(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,f.checkStrictMode)(e,"default is ignored in the schema root")}(e),o.let(u.default.vErrors,null),o.let(u.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",l._`${r}.evaluated`),t.if(l._`${e.evaluated}.dynamicProps`,()=>t.assign(l._`${e.evaluated}.props`,l._`undefined`)),t.if(l._`${e.evaluated}.dynamicItems`,()=>t.assign(l._`${e.evaluated}.items`,l._`undefined`))}(e),_(e),function(e){const{gen:t,schemaEnv:r,validateName:o,ValidationError:n,opts:i}=e;r.$async?t.if(l._`${u.default.errors} === 0`,()=>t.return(u.default.data),()=>t.throw(l._`new ${n}(${u.default.vErrors})`)):(t.assign(l._`${o}.errors`,u.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:r,items:o}){r instanceof l.Name&&e.assign(l._`${t}.props`,r),o instanceof l.Name&&e.assign(l._`${t}.items`,o)}(e),t.return(l._`${u.default.errors} === 0`))}(e)})}(e):m(e,()=>(0,o.topBoolOrEmptySchema)(e))};class E{constructor(e,t,r){if((0,c.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,f.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",O(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,c.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",u.default.errors))}result(e,t,r){this.failResult((0,l.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,l.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(l._`${t} !== undefined && (${(0,l.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?p.reportExtraError:p.reportError)(this,this.def.error,t)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=l.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=l.nil,t=l.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:n,def:i}=this;r.if((0,l.or)(l._`${o} === undefined`,t)),e!==l.nil&&r.assign(e,!0),(n.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==l.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:o,it:n}=this;return(0,l.or)(function(){if(r.length){if(!(t instanceof l.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return l._`${(0,s.checkDataTypes)(e,t,n.opts.strictNumbers,s.DataType.Wrong)}`}return l.nil}(),function(){if(o.validateSchema){const r=e.scopeValue("validate$data",{ref:o.validateSchema});return l._`!${r}(${t})`}return l.nil}())}subschema(e,t){const r=(0,d.getSubschema)(this.it,e);(0,d.extendSubschemaData)(r,this.it,e),(0,d.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return function(e,t){v(e)&&(w(e),y(e))?function(e,t){const{schema:r,gen:o,opts:n}=e;n.$comment&&r.$comment&&b(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,h.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=o.const("_errs",u.default.errors);_(e,i),o.var(t,l._`${i} === ${u.default.errors}`)}(e,t):(0,o.boolOrEmptySchema)(e,t)}(n,t),n}mergeEvaluated(e,t){const{it:r,gen:o}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=f.mergeEvaluated.props(o,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=f.mergeEvaluated.items(o,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return o.if(t,()=>this.mergeEvaluated(e,l.Name)),!0}}function I(e,t,r,o){const n=new E(e,r,t);"code"in r?r.code(n,o):n.$data&&r.validate?(0,c.funcKeywordCode)(n,r):"macro"in r?(0,c.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,c.funcKeywordCode)(n,r)}t.KeywordCxt=E;const C=/^\/(?:[^~]|~0|~1)*$/,T=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function O(e,{dataLevel:t,dataNames:r,dataPathArr:o}){let n,i;if(""===e)return u.default.rootData;if("/"===e[0]){if(!C.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,i=u.default.rootData}else{const s=T.exec(e);if(!s)throw new Error(`Invalid JSON-pointer: ${e}`);const a=+s[1];if(n=s[2],"#"===n){if(a>=t)throw new Error(c("property/index",a));return o[t-a]}if(a>t)throw new Error(c("data",a));if(i=r[t-a],!n)return i}let s=i;const a=n.split("/");for(const e of a)e&&(i=l._`${i}${(0,l.getProperty)((0,f.unescapeJsonPointer)(e))}`,s=l._`${s} && ${i}`);return s;function c(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}t.getData=O},97405:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConfigService=void 0;const o=r(48021);t.OAuthConfigService=class{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,cacheTtl:e.cacheTtl??3e5,logger:e.logger||(()=>{}),cache:e.cache||new o.InMemoryOAuthConfigCache}}async getOAuthConfig(e){const t=await this.config.cache.get(e);if(t)return this.config.logger("[OAuthConfigService] Cache hit",{projectId:e}),t;const r=`${this.config.baseUrl}/api/v1/bouncer/projects/${encodeURIComponent(e)}/providers`;this.config.logger("[OAuthConfigService] Fetching config from API",{projectId:e,url:r});try{const t=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"}});if(!t.ok){const e=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch OAuth config: ${t.status} ${t.statusText} - ${e}`)}const o=await t.json();if(!o.success||!o.data)throw new Error("Invalid API response: missing success or data field");const n=o.data.providers||{};if("object"!=typeof n||Array.isArray(n))throw new Error("Invalid API response: providers must be an object, not an array");const i={};for(const[e,t]of Object.entries(n)){const r=t;i[e]={clientId:r.clientId??r.client_id??"",clientSecret:r.clientSecret??r.client_secret??null,authorizationUrl:r.authorizationUrl??r.authorization_url??"",tokenUrl:r.tokenUrl??r.token_url??"",userInfoUrl:r.userInfoUrl??r.user_info_url,supportsPKCE:r.supportsPKCE??r.supports_pkce??!1,requiresClientSecret:r.requiresClientSecret??r.requires_client_secret??!0,scopes:r.scopes??[],defaultScopes:r.defaultScopes??r.default_scopes,proxyMode:r.proxyMode??r.proxy_mode??!1,customParams:r.customParams??r.custom_params,tokenEndpointAuthMethod:r.tokenEndpointAuthMethod??r.token_endpoint_auth_method,responseType:r.responseType??r.response_type,grantType:r.grantType??r.grant_type}}const s=o.data.configuredProvider??o.data.configured_provider??null,a={providers:i,configuredProvider:s};return await this.config.cache.set(e,a,this.config.cacheTtl),this.config.logger("[OAuthConfigService] Config fetched and cached",{projectId:e,providerCount:Object.keys(i).length,providers:Object.keys(i),configuredProvider:s,expiresAt:new Date(Date.now()+this.config.cacheTtl).toISOString()}),a}catch(t){throw this.config.logger("[OAuthConfigService] API fetch failed",{projectId:e,error:t instanceof Error?t.message:String(t)}),t}}async clearCache(e){await this.config.cache.delete(e),this.config.logger("[OAuthConfigService] Cache cleared",{projectId:e})}async clearAllCache(){await this.config.cache.clear(),this.config.logger("[OAuthConfigService] All cache cleared")}}},98358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=void 0,t.createStatusListManager=function(e,t,r,o,n,s){return new i(e,t,r,o,n,s)};const o=r(46610),n=r(63969);class i{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;constructor(e,t,r,o,n,i){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=o,this.decompressor=n,this.statusListBaseUrl=i?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=i?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r,statusListIndex:i}=e,s=await this.storage.getStatusList(r);if(!s)throw new Error(`Status list not found: ${r}`);const a=await o.BitstringManager.decode(s.credentialSubject.encodedList,this.compressor,this.decompressor),c=parseInt(i,10);a.setBit(c,t);const d=await a.encode(),l={...s,credentialSubject:{...s.credentialSubject,encodedList:d}},u={...l};delete u.proof;const h=(0,n.canonicalizeJSON)(u),f=await this.signingFunction(h,this.identity.getDid(),this.identity.getKeyId()),p={...l,proof:f};await this.storage.setStatusList(r,p)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,n=await this.storage.getStatusList(t);if(!n)return!1;const i=await o.BitstringManager.decode(n.credentialSubject.encodedList,this.compressor,this.decompressor),s=parseInt(r,10);return i.getBit(s)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await o.BitstringManager.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new o.BitstringManager(this.defaultListSize,this.compressor,this.decompressor),i=await r.encode(),s={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:i}},a=(0,n.canonicalizeJSON)(s),c=await this.signingFunction(a,this.identity.getDid(),this.identity.getKeyId()),d={...s,proof:c};await this.storage.setStatusList(e,d)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}t.StatusList2021Manager=i},98448:(e,t)=>{"use strict";function r(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}Object.defineProperty(t,"__esModule",{value:!0}),t.base64urlDecodeToString=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof Buffer){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");try{return Buffer.from(t,"base64").toString("utf-8")}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}}if("undefined"!=typeof atob)try{const e=atob(t);if("undefined"!=typeof TextDecoder){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return(new TextDecoder).decode(t)}return e}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}throw new Error("Neither Buffer nor atob is available")},t.base64urlDecodeToBytes=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}return new Uint8Array(Buffer.from(t,"base64"))},t.base64urlEncodeFromString=function(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");if("undefined"!=typeof btoa)try{const t=(new TextEncoder).encode(e),r=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}catch{return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}throw new Error("Neither Buffer nor btoa is available")},t.base64urlEncodeFromBytes=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.bytesToBase64=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")},t.base64ToBytes=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}},99147:(e,t,r)=>{"use strict";const{isUUID:o}=r(96214),n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=["http","https","ws","wss","urn","urn:uuid"];function s(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function a(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function c(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const d={scheme:"http",domainHost:!0,parse:a,serialize:c},l={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=s(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(s(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},u={http:d,https:{scheme:"https",domainHost:d.domainHost,parse:a,serialize:c},ws:l,wss:{scheme:"wss",domainHost:l.domainHost,parse:l.parse,serialize:l.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(n);if(r){const o=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const n=h(`${o}:${t.nid||e.nid}`);e.path=void 0,n&&(e=n.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",o=e.nid.toLowerCase(),n=h(`${r}:${t.nid||o}`);n&&(e=n.serialize(e,t));const i=e,s=e.nss;return i.path=`${o||t.nid}:${s}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&o(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function h(e){return e&&(u[e]||u[e.toLowerCase()])||void 0}Object.setPrototypeOf(u,null),e.exports={wsIsSecure:s,SCHEMES:u,isValidSchemeName:function(e){return-1!==i.indexOf(e)},getSchemeHandler:h}},99352:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const o=r(36556),n=r(28512),i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>o.str`must match "${e.ifClause}" schema`,params:({params:e})=>o._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:r,it:i}=e;void 0===r.then&&void 0===r.else&&(0,n.checkStrictMode)(i,'"if" without "then" and "else" is ignored');const a=s(i,"then"),c=s(i,"else");if(!a&&!c)return;const d=t.let("valid",!0),l=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);e.mergeEvaluated(t)}(),e.reset(),a&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(l,u("then",r),u("else",r))}else a?t.if(l,u("then")):t.if((0,o.not)(l),u("else"));function u(r,n){return()=>{const i=e.subschema({keyword:r},l);t.assign(d,l),e.mergeValidEvaluated(i,d),n?t.assign(n,o._`${r}`):e.setParams({ifClause:r})}}e.pass(d,()=>e.error(!0))}};function s(e,t){const r=e.schema[t];return void 0!==r&&!(0,n.alwaysValidSchema)(e,r)}t.default=i},99881:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=require("node:process");function t(e,t,r){function o(r,o){var n;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,o);for(const e in s.prototype)e in r||Object.defineProperty(r,e,{value:s.prototype[e].bind(r)});r._zod.constr=s,r._zod.def=o}const n=r?.Parent??Object;class i extends n{}function s(e){var t;const n=r?.Parent?new i:this;o(n,e),(t=n._zod).deferred??(t.deferred=[]);for(const e of n._zod.deferred)e();return n}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Object.freeze({status:"aborted"}),Symbol("zod_brand");class o extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const n={};function i(e){return e&&Object.assign(n,e),n}const s=/^[cC][^\s-]{8,}$/,a=/^[0-9a-z]+$/,c=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,d=/^[0-9a-vA-V]{20}$/,l=/^[A-Za-z0-9]{27}$/,u=/^[a-zA-Z0-9_-]{21}$/,h=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,f=/^([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})$/,p=e=>e?new 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)$/,m=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,g=/^(?:(?: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])$/,y=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,v=/^((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])$/,w=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,b=/^[A-Za-z0-9_-]*$/,S=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,P=/^\+(?:[0-9]){6,14}[0-9]$/,$="(?:(?:\\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])))",k=new RegExp(`^${$}$`);function E(e){const 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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const I=/^\d+$/,C=/^-?\d+(?:\.\d+)?/i,T=/true|false/i,O=/null/i,D=/^[^A-Z]*$/,A=/^[^a-z]*$/;function R(e,t){return"bigint"==typeof t?t.toString():t}function x(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function j(e){return null==e}function N(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function M(e,t,r){Object.defineProperty(e,t,{get(){{const o=r();return e[t]=o,o}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function z(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function U(e){return JSON.stringify(e)}const q=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function K(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const V=x(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function L(e){if(!1===K(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==K(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const F=new Set(["string","number","symbol"]);function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function B(e,t,r){const o=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(o._zod.parent=e),o}function J(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}new Set(["string","number","bigint","boolean","symbol","undefined"]);const W={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Z(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function G(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Y(e){return"string"==typeof e?e:e?.message}function Q(e,t,r){const o={...e,path:e.path??[]};if(!e.message){const n=Y(e.inst?._zod.def?.error?.(e))??Y(t?.error?.(e))??Y(r.customError?.(e))??Y(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function X(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ee(...e){const[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}const te=t("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),re={number:"number",bigint:"bigint",object:"date"},oe=t("$ZodCheckLessThan",(e,t)=>{te.init(e,t);const r=re[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ne=t("$ZodCheckGreaterThan",(e,t)=>{te.init(e,t);const r=re[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ie=t("$ZodCheckMultipleOf",(e,t)=>{te.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),se=t("$ZodCheckNumberFormat",(e,t)=>{te.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),o=r?"int":"number",[n,i]=W[t.format];e._zod.onattach.push(e=>{const o=e._zod.bag;o.format=t.format,o.minimum=n,o.maximum=i,r&&(o.pattern=I)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a))return void s.issues.push({expected:o,format:t.format,code:"invalid_type",input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}))}a<n&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}}),ae=t("$ZodCheckMaxLength",(e,t)=>{var r;te.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!j(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const n=X(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ce=t("$ZodCheckMinLength",(e,t)=>{var r;te.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!j(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const n=X(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),de=t("$ZodCheckLengthEquals",(e,t)=>{var r;te.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!j(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const o=r.value,n=o.length;if(n===t.length)return;const i=X(o),s=n>t.length;r.issues.push({origin:i,...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})}}),le=t("$ZodCheckStringFormat",(e,t)=>{var r,o;te.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),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=()=>{})}),ue=t("$ZodCheckRegex",(e,t)=>{le.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})}}),he=t("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=D),le.init(e,t)}),fe=t("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=A),le.init(e,t)}),pe=t("$ZodCheckIncludes",(e,t)=>{te.init(e,t);const r=H(t.includes),o=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),me=t("$ZodCheckStartsWith",(e,t)=>{te.init(e,t);const r=new RegExp(`^${H(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),ge=t("$ZodCheckEndsWith",(e,t)=>{te.init(e,t);const r=new RegExp(`.*${H(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),ye=t("$ZodCheckOverwrite",(e,t)=>{te.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ve{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),o=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of o)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const we=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,R,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_e=t("$ZodError",we),be=t("$ZodError",we,{Parent:Error}),Se=e=>(t,r,n,s)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},c=t._zod.run({value:r,issues:[]},a);if(c instanceof Promise)throw new o;if(c.issues.length){const t=new(s?.Err??e)(c.issues.map(e=>Q(e,a,i())));throw q(t,s?.callee),t}return c.value},Pe=e=>async(t,r,o,n)=>{const s=o?Object.assign(o,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>Q(e,s,i())));throw q(t,n?.callee),t}return a.value},$e=e=>(t,r,n)=>{const s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new o;return a.issues.length?{success:!1,error:new(e??_e)(a.issues.map(e=>Q(e,s,i())))}:{success:!0,data:a.value}},ke=$e(be),Ee=e=>async(t,r,o)=>{const n=o?Object.assign(o,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>Q(e,n,i())))}:{success:!0,data:s.value}},Ie=Ee(be),Ce={major:4,minor:0,patch:0},Te=t("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ce;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=Z(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,a=s._zod.check(e);if(a instanceof Promise&&!1===r?.async)throw new o;if(n||a instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(i||(i=Z(e,t)))});else{if(e.issues.length===t)continue;i||(i=Z(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,i)=>{const s=e._zod.parse(r,i);if(s instanceof Promise){if(!1===i.async)throw new o;return s.then(e=>t(e,n,i))}return t(s,n,i)}}e["~standard"]={validate:t=>{try{const r=ke(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Ie(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Oe=t("$ZodString",(e,t)=>{var r;Te.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),De=t("$ZodStringFormat",(e,t)=>{le.init(e,t),Oe.init(e,t)}),Ae=t("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=f),De.init(e,t)}),Re=t("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=p(e))}else t.pattern??(t.pattern=p());De.init(e,t)}),xe=t("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=m),De.init(e,t)}),je=t("$ZodURL",(e,t)=>{De.init(e,t),e._zod.check=r=>{try{const o=r.value,n=new URL(o),i=n.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:S.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!o.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i)}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Ne=t("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),De.init(e,t)}),Me=t("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=u),De.init(e,t)}),ze=t("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=s),De.init(e,t)}),Ue=t("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=a),De.init(e,t)}),qe=t("$ZodULID",(e,t)=>{t.pattern??(t.pattern=c),De.init(e,t)}),Ke=t("$ZodXID",(e,t)=>{t.pattern??(t.pattern=d),De.init(e,t)}),Ve=t("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=l),De.init(e,t)}),Le=t("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=E({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const o=`${t}(?:${r.join("|")})`;return new RegExp(`^${$}T(?:${o})$`)}(t)),De.init(e,t)}),Fe=t("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=k),De.init(e,t)}),He=t("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${E(t)}$`)),De.init(e,t)}),Be=t("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=h),De.init(e,t)}),Je=t("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=g),De.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),We=t("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=y),De.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ze=t("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=v),De.init(e,t)}),Ge=t("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=w),De.init(e,t),e._zod.check=r=>{const[o,n]=r.value.split("/");try{if(!n)throw new Error;const e=Number(n);if(`${e}`!==n)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Ye(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Qe=t("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_),De.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Ye(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Xe=t("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=b),De.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!b.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Ye(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})}}),et=t("$ZodE164",(e,t)=>{t.pattern??(t.pattern=P),De.init(e,t)}),tt=t("$ZodJWT",(e,t)=>{De.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[o]=r;if(!o)return!1;const n=JSON.parse(atob(o));return!("typ"in n&&"JWT"!==n?.typ||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),rt=t("$ZodNumber",(e,t)=>{Te.init(e,t),e._zod.pattern=e._zod.bag.pattern??C,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;const i="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),ot=t("$ZodNumber",(e,t)=>{se.init(e,t),rt.init(e,t)}),nt=t("$ZodBoolean",(e,t)=>{Te.init(e,t),e._zod.pattern=T,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),it=t("$ZodNull",(e,t)=>{Te.init(e,t),e._zod.pattern=O,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const o=t.value;return null===o||t.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),t}}),st=t("$ZodUnknown",(e,t)=>{Te.init(e,t),e._zod.parse=e=>e}),at=t("$ZodNever",(e,t)=>{Te.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function ct(e,t,r){e.issues.length&&t.issues.push(...G(r,e.issues)),t.value[r]=e.value}const dt=t("$ZodArray",(e,t)=>{Te.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);const i=[];for(let e=0;e<n.length;e++){const s=n[e],a=t.element._zod.run({value:s,issues:[]},o);a instanceof Promise?i.push(a.then(t=>ct(t,r,e))):ct(a,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function lt(e,t,r){e.issues.length&&t.issues.push(...G(r,e.issues)),t.value[r]=e.value}function ut(e,t,r,o){e.issues.length?void 0===o[r]?t.value[r]=r in o?void 0:e.value:t.issues.push(...G(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}const ht=t("$ZodObject",(e,t)=>{Te.init(e,t);const r=x(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Te))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(o=t.shape,Object.keys(o).filter(e=>"optional"===o[e]._zod.optin&&"optional"===o[e]._zod.optout));var o;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});let o;M(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const o=e[t]._zod;if(o.values){r[t]??(r[t]=new Set);for(const e of o.values)r[t].add(e)}}return r});const i=K,s=!n.jitless,a=s&&V.value,c=t.catchall;let d;e._zod.parse=(n,l)=>{d??(d=r.value);const u=n.value;if(!i(u))return n.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),n;const h=[];if(s&&a&&!1===l?.async&&!0!==l.jitless)o||(o=(e=>{const t=new ve(["shape","payload","ctx"]),o=r.value,n=e=>{const t=U(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const e of o.keys)i[e]="key_"+s++;t.write("const newResult = {}");for(const e of o.keys)if(o.optionalKeys.has(e)){const r=i[e];t.write(`const ${r} = ${n(e)};`);const o=U(e);t.write(`\n if (${r}.issues.length) {\n if (input[${o}] === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${o} in input) newResult[${o}] = undefined;\n } else {\n newResult[${o}] = ${r}.value;\n }\n `)}else{const r=i[e];t.write(`const ${r} = ${n(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${U(e)}, ...iss.path] : [${U(e)}]\n })));`),t.write(`newResult[${U(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),n=o(n,l);else{n.value={};const e=d.shape;for(const t of d.keys){const r=e[t],o=r._zod.run({value:u[t],issues:[]},l),i="optional"===r._zod.optin&&"optional"===r._zod.optout;o instanceof Promise?h.push(o.then(e=>i?ut(e,n,t,u):lt(e,n,t))):i?ut(o,n,t,u):lt(o,n,t)}}if(!c)return h.length?Promise.all(h).then(()=>n):n;const f=[],p=d.keySet,m=c._zod,g=m.def.type;for(const e of Object.keys(u)){if(p.has(e))continue;if("never"===g){f.push(e);continue}const t=m.run({value:u[e],issues:[]},l);t instanceof Promise?h.push(t.then(t=>lt(t,n,e))):lt(t,n,e)}return f.length&&n.issues.push({code:"unrecognized_keys",keys:f,input:u,inst:e}),h.length?Promise.all(h).then(()=>n):n}});function ft(e,t,r,o){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>Q(e,o,i())))}),t}const pt=t("$ZodUnion",(e,t)=>{Te.init(e,t),M(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),M(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),M(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),M(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>N(e.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)i.push(t),n=!0;else{if(0===t.issues.length)return t;i.push(t)}}return n?Promise.all(i).then(t=>ft(t,r,e,o)):ft(i,r,e,o)}}),mt=t("$ZodDiscriminatedUnion",(e,t)=>{pt.init(e,t);const r=e._zod.parse;M(e._zod,"propValues",()=>{const e={};for(const r of t.options){const o=r._zod.propValues;if(!o||0===Object.keys(o).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(o)){e[t]||(e[t]=new Set);for(const o of r)e[t].add(o)}}return e});const o=x(()=>{const e=t.options,r=new Map;for(const o of e){const e=o._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,o)}}return r});e._zod.parse=(n,i)=>{const s=n.value;if(!K(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;const a=o.value.get(s?.[t.discriminator]);return a?a._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),n)}}),gt=t("$ZodIntersection",(e,t)=>{Te.init(e,t),e._zod.parse=(e,r)=>{const o=e.value,n=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>vt(e,t,r)):vt(e,n,i)}});function yt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(L(e)&&L(t)){const r=Object.keys(t),o=Object.keys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const r of o){const o=yt(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n[r]=o.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let o=0;o<e.length;o++){const n=yt(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};r.push(n.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function vt(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Z(e))return e;const o=yt(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const wt=t("$ZodRecord",(e,t)=>{Te.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!L(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;const s=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;r.value={};for(const e of i)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const i=t.valueType._zod.run({value:n[e],issues:[]},o);i instanceof Promise?s.push(i.then(t=>{t.issues.length&&r.issues.push(...G(e,t.issues)),r.value[e]=t.value})):(i.issues.length&&r.issues.push(...G(e,i.issues)),r.value[e]=i.value)}let a;for(const e in n)i.has(e)||(a=a??[],a.push(e));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:a})}else{r.value={};for(const a of Reflect.ownKeys(n)){if("__proto__"===a)continue;const c=t.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(e=>Q(e,o,i())),input:a,path:[a],inst:e}),r.value[c.value]=c.value;continue}const d=t.valueType._zod.run({value:n[a],issues:[]},o);d instanceof Promise?s.push(d.then(e=>{e.issues.length&&r.issues.push(...G(a,e.issues)),r.value[c.value]=e.value})):(d.issues.length&&r.issues.push(...G(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}}),_t=t("$ZodEnum",(e,t)=>{Te.init(e,t);const r=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>F.has(typeof e)).map(e=>"string"==typeof e?H(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),bt=t("$ZodLiteral",(e,t)=>{Te.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?H(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,o)=>{const n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),St=t("$ZodTransform",(e,t)=>{Te.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new o;return e.value=n,e}}),Pt=t("$ZodOptional",(e,t)=>{Te.init(e,t),e._zod.optin="optional",e._zod.optout="optional",M(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),M(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${N(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),$t=t("$ZodNullable",(e,t)=>{Te.init(e,t),M(e._zod,"optin",()=>t.innerType._zod.optin),M(e._zod,"optout",()=>t.innerType._zod.optout),M(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${N(e.source)}|null)$`):void 0}),M(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),kt=t("$ZodDefault",(e,t)=>{Te.init(e,t),e._zod.optin="optional",M(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(e=>Et(e,t)):Et(o,t)}});function Et(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const It=t("$ZodPrefault",(e,t)=>{Te.init(e,t),e._zod.optin="optional",M(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),Ct=t("$ZodNonOptional",(e,t)=>{Te.init(e,t),M(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,o)=>{const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(t=>Tt(t,e)):Tt(n,e)}});function Tt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ot=t("$ZodCatch",(e,t)=>{Te.init(e,t),e._zod.optin="optional",M(e._zod,"optout",()=>t.innerType._zod.optout),M(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(o=>(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>Q(e,r,i()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>Q(e,r,i()))},input:e.value}),e.issues=[]),e)}}),Dt=t("$ZodPipe",(e,t)=>{Te.init(e,t),M(e._zod,"values",()=>t.in._zod.values),M(e._zod,"optin",()=>t.in._zod.optin),M(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const o=t.in._zod.run(e,r);return o instanceof Promise?o.then(e=>At(e,t,r)):At(o,t,r)}});function At(e,t,r){return Z(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Rt=t("$ZodReadonly",(e,t)=>{Te.init(e,t),M(e._zod,"propValues",()=>t.innerType._zod.propValues),M(e._zod,"values",()=>t.innerType._zod.values),M(e._zod,"optin",()=>t.innerType._zod.optin),M(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(xt):xt(o)}});function xt(e){return e.value=Object.freeze(e.value),e}const jt=t("$ZodCustom",(e,t)=>{te.init(e,t),Te.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(t=>Nt(t,r,o,e));Nt(n,r,o,e)}});function Nt(e,t,r,o){if(!e){const e={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(e.params=o._zod.def.params),t.issues.push(ee(e))}}Symbol("ZodOutput"),Symbol("ZodInput");class Mt{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function zt(){return new Mt}const Ut=zt();function qt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...J(t)})}function Kt(e,t){return new oe({check:"less_than",...J(t),value:e,inclusive:!1})}function Vt(e,t){return new oe({check:"less_than",...J(t),value:e,inclusive:!0})}function Lt(e,t){return new ne({check:"greater_than",...J(t),value:e,inclusive:!1})}function Ft(e,t){return new ne({check:"greater_than",...J(t),value:e,inclusive:!0})}function Ht(e,t){return new ie({check:"multiple_of",...J(t),value:e})}function Bt(e,t){return new ae({check:"max_length",...J(t),maximum:e})}function Jt(e,t){return new ce({check:"min_length",...J(t),minimum:e})}function Wt(e,t){return new de({check:"length_equals",...J(t),length:e})}function Zt(e){return new ye({check:"overwrite",tx:e})}const Gt=t("ZodISODateTime",(e,t)=>{Le.init(e,t),ur.init(e,t)});function Yt(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(t)})}(Gt,e)}const Qt=t("ZodISODate",(e,t)=>{Fe.init(e,t),ur.init(e,t)});const Xt=t("ZodISOTime",(e,t)=>{He.init(e,t),ur.init(e,t)});const er=t("ZodISODuration",(e,t)=>{Be.init(e,t),ur.init(e,t)});const tr=(e,t)=>{_e.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const r=t||function(e){return e.message},o={_errors:[]},n=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)o._errors.push(r(t));else{let e=o,n=0;for(;n<t.path.length;){const o=t.path[n];n===t.path.length-1?(e[o]=e[o]||{_errors:[]},e[o]._errors.push(r(t))):e[o]=e[o]||{_errors:[]},e=e[o],n++}}};return n(e),o}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},o=[];for(const n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},rr=(t("ZodError",tr),t("ZodError",tr,{Parent:Error})),or=Se(rr),nr=Pe(rr),ir=$e(rr),sr=Ee(rr),ar=t("ZodType",(e,t)=>(Te.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>B(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>or(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>ir(e,t,r),e.parseAsync=async(t,r)=>nr(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>sr(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...J(r)})}(wo,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new te({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(ee(e,r.value,t._zod.def));else{const o=e;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(ee(o))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(Zt(t)),e.optional=()=>co(e),e.nullable=()=>uo(e),e.nullish=()=>co(uo(e)),e.nonoptional=t=>function(e,t){return new po({type:"nonoptional",innerType:e,...J(t)})}(e,t),e.array=()=>Lr(e),e.or=t=>Wr([e,t]),e.and=t=>Qr(e,t),e.transform=t=>yo(e,so(t)),e.default=t=>{return r=t,new ho({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new fo({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new mo({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>yo(e,t),e.readonly=()=>new vo({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return Ut.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Ut.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ut.get(e);const r=e.clone();return Ut.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),cr=t("_ZodString",(e,t)=>{Oe.init(e,t),ar.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new ue({check:"string_format",format:"regex",...J(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new pe({check:"string_format",format:"includes",...J(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new me({check:"string_format",format:"starts_with",...J(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new ge({check:"string_format",format:"ends_with",...J(t),suffix:e})}(...t)),e.min=(...t)=>e.check(Jt(...t)),e.max=(...t)=>e.check(Bt(...t)),e.length=(...t)=>e.check(Wt(...t)),e.nonempty=(...t)=>e.check(Jt(1,...t)),e.lowercase=t=>e.check(function(e){return new he({check:"string_format",format:"lowercase",...J(e)})}(t)),e.uppercase=t=>e.check(function(e){return new fe({check:"string_format",format:"uppercase",...J(e)})}(t)),e.trim=()=>e.check(Zt(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return Zt(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(Zt(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(Zt(e=>e.toUpperCase()))}),dr=t("ZodString",(e,t)=>{Oe.init(e,t),cr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...J(t)})}(hr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...J(t)})}(mr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...J(t)})}(Or,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...J(t)})}(gr,t)),e.guid=t=>e.check(qt(fr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...J(t)})}(pr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(t)})}(pr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(t)})}(pr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(t)})}(pr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(t)})}(yr,t)),e.guid=t=>e.check(qt(fr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...J(t)})}(vr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(t)})}(wr,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...J(t)})}(_r,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...J(t)})}(Ir,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...J(t)})}(Cr,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...J(t)})}(br,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(t)})}(Sr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(t)})}(Pr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(t)})}($r,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(t)})}(kr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(t)})}(Er,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...J(t)})}(Tr,t)),e.datetime=t=>e.check(Yt(t)),e.date=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...J(t)})}(Qt,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...J(t)})}(Xt,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...J(t)})}(er,e)}(t))});function lr(e){return function(e,t){return new e({type:"string",...J(t)})}(dr,e)}const ur=t("ZodStringFormat",(e,t)=>{De.init(e,t),cr.init(e,t)}),hr=t("ZodEmail",(e,t)=>{xe.init(e,t),ur.init(e,t)}),fr=t("ZodGUID",(e,t)=>{Ae.init(e,t),ur.init(e,t)}),pr=t("ZodUUID",(e,t)=>{Re.init(e,t),ur.init(e,t)}),mr=t("ZodURL",(e,t)=>{je.init(e,t),ur.init(e,t)}),gr=t("ZodEmoji",(e,t)=>{Ne.init(e,t),ur.init(e,t)}),yr=t("ZodNanoID",(e,t)=>{Me.init(e,t),ur.init(e,t)}),vr=t("ZodCUID",(e,t)=>{ze.init(e,t),ur.init(e,t)}),wr=t("ZodCUID2",(e,t)=>{Ue.init(e,t),ur.init(e,t)}),_r=t("ZodULID",(e,t)=>{qe.init(e,t),ur.init(e,t)}),br=t("ZodXID",(e,t)=>{Ke.init(e,t),ur.init(e,t)}),Sr=t("ZodKSUID",(e,t)=>{Ve.init(e,t),ur.init(e,t)}),Pr=t("ZodIPv4",(e,t)=>{Je.init(e,t),ur.init(e,t)}),$r=t("ZodIPv6",(e,t)=>{We.init(e,t),ur.init(e,t)}),kr=t("ZodCIDRv4",(e,t)=>{Ze.init(e,t),ur.init(e,t)}),Er=t("ZodCIDRv6",(e,t)=>{Ge.init(e,t),ur.init(e,t)}),Ir=t("ZodBase64",(e,t)=>{Qe.init(e,t),ur.init(e,t)}),Cr=t("ZodBase64URL",(e,t)=>{Xe.init(e,t),ur.init(e,t)}),Tr=t("ZodE164",(e,t)=>{et.init(e,t),ur.init(e,t)}),Or=t("ZodJWT",(e,t)=>{tt.init(e,t),ur.init(e,t)}),Dr=t("ZodNumber",(e,t)=>{rt.init(e,t),ar.init(e,t),e.gt=(t,r)=>e.check(Lt(t,r)),e.gte=(t,r)=>e.check(Ft(t,r)),e.min=(t,r)=>e.check(Ft(t,r)),e.lt=(t,r)=>e.check(Kt(t,r)),e.lte=(t,r)=>e.check(Vt(t,r)),e.max=(t,r)=>e.check(Vt(t,r)),e.int=t=>e.check(xr(t)),e.safe=t=>e.check(xr(t)),e.positive=t=>e.check(Lt(0,t)),e.nonnegative=t=>e.check(Ft(0,t)),e.negative=t=>e.check(Kt(0,t)),e.nonpositive=t=>e.check(Vt(0,t)),e.multipleOf=(t,r)=>e.check(Ht(t,r)),e.step=(t,r)=>e.check(Ht(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Ar(e){return function(e,t){return new e({type:"number",checks:[],...J(t)})}(Dr,e)}const Rr=t("ZodNumberFormat",(e,t)=>{ot.init(e,t),Dr.init(e,t)});function xr(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...J(t)})}(Rr,e)}const jr=t("ZodBoolean",(e,t)=>{nt.init(e,t),ar.init(e,t)});function Nr(e){return function(e,t){return new e({type:"boolean",...J(t)})}(jr,e)}const Mr=t("ZodNull",(e,t)=>{it.init(e,t),ar.init(e,t)});function zr(e){return function(e,t){return new e({type:"null",...J(t)})}(Mr,e)}const Ur=t("ZodUnknown",(e,t)=>{st.init(e,t),ar.init(e,t)});function qr(){return new Ur({type:"unknown"})}const Kr=t("ZodNever",(e,t)=>{at.init(e,t),ar.init(e,t)});const Vr=t("ZodArray",(e,t)=>{dt.init(e,t),ar.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(Jt(t,r)),e.nonempty=t=>e.check(Jt(1,t)),e.max=(t,r)=>e.check(Bt(t,r)),e.length=(t,r)=>e.check(Wt(t,r)),e.unwrap=()=>e.element});function Lr(e,t){return function(e,t,r){return new e({type:"array",element:t,...J(r)})}(Vr,e,t)}const Fr=t("ZodObject",(e,t)=>{ht.init(e,t),ar.init(e,t),M(e,"shape",()=>t.shape),e.keyof=()=>ro(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:qr()}),e.loose=()=>e.clone({...e._zod.def,catchall:qr()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new e({type:"never",...J(t)})}(Kr,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!L(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return z(this,"shape",r),r},checks:[]};return B(e,r)}(e,t),e.merge=t=>{return o=t,B(r=e,{...r._zod.def,get shape(){const e={...r._zod.def.shape,...o._zod.def.shape};return z(this,"shape",e),e},catchall:o._zod.def.catchall,checks:[]});var r,o},e.pick=t=>function(e,t){const r={},o=e._zod.def;for(const e in t){if(!(e in o.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=o.shape[e])}return B(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.omit=t=>function(e,t){const r={...e._zod.def.shape},o=e._zod.def;for(const e in t){if(!(e in o.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return B(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,r){const o=t._zod.def.shape,n={...o};if(r)for(const t in r){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:o[t]}):o[t])}else for(const t in o)n[t]=e?new e({type:"optional",innerType:o[t]}):o[t];return B(t,{...t._zod.def,shape:n,checks:[]})}(ao,e,t[0]),e.required=(...t)=>function(e,t,r){const o=t._zod.def.shape,n={...o};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:o[t]}))}else for(const t in o)n[t]=new e({type:"nonoptional",innerType:o[t]});return B(t,{...t._zod.def,shape:n,checks:[]})}(po,e,t[0])});function Hr(e,t){const r={type:"object",get shape(){return z(this,"shape",{...e}),this.shape},...J(t)};return new Fr(r)}function Br(e,t){return new Fr({type:"object",get shape(){return z(this,"shape",{...e}),this.shape},catchall:qr(),...J(t)})}const Jr=t("ZodUnion",(e,t)=>{pt.init(e,t),ar.init(e,t),e.options=t.options});function Wr(e,t){return new Jr({type:"union",options:e,...J(t)})}const Zr=t("ZodDiscriminatedUnion",(e,t)=>{Jr.init(e,t),mt.init(e,t)});function Gr(e,t,r){return new Zr({type:"union",options:t,discriminator:e,...J(r)})}const Yr=t("ZodIntersection",(e,t)=>{gt.init(e,t),ar.init(e,t)});function Qr(e,t){return new Yr({type:"intersection",left:e,right:t})}const Xr=t("ZodRecord",(e,t)=>{wt.init(e,t),ar.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function eo(e,t,r){return new Xr({type:"record",keyType:e,valueType:t,...J(r)})}const to=t("ZodEnum",(e,t)=>{_t.init(e,t),ar.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,o)=>{const n={};for(const o of e){if(!r.has(o))throw new Error(`Key ${o} not found in enum`);n[o]=t.entries[o]}return new to({...t,checks:[],...J(o),entries:n})},e.exclude=(e,o)=>{const n={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete n[t]}return new to({...t,checks:[],...J(o),entries:n})}});function ro(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new to({type:"enum",entries:r,...J(t)})}const oo=t("ZodLiteral",(e,t)=>{bt.init(e,t),ar.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function no(e,t){return new oo({type:"literal",values:Array.isArray(e)?e:[e],...J(t)})}const io=t("ZodTransform",(e,t)=>{St.init(e,t),ar.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=o=>{if("string"==typeof o)r.issues.push(ee(o,r.value,t));else{const t=o;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(ee(t))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}});function so(e){return new io({type:"transform",transform:e})}const ao=t("ZodOptional",(e,t)=>{Pt.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function co(e){return new ao({type:"optional",innerType:e})}const lo=t("ZodNullable",(e,t)=>{$t.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function uo(e){return new lo({type:"nullable",innerType:e})}const ho=t("ZodDefault",(e,t)=>{kt.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),fo=t("ZodPrefault",(e,t)=>{It.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType}),po=t("ZodNonOptional",(e,t)=>{Ct.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType}),mo=t("ZodCatch",(e,t)=>{Ot.init(e,t),ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),go=t("ZodPipe",(e,t)=>{Dt.init(e,t),ar.init(e,t),e.in=t.in,e.out=t.out});function yo(e,t){return new go({type:"pipe",in:e,out:t})}const vo=t("ZodReadonly",(e,t)=>{Rt.init(e,t),ar.init(e,t)}),wo=t("ZodCustom",(e,t)=>{jt.init(e,t),ar.init(e,t)});function _o(e,t){return yo(so(e),t)}const bo="2025-11-25",So=[bo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Po="io.modelcontextprotocol/related-task",$o="2.0",ko=function(e,t,r){const o=J(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...o})}(wo,0,undefined);const Eo=Wr([lr(),Ar().int()]),Io=lr(),Co=(Br({ttl:Wr([Ar(),zr()]).optional(),pollInterval:Ar().optional()}),Hr({ttl:Ar().optional()})),To=Hr({taskId:lr()}),Oo=Br({progressToken:Eo.optional(),[Po]:To.optional()}),Do=Hr({_meta:Oo.optional()}),Ao=Do.extend({task:Co.optional()}),Ro=Hr({method:lr(),params:Do.loose().optional()}),xo=Hr({_meta:Oo.optional()}),jo=Hr({method:lr(),params:xo.loose().optional()}),No=Br({_meta:Oo.optional()}),Mo=Wr([lr(),Ar().int()]),zo=Hr({jsonrpc:no($o),id:Mo,...Ro.shape}).strict(),Uo=e=>zo.safeParse(e).success,qo=Hr({jsonrpc:no($o),...jo.shape}).strict(),Ko=Hr({jsonrpc:no($o),id:Mo,result:No}).strict(),Vo=e=>Ko.safeParse(e).success;var Lo;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(Lo||(Lo={}));const Fo=Hr({jsonrpc:no($o),id:Mo.optional(),error:Hr({code:Ar().int(),message:lr(),data:qr().optional()})}).strict(),Ho=Wr([zo,qo,Ko,Fo]),Bo=(Wr([Ko,Fo]),No.strict()),Jo=xo.extend({requestId:Mo.optional(),reason:lr().optional()}),Wo=jo.extend({method:no("notifications/cancelled"),params:Jo}),Zo=Hr({src:lr(),mimeType:lr().optional(),sizes:Lr(lr()).optional(),theme:ro(["light","dark"]).optional()}),Go=Hr({icons:Lr(Zo).optional()}),Yo=Hr({name:lr(),title:lr().optional()}),Qo=Yo.extend({...Yo.shape,...Go.shape,version:lr(),websiteUrl:lr().optional(),description:lr().optional()}),Xo=Qr(Hr({applyDefaults:Nr().optional()}),eo(lr(),qr())),en=_o(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,Qr(Hr({form:Xo.optional(),url:ko.optional()}),eo(lr(),qr()).optional())),tn=Br({list:ko.optional(),cancel:ko.optional(),requests:Br({sampling:Br({createMessage:ko.optional()}).optional(),elicitation:Br({create:ko.optional()}).optional()}).optional()}),rn=Br({list:ko.optional(),cancel:ko.optional(),requests:Br({tools:Br({call:ko.optional()}).optional()}).optional()}),on=Hr({experimental:eo(lr(),ko).optional(),sampling:Hr({context:ko.optional(),tools:ko.optional()}).optional(),elicitation:en.optional(),roots:Hr({listChanged:Nr().optional()}).optional(),tasks:tn.optional()}),nn=Do.extend({protocolVersion:lr(),capabilities:on,clientInfo:Qo}),sn=Ro.extend({method:no("initialize"),params:nn}),an=Hr({experimental:eo(lr(),ko).optional(),logging:ko.optional(),completions:ko.optional(),prompts:Hr({listChanged:Nr().optional()}).optional(),resources:Hr({subscribe:Nr().optional(),listChanged:Nr().optional()}).optional(),tools:Hr({listChanged:Nr().optional()}).optional(),tasks:rn.optional()}),cn=No.extend({protocolVersion:lr(),capabilities:an,serverInfo:Qo,instructions:lr().optional()}),dn=jo.extend({method:no("notifications/initialized"),params:xo.optional()}),ln=Ro.extend({method:no("ping"),params:Do.optional()}),un=Hr({progress:Ar(),total:co(Ar()),message:co(lr())}),hn=Hr({...xo.shape,...un.shape,progressToken:Eo}),fn=jo.extend({method:no("notifications/progress"),params:hn}),pn=Do.extend({cursor:Io.optional()}),mn=Ro.extend({params:pn.optional()}),gn=No.extend({nextCursor:Io.optional()}),yn=ro(["working","input_required","completed","failed","cancelled"]),vn=Hr({taskId:lr(),status:yn,ttl:Wr([Ar(),zr()]),createdAt:lr(),lastUpdatedAt:lr(),pollInterval:co(Ar()),statusMessage:co(lr())}),wn=No.extend({task:vn}),_n=xo.merge(vn),bn=jo.extend({method:no("notifications/tasks/status"),params:_n}),Sn=Ro.extend({method:no("tasks/get"),params:Do.extend({taskId:lr()})}),Pn=No.merge(vn),$n=Ro.extend({method:no("tasks/result"),params:Do.extend({taskId:lr()})}),kn=(No.loose(),mn.extend({method:no("tasks/list")})),En=gn.extend({tasks:Lr(vn)}),In=Ro.extend({method:no("tasks/cancel"),params:Do.extend({taskId:lr()})}),Cn=No.merge(vn),Tn=Hr({uri:lr(),mimeType:co(lr()),_meta:eo(lr(),qr()).optional()}),On=Tn.extend({text:lr()}),Dn=lr().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),An=Tn.extend({blob:Dn}),Rn=ro(["user","assistant"]),xn=Hr({audience:Lr(Rn).optional(),priority:Ar().min(0).max(1).optional(),lastModified:Yt({offset:!0}).optional()}),jn=Hr({...Yo.shape,...Go.shape,uri:lr(),description:co(lr()),mimeType:co(lr()),annotations:xn.optional(),_meta:co(Br({}))}),Nn=Hr({...Yo.shape,...Go.shape,uriTemplate:lr(),description:co(lr()),mimeType:co(lr()),annotations:xn.optional(),_meta:co(Br({}))}),Mn=mn.extend({method:no("resources/list")}),zn=gn.extend({resources:Lr(jn)}),Un=mn.extend({method:no("resources/templates/list")}),qn=gn.extend({resourceTemplates:Lr(Nn)}),Kn=Do.extend({uri:lr()}),Vn=Kn,Ln=Ro.extend({method:no("resources/read"),params:Vn}),Fn=No.extend({contents:Lr(Wr([On,An]))}),Hn=jo.extend({method:no("notifications/resources/list_changed"),params:xo.optional()}),Bn=Kn,Jn=Ro.extend({method:no("resources/subscribe"),params:Bn}),Wn=Kn,Zn=Ro.extend({method:no("resources/unsubscribe"),params:Wn}),Gn=xo.extend({uri:lr()}),Yn=jo.extend({method:no("notifications/resources/updated"),params:Gn}),Qn=Hr({name:lr(),description:co(lr()),required:co(Nr())}),Xn=Hr({...Yo.shape,...Go.shape,description:co(lr()),arguments:co(Lr(Qn)),_meta:co(Br({}))}),ei=mn.extend({method:no("prompts/list")}),ti=gn.extend({prompts:Lr(Xn)}),ri=Do.extend({name:lr(),arguments:eo(lr(),lr()).optional()}),oi=Ro.extend({method:no("prompts/get"),params:ri}),ni=Hr({type:no("text"),text:lr(),annotations:xn.optional(),_meta:eo(lr(),qr()).optional()}),ii=Hr({type:no("image"),data:Dn,mimeType:lr(),annotations:xn.optional(),_meta:eo(lr(),qr()).optional()}),si=Hr({type:no("audio"),data:Dn,mimeType:lr(),annotations:xn.optional(),_meta:eo(lr(),qr()).optional()}),ai=Hr({type:no("tool_use"),name:lr(),id:lr(),input:eo(lr(),qr()),_meta:eo(lr(),qr()).optional()}),ci=Hr({type:no("resource"),resource:Wr([On,An]),annotations:xn.optional(),_meta:eo(lr(),qr()).optional()}),di=Wr([ni,ii,si,jn.extend({type:no("resource_link")}),ci]),li=Hr({role:Rn,content:di}),ui=No.extend({description:lr().optional(),messages:Lr(li)}),hi=jo.extend({method:no("notifications/prompts/list_changed"),params:xo.optional()}),fi=Hr({title:lr().optional(),readOnlyHint:Nr().optional(),destructiveHint:Nr().optional(),idempotentHint:Nr().optional(),openWorldHint:Nr().optional()}),pi=Hr({taskSupport:ro(["required","optional","forbidden"]).optional()}),mi=Hr({...Yo.shape,...Go.shape,description:lr().optional(),inputSchema:Hr({type:no("object"),properties:eo(lr(),ko).optional(),required:Lr(lr()).optional()}).catchall(qr()),outputSchema:Hr({type:no("object"),properties:eo(lr(),ko).optional(),required:Lr(lr()).optional()}).catchall(qr()).optional(),annotations:fi.optional(),execution:pi.optional(),_meta:eo(lr(),qr()).optional()}),gi=mn.extend({method:no("tools/list")}),yi=gn.extend({tools:Lr(mi)}),vi=No.extend({content:Lr(di).default([]),structuredContent:eo(lr(),qr()).optional(),isError:Nr().optional()}),wi=(vi.or(No.extend({toolResult:qr()})),Ao.extend({name:lr(),arguments:eo(lr(),qr()).optional()})),_i=Ro.extend({method:no("tools/call"),params:wi}),bi=jo.extend({method:no("notifications/tools/list_changed"),params:xo.optional()}),Si=(Hr({autoRefresh:Nr().default(!0),debounceMs:Ar().int().nonnegative().default(300)}),ro(["debug","info","notice","warning","error","critical","alert","emergency"])),Pi=Do.extend({level:Si}),$i=Ro.extend({method:no("logging/setLevel"),params:Pi}),ki=xo.extend({level:Si,logger:lr().optional(),data:qr()}),Ei=jo.extend({method:no("notifications/message"),params:ki}),Ii=Hr({name:lr().optional()}),Ci=Hr({hints:Lr(Ii).optional(),costPriority:Ar().min(0).max(1).optional(),speedPriority:Ar().min(0).max(1).optional(),intelligencePriority:Ar().min(0).max(1).optional()}),Ti=Hr({mode:ro(["auto","required","none"]).optional()}),Oi=Hr({type:no("tool_result"),toolUseId:lr().describe("The unique identifier for the corresponding tool call."),content:Lr(di).default([]),structuredContent:Hr({}).loose().optional(),isError:Nr().optional(),_meta:eo(lr(),qr()).optional()}),Di=Gr("type",[ni,ii,si]),Ai=Gr("type",[ni,ii,si,ai,Oi]),Ri=Hr({role:Rn,content:Wr([Ai,Lr(Ai)]),_meta:eo(lr(),qr()).optional()}),xi=Ao.extend({messages:Lr(Ri),modelPreferences:Ci.optional(),systemPrompt:lr().optional(),includeContext:ro(["none","thisServer","allServers"]).optional(),temperature:Ar().optional(),maxTokens:Ar().int(),stopSequences:Lr(lr()).optional(),metadata:ko.optional(),tools:Lr(mi).optional(),toolChoice:Ti.optional()}),ji=Ro.extend({method:no("sampling/createMessage"),params:xi}),Ni=No.extend({model:lr(),stopReason:co(ro(["endTurn","stopSequence","maxTokens"]).or(lr())),role:Rn,content:Di}),Mi=No.extend({model:lr(),stopReason:co(ro(["endTurn","stopSequence","maxTokens","toolUse"]).or(lr())),role:Rn,content:Wr([Ai,Lr(Ai)])}),zi=Hr({type:no("boolean"),title:lr().optional(),description:lr().optional(),default:Nr().optional()}),Ui=Hr({type:no("string"),title:lr().optional(),description:lr().optional(),minLength:Ar().optional(),maxLength:Ar().optional(),format:ro(["email","uri","date","date-time"]).optional(),default:lr().optional()}),qi=Hr({type:ro(["number","integer"]),title:lr().optional(),description:lr().optional(),minimum:Ar().optional(),maximum:Ar().optional(),default:Ar().optional()}),Ki=Hr({type:no("string"),title:lr().optional(),description:lr().optional(),enum:Lr(lr()),default:lr().optional()}),Vi=Hr({type:no("string"),title:lr().optional(),description:lr().optional(),oneOf:Lr(Hr({const:lr(),title:lr()})),default:lr().optional()}),Li=Hr({type:no("string"),title:lr().optional(),description:lr().optional(),enum:Lr(lr()),enumNames:Lr(lr()).optional(),default:lr().optional()}),Fi=Wr([Ki,Vi]),Hi=Wr([Hr({type:no("array"),title:lr().optional(),description:lr().optional(),minItems:Ar().optional(),maxItems:Ar().optional(),items:Hr({type:no("string"),enum:Lr(lr())}),default:Lr(lr()).optional()}),Hr({type:no("array"),title:lr().optional(),description:lr().optional(),minItems:Ar().optional(),maxItems:Ar().optional(),items:Hr({anyOf:Lr(Hr({const:lr(),title:lr()}))}),default:Lr(lr()).optional()})]),Bi=Wr([Li,Fi,Hi]),Ji=Wr([Bi,zi,Ui,qi]),Wi=Wr([Ao.extend({mode:no("form").optional(),message:lr(),requestedSchema:Hr({type:no("object"),properties:eo(lr(),Ji),required:Lr(lr()).optional()})}),Ao.extend({mode:no("url"),message:lr(),elicitationId:lr(),url:lr().url()})]),Zi=Ro.extend({method:no("elicitation/create"),params:Wi}),Gi=xo.extend({elicitationId:lr()}),Yi=jo.extend({method:no("notifications/elicitation/complete"),params:Gi}),Qi=No.extend({action:ro(["accept","decline","cancel"]),content:_o(e=>null===e?void 0:e,eo(lr(),Wr([lr(),Ar(),Nr(),Lr(lr())])).optional())}),Xi=Hr({type:no("ref/resource"),uri:lr()}),es=Hr({type:no("ref/prompt"),name:lr()}),ts=Do.extend({ref:Wr([es,Xi]),argument:Hr({name:lr(),value:lr()}),context:Hr({arguments:eo(lr(),lr()).optional()}).optional()}),rs=Ro.extend({method:no("completion/complete"),params:ts}),os=No.extend({completion:Br({values:Lr(lr()).max(100),total:co(Ar().int()),hasMore:co(Nr())})}),ns=Hr({uri:lr().startsWith("file://"),name:lr().optional(),_meta:eo(lr(),qr()).optional()}),is=Ro.extend({method:no("roots/list"),params:Do.optional()}),ss=No.extend({roots:Lr(ns)}),as=jo.extend({method:no("notifications/roots/list_changed"),params:xo.optional()});Wr([ln,sn,rs,$i,oi,ei,Mn,Un,Ln,Jn,Zn,_i,gi,Sn,$n,kn,In]),Wr([Wo,fn,dn,as,bn]),Wr([Bo,Ni,Mi,Qi,ss,Pn,En,wn]),Wr([ln,ji,Zi,is,Sn,$n,kn,In]),Wr([Wo,fn,Ei,Yn,Hn,bi,hi,bn,Yi]),Wr([Bo,cn,os,ui,ti,zn,qn,Fn,vi,yi,Pn,En,wn]);class cs extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Lo.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new ds(e.elicitations,t)}return new cs(e,t,r)}}class ds extends cs{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Lo.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}class ls{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return Ho.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class us{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new ls,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}function hs(e){return!!e._zod}function fs(e,t){return hs(e)?ke(e,t):e.safeParse(t)}function ps(e){if(!e)return;let t;if(hs(e)){const r=e;t=r._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function ms(e){return"completed"===e||"failed"===e||"cancelled"===e}function gs(e){const t=ps(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const o=function(e){if(hs(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}(r);if("string"!=typeof o)throw new Error("Schema method literal must be a string");return o}function ys(e,t){const r=fs(e,t);if(!r.success)throw r.error;return r.data}Symbol("Let zodToJsonSchema decide on which parser to use");class vs{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Wo,e=>{this._oncancel(e)}),this.setNotificationHandler(fn,e=>{this._onprogress(e)}),this.setRequestHandler(ln,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Sn,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new cs(Lo.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler($n,async(e,t)=>{const r=async()=>{const o=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(o,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,o=this._requestResolvers.get(r);if(o)if(this._requestResolvers.delete(r),"response"===e.type)o(t);else{const e=t;o(new cs(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const n=await this._taskStore.getTask(o,t.sessionId);if(!n)throw new cs(Lo.InvalidParams,`Task not found: ${o}`);if(!ms(n.status))return await this._waitForTaskUpdate(o,t.signal),await r();if(ms(n.status)){const e=await this._taskStore.getTaskResult(o,t.sessionId);return this._clearTaskQueue(o),{...e,_meta:{...e._meta,[Po]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(kn,async(e,t)=>{try{const{tasks:r,nextCursor:o}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(e){throw new cs(Lo.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(In,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new cs(Lo.InvalidParams,`Task not found: ${e.params.taskId}`);if(ms(r.status))throw new cs(Lo.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const o=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!o)throw new cs(Lo.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...o}}catch(e){if(e instanceof cs)throw e;throw new cs(Lo.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),cs.fromError(Lo.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const o=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var r;o?.(e,t),Vo(e)||(e=>Fo.safeParse(e).success)(e)?this._onresponse(e):Uo(e)?this._onrequest(e,t):(r=e,qo.safeParse(r).success?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`)))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=cs.fromError(Lo.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,n=e.params?._meta?.[Po]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:Lo.MethodNotFound,message:"Method not found"}};return void(n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:t,timestamp:Date.now()},o?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):o?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const s=(a=e.params,Ao.safeParse(a).success?e.params.task:void 0);var a;const c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(i.signal.aborted)return;const r={relatedRequestId:e.id};n&&(r.relatedTask={taskId:n}),await this.notification(t,r)},sendRequest:async(t,r,o)=>{if(i.signal.aborted)throw new cs(Lo.ConnectionClosed,"Request was cancelled");const s={...o,relatedRequestId:e.id};n&&!s.relatedTask&&(s.relatedTask={taskId:n});const a=s.relatedTask?.taskId??n;return a&&c&&await c.updateTaskStatus(a,"input_required"),await this.request(t,r,s)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,d)).then(async t=>{if(i.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:r,timestamp:Date.now()},o?.sessionId):await(o?.send(r))},async t=>{if(i.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Lo.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:r,timestamp:Date.now()},o?.sessionId):await(o?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(e){return this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),void i(e)}n(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void(Vo(e)?r(e):r(new cs(e.error.code,e.error.message,e.error.data)));const o=this._responseHandlers.get(t);if(void 0===o)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let n=!1;if(Vo(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(n=!0,this._taskProgressTokens.set(e.taskId,t))}}n||this._progressHandlers.delete(t),Vo(e)?o(e):o(cs.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:o}=r??{};if(!o){try{const o=await this.request(e,t,r);yield{type:"result",result:o}}catch(e){yield{type:"error",error:e instanceof cs?e:new cs(Lo.InternalError,String(e))}}return}let n;try{const o=await this.request(e,wn,r);if(!o.task)throw new cs(Lo.InternalError,"Task creation did not return a task");for(n=o.task.taskId,yield{type:"taskCreated",task:o.task};;){const e=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:e},ms(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:n},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new cs(Lo.InternalError,`Task ${n} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new cs(Lo.InternalError,`Task ${n} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:n},t,r);return void(yield{type:"result",result:e})}const o=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,o)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof cs?e:new cs(Lo.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{const l=e=>{d(e)};if(!this._transport)return void l(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(e){return void l(e)}r?.signal?.throwIfAborted();const u=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:u};r?.onprogress&&(this._progressHandlers.set(u,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:u}}),s&&(h.params={...h.params,task:s}),a&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Po]:a}});const f=e=>{this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}},{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof cs?e:new cs(Lo.RequestTimeout,String(e));d(t)};this._responseHandlers.set(u,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return d(e);try{const r=fs(t,e.result);r.success?c(r.data):d(r.error)}catch(e){d(e)}}}),r?.signal?.addEventListener("abort",()=>{f(r?.signal?.reason)});const p=r?.timeout??6e4;this._setupTimeout(u,p,r?.maxTotalTimeout,()=>f(cs.fromError(Lo.RequestTimeout,"Request timed out",{timeout:p})),r?.resetTimeoutOnProgress??!1);const m=a?.taskId;if(m){const e=e=>{const t=this._responseHandlers.get(u);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${u}`))};this._requestResolvers.set(u,e),this._enqueueTaskMessage(m,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(u),d(e)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(u),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Pn,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},En,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Cn,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const o={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Po]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:o,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Po]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let o={...e,jsonrpc:"2.0"};t?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Po]:t.relatedTask}}}),await this._transport.send(o,t)}setRequestHandler(e,t){const r=gs(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,o)=>{const n=ys(e,r);return Promise.resolve(t(n,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=gs(e);this._notificationHandlers.set(r,r=>{const o=ys(e,r);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&Uo(t.message)){const r=t.message.id,o=this._requestResolvers.get(r);o?(o(new cs(Lo.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,o)=>{if(t.aborted)return void o(new cs(Lo.InvalidRequest,"Request cancelled"));const n=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(n),o(new cs(Lo.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const o=await r.getTask(e,t);if(!o)throw new cs(Lo.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(e,o,n)=>{await r.storeTaskResult(e,o,n,t);const i=await r.getTask(e,t);if(i){const t=bn.parse({method:"notifications/tasks/status",params:i});await this.notification(t),ms(i.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,o,n)=>{const i=await r.getTask(e,t);if(!i)throw new cs(Lo.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(ms(i.status))throw new cs(Lo.InvalidParams,`Cannot update task "${e}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,o,n,t);const s=await r.getTask(e,t);if(s){const t=bn.parse({method:"notifications/tasks/status",params:s});await this.notification(t),ms(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function ws(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var _s=r(74319),bs=r(10494);class Ss{constructor(e){this._ajv=e??function(){const e=new _s({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return bs(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Ps{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class $s extends vs{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Si.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Ss,this.setRequestHandler(sn,e=>this._oninitialize(e)),this.setNotificationHandler(dn,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler($i,async(e,t)=>{const r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=e.params,n=Si.safeParse(o);return n.success&&this._loggingLevels.set(r,n.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ps(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const e in t){const o=e,n=t[o];if(void 0===n)continue;const i=r[o];ws(i)&&ws(n)?r[o]={...i,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=ps(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if(hs(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");if("tools/call"===n){const r=async(e,r)=>{const o=fs(_i,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new cs(Lo.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:n}=o.data,i=await Promise.resolve(t(e,r));if(n.task){const e=fs(wn,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new cs(Lo.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const s=fs(vi,i);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new cs(Lo.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:So.includes(t)?t:bo,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Bo)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],o=r.some(e=>"tool_result"===e.type),n=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=n?Array.isArray(n.content)?n.content:[n.content]:[],s=i.some(e=>"tool_use"===e.type);if(o){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!s)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){const e=new Set(i.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Mi,t):this.request({method:"sampling/createMessage",params:e},Ni,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const r=e;return this.request({method:"elicitation/create",params:r},Qi,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const r="form"===e.mode?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:r},Qi,t);if("accept"===o.action&&o.content&&r.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(o.content);if(!e.valid)throw new cs(Lo.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof cs)throw e;throw new cs(Lo.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},ss,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const ks=require("crypto"),Es=require("node:crypto"),Is=require("node:buffer");const Cs=e=>Is.Buffer.from(e).toString("base64url"),Ts=require("node:util");class Os 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 Ds extends Os{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class As extends Os{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Rs extends Os{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;const xs=Es.webcrypto,js=e=>Ts.types.isCryptoKey(e),Ns=e=>Ts.types.isKeyObject(e);function Ms(e,t,...r){if((r=r.filter(Boolean)).length>2){const 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}const zs=(e,...t)=>Ms("Key must be ",e,...t);function Us(e,t,...r){return Ms(`Key for the ${e} algorithm must be `,t,...r)}const qs=e=>Ns(e)||js(e),Ks=["KeyObject"];function Vs(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Ls(e){return Vs(e)&&"string"==typeof e.kty}(globalThis.CryptoKey||xs?.CryptoKey)&&Ks.push("CryptoKey"),new WeakMap;const Fs=(e,t)=>{let r;if(js(e))r=Es.KeyObject.from(e);else{if(!Ns(e)){if(Ls(e))return e.crv;throw new TypeError(zs(e,...Ks))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Ds("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Hs=(e,t)=>{let r;try{r=e instanceof Es.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},Bs=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function Js(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Ws(e,t){return e.name===t}function Zs(e){return parseInt(e.name.slice(4),10)}function Gs(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Ws(e.algorithm,"HMAC"))throw Js("HMAC");const r=parseInt(t.slice(2),10);if(Zs(e.algorithm.hash)!==r)throw Js(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ws(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Js("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(Zs(e.algorithm.hash)!==r)throw Js(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ws(e.algorithm,"RSA-PSS"))throw Js("RSA-PSS");const r=parseInt(t.slice(2),10);if(Zs(e.algorithm.hash)!==r)throw Js(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw Js("Ed25519 or Ed448");break;case"Ed25519":if(!Ws(e.algorithm,"Ed25519"))throw Js("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!Ws(e.algorithm,"ECDSA"))throw Js("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw Js(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const Ys=(0,Ts.promisify)(Es.sign),Qs=new TextEncoder,Xs=new TextDecoder;const ea=e=>e?.[Symbol.toStringTag],ta=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ra(e,t,r,o){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,o)=>{if(!(t instanceof Uint8Array)){if(o&&Ls(t)){if(function(e){return Ls(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ta(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!qs(t))throw new TypeError(Us(e,t,...Ks,"Uint8Array",o?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${ea(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,o,e):((e,t,r,o)=>{if(o&&Ls(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ta(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ta(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!qs(t))throw new TypeError(Us(e,t,...Ks,o?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${ea(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${ea(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${ea(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${ea(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${ea(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,o,e)}ra.bind(void 0,!1);const oa=ra.bind(void 0,!0);class na{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new As("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new As("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let o=!0;if(function(e,t,r,o,n){if(void 0!==n.crit&&void 0===o?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;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;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new Ds(`Extension Header Parameter "${t}" is not recognized`);if(void 0===n[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===o[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(o.crit)}(As,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(o=this._protectedHeader.b64,"boolean"!=typeof o))throw new As('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:n}=r;if("string"!=typeof n||!n)throw new As('JWS "alg" (Algorithm) Header Parameter missing or invalid');oa(n,e,"sign");let i,s=this._payload;o&&(s=Qs.encode(Cs(s))),i=this._protectedHeader?Qs.encode(Cs(JSON.stringify(this._protectedHeader))):Qs.encode("");const a=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let o=0;for(const t of e)r.set(t,o),o+=t.length;return r}(i,Qs.encode("."),s),c=await(async(e,t,r)=>{const o=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(zs(t,...Ks));return(0,Es.createSecretKey)(t)}if(t instanceof Es.KeyObject)return t;if(js(t))return Gs(t,e,"sign"),Es.KeyObject.from(t);if(Ls(t))return e.startsWith("HS")?(0,Es.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(zs(t,...Ks,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=Es.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Ds(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),o);return t.update(r),t.digest()}return Ys(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Ds(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,o,n,i;if(t instanceof Es.KeyObject)r=t.asymmetricKeyType,o=t.asymmetricKeyDetails;else switch(n=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Hs(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:n}=o,i=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${i}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==n&&n>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Hs(t,e),i={padding:Es.constants.RSA_PKCS1_PSS_PADDING,saltLength:Es.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const o=Fs(t),n=Bs.get(e);if(o!==n)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${n}, got ${o}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new Ds(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return n?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}(e,o))})(n,e,a),d={signature:Cs(c),payload:""};return o&&(d.payload=Xs.decode(s)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=Xs.decode(i)),d}}class ia{_flattened;constructor(e){this._flattened=new na(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const sa=e=>Math.floor(e.getTime()/1e3),aa=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ca=e=>{const t=aa.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(3600*r);break;case"day":case"days":case"d":o=Math.round(86400*r);break;case"week":case"weeks":case"w":o=Math.round(604800*r);break;default:o=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-o:o};function da(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class la{_payload;constructor(e={}){if(!Vs(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:da("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:da("setNotBefore",sa(e))}:this._payload={...this._payload,nbf:sa(new Date)+ca(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:da("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:da("setExpirationTime",sa(e))}:this._payload={...this._payload,exp:sa(new Date)+ca(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:sa(new Date)}:e instanceof Date?this._payload={...this._payload,iat:da("setIssuedAt",sa(e))}:this._payload="string"==typeof e?{...this._payload,iat:da("setIssuedAt",sa(new Date)+ca(e))}:{...this._payload,iat:da("setIssuedAt",e)},this}}class ua extends la{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new ia(Qs.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Rs("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var ha=r(77753),fa=r(95277);const pa=require("fs");var ma=r(16928);class ga extends fa.CryptoProvider{async sign(e,t){const r=Buffer.from(t,"base64"),o=64===r.length?r.subarray(0,32):r,n=Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),o]),i=ks.createPrivateKey({key:n,format:"der",type:"pkcs8"}),s=ks.sign(null,Buffer.from(e),i);return new Uint8Array(s)}async verify(e,t,r){try{const o=Buffer.from(r,"base64"),n=Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),o]),i=ks.createPublicKey({key:n,format:"der",type:"spki"});return ks.verify(null,Buffer.from(e),i,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=ks.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),r=t.subarray(16,48),o=e.subarray(12,44);return{privateKey:r.toString("base64"),publicKey:o.toString("base64")}}async hash(e){const t=ks.createHash("sha256").update(Buffer.from(e)).digest();return new Uint8Array(t)}async randomBytes(e){return new Uint8Array(ks.randomBytes(e))}}fa.StorageProvider,fa.IdentityProvider;class ya{async generateProof(e,t,r,o={}){const n=this.generateCanonicalHashes(e,t),i={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:n.requestHash,responseHash:n.responseHash,...o};return{jws:await this.generateJWS(i),meta:i}}generateCanonicalHashes(e,t){const r={method:e.method,...e.params&&{params:e.params}},o=t.data;return{requestHash:this.generateSHA256Hash(r),responseHash:this.generateSHA256Hash(o)}}generateSHA256Hash(e){const t=this.canonicalizeJSON(e);return`sha256:${(0,ks.createHash)("sha256").update(t,"utf8").digest("hex")}`}canonicalizeJSON(e){return(0,ha.d)(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,Es.createPrivateKey)({key:Is.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),o={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new ua(o).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=Buffer.from(e,"base64"),r=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),o=Buffer.concat([r,t.subarray(0,32)]).toString("base64");return"-----BEGIN PRIVATE KEY-----\n"+(o.match(/.{1,64}/g)?.join("\n")||o)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const o=this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==o.requestHash||e.meta.responseHash!==o.responseHash)return!1;const n=this.base64PublicKeyToJWK(this.identity.publicKey),i=new ga,s=new fa.CryptoService(i);return await s.verifyJWS(e.jws,n,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch(e){return console.error("[ProofGenerator] Proof verification error:",e),!1}}base64PublicKeyToJWK(e){const t=Buffer.from(e,"base64");if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),kid:this.identity.kid}}constructor(e){var t,r;r=void 0,(t="identity")in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r,this.identity=e}}const va=require("fs/promises"),wa=(0,Ts.promisify)(Es.generateKeyPair);function _a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r(75306);class ba{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,pa.existsSync)(e)){const t=await(0,va.readFile)(e,"utf-8"),r=JSON.parse(t);let o=r.kid||r.keyId;if(r.keyId&&!r.kid&&o.startsWith("key-")){o=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:o,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${o}`),e}return{did:r.did,kid:o,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new Ds("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await wa("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return wa("ec",{namedCurve:"P-256"});case"ES256K":return wa("ec",{namedCurve:"secp256k1"});case"ES384":return wa("ec",{namedCurve:"P-384"});case"ES512":return wa("ec",{namedCurve:"P-521"});case"Ed25519":return wa("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return wa("ed25519");case"Ed448":return wa("ed448");default:throw new Ds("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return wa("ec",{namedCurve:e});case"X25519":return wa("x25519");case"X448":return wa("x448");default:throw new Ds("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Ds('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return(e=>{let t;if(js(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=Es.KeyObject.from(e)}else{if(!Ns(e)){if(e instanceof Uint8Array)return{kty:"oct",k:Cs(e)};throw new TypeError(zs(e,...Ks,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new Ds("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})})(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),o=Buffer.from(t.x,"base64url").toString("base64"),n=this.generateMultibaseKid(o),i={did:`did:web:localhost:3000:agents:${(0,ks.createHash)("sha256").update(o).digest("hex").substring(0,8)}`,kid:n,privateKey:r,publicKey:o,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(i),i}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,va.mkdir)((0,ma.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,va.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const o of e){const e=process.env[o];e?r[o]=e:t.push(o)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const o=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),n=(0,ks.createHash)("sha256").update(o).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:n,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){_a(this,"config",void 0),_a(this,"cachedIdentity",void 0);const t=r(16928);let o=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(o)||(o=t.resolve(process.cwd(),o)),this.config={privacyMode:!1,...e,devIdentityPath:o},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function Sa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new ba;const Pa=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){Sa(this,"config",new Map),Sa(this,"delegationVerifier",null),Sa(this,"authConfig",null),Sa(this,"debug",!1),Sa(this,"currentSession",null)}},$a=require("@kya-os/contracts/runtime");async function ka(e,t,r,o){const n=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),i=Date.now()+(r.bouncer.resumeTokenTtl||6e5),s=new URL(r.bouncer.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",n);const a={title:"Authorization Required",hint:["link","qr"],authorizationCode:n.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(s.toString())}`};return(0,$a.createNeedsAuthorizationError)({message:o,authorizationUrl:s.toString(),resumeToken:n,expiresAt:i,scopes:t,display:a})}function Ea(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ia{async has(e,t){const r=t?`nonce:${t}:${e}`:e,o=this.cache.get(r);return!(!o||Date.now()>o.expiresAt&&(this.cache.delete(r),1))}async add(e,t,r){const o=r?`nonce:${r}:${e}`:e,n=this.cache.get(o);if(n&&Date.now()<=n.expiresAt)throw new Error(`Nonce ${e} already exists - potential replay attack`);const i=t<=0?Date.now()-1:Date.now()+1e3*t,s={sessionId:`mem_${Date.now()}_${Math.random().toString(36).substring(2)}`,expiresAt:i};this.cache.set(o,s)}async cleanup(){const e=Date.now(),t=[];for(const[r,o]of this.cache.entries())e>o.expiresAt&&t.push(r);for(const e of t)this.cache.delete(e)}getStats(){const e=Date.now();let t=0;for(const r of this.cache.values())e>r.expiresAt&&t++;return{size:this.cache.size,expired:t}}clear(){this.cache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.cache.clear()}constructor(e=6e4){Ea(this,"cache",new Map),Ea(this,"cleanupInterval",void 0),console.warn("⚠️ MemoryNonceCache is not suitable for multi-instance deployments. For production use with multiple instances, configure Redis, DynamoDB, or Cloudflare KV."),this.cleanupInterval=setInterval(()=>{this.cleanup().catch(console.error)},e)}}function Ca(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ta{setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust XMCP_I_TS_SKEW_SEC if needed.`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const o=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,o,e.agentDid);const n=this.generateSessionId(),i=this.buildClientInfo(e),s={sessionId:n,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...i&&{clientInfo:i}};return this.sessions.set(n,s),{success:!0,session:s}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}generateSessionId(){const e=(0,ks.randomBytes)(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=e.toString("hex");return`mcpi_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}generateClientId(){return`client_${(0,ks.randomBytes)(6).toString("hex")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}buildClientInfo(e){if(!e.clientInfo&&"string"!=typeof e.clientProtocolVersion&&void 0===e.clientCapabilities)return;const t=e.clientInfo;return{name:this.normalizeClientInfoString(t?.name)??"unknown",title:this.normalizeClientInfoString(t?.title),version:this.normalizeClientInfoString(t?.version),platform:this.normalizeClientInfoString(t?.platform),vendor:this.normalizeClientInfoString(t?.vendor),persistentId:this.normalizeClientInfoString(t?.persistentId),clientId:this.normalizeClientInfoString(t?.clientId)??this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){return(0,ks.randomBytes)(16).toString("base64url")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let o=e-r.lastActivity>60*r.ttlMinutes;!o&&this.config.absoluteSessionLifetime&&(o=e-r.createdAt>60*this.config.absoluteSessionLifetime),o&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}constructor(e={}){Ca(this,"config",void 0),Ca(this,"sessions",new Map),this.config={timestampSkewSeconds:parseInt(process.env.XMCP_I_TS_SKEW_SEC||"120"),sessionTtlMinutes:parseInt(process.env.XMCP_I_SESSION_TTL_MIN||"30"),nonceCache:new Ia,...e},this.config.nonceCache instanceof Ia&&console.warn("Warning: Using MemoryNonceCache - not suitable for multi-instance deployments. Consider using Redis, DynamoDB, or Cloudflare KV for production.")}}new Ta;const Oa=new(require("async_hooks").AsyncLocalStorage);function Da(){return(Oa.getStore()?.session)?.agentDid}function Aa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ra{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){Aa(this,"name","AgentShield"),Aa(this,"apiUrl",void 0),Aa(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class xa{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.error(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.error(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.error(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.error(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){Aa(this,"queue",[]),Aa(this,"pendingBatches",[]),Aa(this,"config",void 0),Aa(this,"flushTimer",void 0),Aa(this,"retryTimer",void 0),Aa(this,"closed",!1),Aa(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}function ja(e){let t=e.type;return"provider"in e&&e.provider&&(t+=`:${e.provider}`),"issuer"in e&&e.issuer&&(t+=`:${e.issuer}`),"credentialType"in e&&e.credentialType&&(t+=`:${e.credentialType}`),t}const Na="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,Ma=Na?"string"==typeof Na?JSON.parse(Na):Na:null;let za=null;async function Ua(e,t,o,n){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return o?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}o?.debug&&console.error("[MCPI] Registering handlers for the first time");const i=new Ta;let s=null;if(o?.enabled)try{s=new ba({environment:o.environment||"development",devIdentityPath:o.devIdentityPath,debug:o.debug});const e=await s.ensureIdentity();o.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${o.devIdentityPath||".mcpi/identity.json"}`))}catch(e){o?.debug&&console.error("[MCPI] Failed to initialize identity:",e),s=null}await async function(e){if(za)return za;if(!Ma)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",Ma);const t=await r(23967)(Ma),o="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!o?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const n=o.proofing;if(!n.batchQueue?.destinations||0===n.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const i=[];for(const t of n.batchQueue.destinations)"agentshield"===t.type&&(i.push(new Ra(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===i.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(za=new xa({destinations:i,maxBatchSize:n.batchQueue.maxBatchSize||10,flushIntervalMs:n.batchQueue.flushIntervalMs||5e3,maxRetries:n.batchQueue.maxRetries||3,debug:n.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${n.batchQueue.maxBatchSize}, flush: ${n.batchQueue.flushIntervalMs}ms, destinations: ${i.length})`),za)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(o?.debug);const a=[],c=new Map;if(t.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),o={name:r,description:"No description provided"};let n={};const{default:i,metadata:s,schema:d}=e;"object"==typeof s&&null!==s&&Object.assign(o,s),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(d)?Object.assign(n,d):null!=d&&console.warn(`Invalid schema for tool "${o.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===o.annotations&&(o.annotations={}),void 0===o.annotations.title&&(o.annotations.title=o.name);const l={name:o.name,description:o.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(n).map(([e,t])=>[e,{type:"string"}]))}};a.push(l),c.set(o.name,i)}),o?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call, handshake)"),s)try{const e=await s.ensureIdentity();i.setServerDid(e.did)}catch(e){o?.debug&&console.error("[MCPI] Failed to set server DID on session manager:",e),s=null}return a.push({name:"_mcpi_handshake",description:"Internal MCP-I handshake tool for session establishment. Clients should call this before protected tools.",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Unique nonce for replay prevention"},audience:{type:"string",description:"Target audience (server DID or URL)"},timestamp:{type:"number",description:"Unix timestamp in seconds"},agentDid:{type:"string",description:"Agent DID for delegation verification (optional)"},clientInfo:{type:"object",description:"MCP client metadata (optional)",properties:{name:{type:"string"},version:{type:"string"},platform:{type:"string"},vendor:{type:"string"}}},clientProtocolVersion:{type:"string",description:"MCP protocol version (optional)"},clientCapabilities:{type:"object",description:"MCP client capabilities (optional)",additionalProperties:!0}},required:["nonce","audience","timestamp"]}}),c.set("_mcpi_handshake",async e=>{const t=[];if((!e.nonce||"string"==typeof e.nonce&&0===e.nonce.trim().length)&&t.push("nonce"),(!e.audience||"string"==typeof e.audience&&0===e.audience.trim().length)&&t.push("audience"),void 0===e.timestamp||null===e.timestamp||"number"!=typeof e.timestamp||e.timestamp<=0||!Number.isInteger(e.timestamp)){if(void 0!==e.timestamp&&null!==e.timestamp)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid timestamp: must be a positive integer (Unix timestamp in seconds)",details:{received:typeof e.timestamp,value:e.timestamp}}};t.push("timestamp")}if(t.length>0)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Missing required field(s): ${t.join(", ")}`,details:{missingFields:t,requiredFields:["nonce","audience","timestamp"]}}};const r=e.timestamp,n={nonce:String(e.nonce).trim(),audience:String(e.audience).trim(),timestamp:r,agentDid:"string"==typeof e.agentDid&&e.agentDid.trim().length>0?e.agentDid.trim():void 0,clientInfo:"object"==typeof e.clientInfo&&null!==e.clientInfo?e.clientInfo:void 0,clientProtocolVersion:"string"==typeof e.clientProtocolVersion&&e.clientProtocolVersion.trim().length>0?e.clientProtocolVersion.trim():void 0,clientCapabilities:"object"==typeof e.clientCapabilities&&null!==e.clientCapabilities?e.clientCapabilities:void 0};if(!("object"==typeof(s=n)&&null!==s&&"string"==typeof s.nonce&&s.nonce.length>0&&"string"==typeof s.audience&&s.audience.length>0&&"number"==typeof s.timestamp&&s.timestamp>0&&Number.isInteger(s.timestamp)))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid handshake request format. Required: nonce, audience, timestamp"}};var s;const a=await i.validateHandshake(n);return o?.debug&&a.success&&a.session?.clientInfo&&console.error("[MCPI] Client connected:",{name:a.session.clientInfo.name,version:a.session.clientInfo.version,platform:a.session.clientInfo.platform,vendor:a.session.clientInfo.vendor,clientId:a.session.clientInfo.clientId}),a.success&&a.session?{success:!0,sessionId:a.session.sessionId,serverDid:a.session.serverDid,ttlMinutes:a.session.ttlMinutes,...a.session.clientInfo&&{clientInfo:a.session.clientInfo}}:{success:!1,error:a.error}}),e.setRequestHandler(gi,async e=>({tools:a})),e.setRequestHandler(_i,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await i.getSession(t),!r&&o?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),a={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},Oa.run(a,async()=>{const{name:t,arguments:i}=e.params,a=c.get(t);if(!a)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const d=Pa.get(t);if(d?.requiresDelegation){const e=Pa.getAuthConfig();if(!Pa.getDelegationVerifier()||!e)return o?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=Da();if(!r)return o?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Math.floor(Date.now()/1e3)}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};o?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${d.requiredScopes?.join(", ")}`);const i=await async function(e,t,r){const o=Date.now();let n,i;if(r.debug&&console.error(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(n=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),o={"Content-Type":"application/json"};t.apiKey&&(o["X-API-Key"]=t.apiKey);const n=await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:o});if(!n.ok){if(404===n.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${n.status} ${n.statusText}`)}const i=await n.json();return{agentDid:i.agentDid||e,score:i.score||50,totalInteractions:i.totalInteractions||0,successRate:i.successRate||0,riskLevel:i.riskLevel||"unknown",updatedAt:i.updatedAt||Date.now()}}(e,r.kta),r.debug&&console.error(`[AuthHandshake] Reputation score: ${n.score}`),n.score<r.bouncer.minReputationScore)return r.debug&&console.error(`[AuthHandshake] Reputation ${n.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await ka(e,t,r,"Agent reputation score below threshold"),reputation:n,reason:"Low reputation score"}}catch(e){console.warn("[AuthHandshake] Failed to check reputation:",e)}try{i=await r.delegationVerifier.verify(e,t)}catch(o){console.error("[AuthHandshake] Delegation verification failed:",o);const n=`Delegation verification error: ${o instanceof Error?o.message:"Unknown error"}`;return{authorized:!1,authError:await ka(e,t,r,n),reason:n}}return i.valid&&i.delegation?(r.debug&&console.error(`[AuthHandshake] Delegation valid, authorized (${Date.now()-o}ms)`),{authorized:!0,delegation:i.delegation,credential:i.credential,reputation:n,reason:"Valid delegation found"}):(r.debug&&console.error(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-o}ms)`),{authorized:!1,authError:await ka(e,t,r,i.reason||"No valid delegation found"),reputation:n,reason:i.reason||"No delegation"})}(r,d.requiredScopes||[],e);if(!i.authorized){o?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`);const e=new fa.DelegationErrorFormatter(n),{message:r,consentUrl:s}=e.format({toolName:t,consentUrl:i.authError?.authorizationUrl,scopes:i.authError?.scopes,clientId:void 0});return{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,displayMessage:r,authorizationUrl:s,resumeToken:i.authError?.resumeToken,scopes:i.authError?.scopes,display:i.authError?.display})}],isError:!0}}if(i.authorized&&d.authorization&&i.credential){const n=d.authorization,s=i.credential.authorization;if(!s){o?.debug&&console.error(`[MCPI] Tool "${t}" blocked - credential missing authorization data`);const i=new URL(e.bouncer.authorizationUrl);return i.searchParams.set("agent_did",r),i.searchParams.set("scopes",(d.requiredScopes||[]).join(",")),i.searchParams.set("tool",t),{content:[{type:"text",text:JSON.stringify({error:"authorization_data_missing",message:`Tool "${t}" requires authorization ${ja(n)} but delegation credential does not contain authorization data. Please re-authorize.`,authorizationUrl:i.toString(),scopes:d.requiredScopes||[],requiredAuth:n})}],isError:!0}}if(!(0,fa.authorizationMatches)(s,n)){o?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization method mismatch`);const i=new URL(e.bouncer.authorizationUrl);return i.searchParams.set("agent_did",r),i.searchParams.set("scopes",(d.requiredScopes||[]).join(",")),i.searchParams.set("tool",t),{content:[{type:"text",text:JSON.stringify({error:"authorization_method_mismatch",message:`Tool "${t}" requires re-authorization. Delegation was created with ${ja(s)} but tool now requires ${ja(n)}.`,authorizationUrl:i.toString(),scopes:d.requiredScopes||[],currentAuth:s,requiredAuth:n})}],isError:!0}}}o?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`)}try{const e=await a(i||{}),n={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(s)try{const a=await s.ensureIdentity(),c={method:t,params:i||{}},d={data:e},l=Math.floor(Date.now()/1e3),u=r??{sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:l,timestamp:l,lastActivity:l,ttlMinutes:30,identityState:"anonymous"};let h;const f=Pa.get(t);h=f?.requiredScopes&&f.requiredScopes.length>0?f.requiredScopes[0]:`${t}:execute`,o?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${h}`);const p=new ya(a),m=await p.generateProof(c,d,u,{scopeId:h,clientDid:r?.clientDid});if(o?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${m.meta.did}`),za)try{za.enqueue(m),o?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){o?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...n,_meta:{proof:m}}}catch(e){return o?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),n}return n}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}});var a}),o?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const qa=INJECTED_TOOLS,Ka="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,Va=Ka?JSON.parse(Ka):void 0,La={name:"MCP Server",version:"0.0.1"},Fa={capabilities:{tools:{}}};function Ha(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class Ba{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){Ha(this,"mcpServer",void 0),Ha(this,"transport",void 0),Ha(this,"debug",void 0),this.mcpServer=e,this.transport=new us,this.debug=t}}const Ja=STDIO_CONFIG.debug||!1;(async function(){if(Va?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(Va?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;Va?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(La)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(Fa)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new $s(La,Fa);if(Va?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(qa);return Va?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>qa[t]().then(r=>{Va?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),Va?.debug&&console.error("[createServer] Tools loaded, configuring server");const o=await async function(e,t){return await Ua(e,t,Va),e}(e,r);return Va?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=o),o})().then(e=>{new Ba(e,Ja).start()})})()})();
4
+ deps: ${r}}`};const a={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e)"__proto__"!==n&&((Array.isArray(e[n])?t:r)[n]=e[n]);return[t,r]}(e);s(e,t),c(e,r)}};function s(e,t=e.schema){const{gen:r,data:i,it:a}=e;if(0===Object.keys(t).length)return;const s=r.let("missing");for(const c in t){const u=t[c];if(0===u.length)continue;const d=(0,o.propertyInData)(r,i,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?r.if(d,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(r.if(n._`${d} && (${(0,o.checkMissingProp)(e,u,s)})`),(0,o.reportMissingProp)(e,s),r.else())}}function c(e,t=e.schema){const{gen:r,data:n,keyword:a,it:s}=e,c=r.name("valid");for(const u in t)(0,i.alwaysValidSchema)(s,t[u])||(r.if((0,o.propertyInData)(r,n,u,s.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>r.var(c,!0)),e.ok(c))}t.validatePropertyDeps=s,t.validateSchemaDeps=c,t.default=a},16928:e=>{"use strict";e.exports=require("path")},17080:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o=r(6013),a={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>n._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:a,schemaCode:s,schema:c}=e;a||c&&"object"==typeof c?e.fail$data(n._`!${(0,i.useFunc)(t,o.default)}(${r}, ${s})`):e.fail(n._`${c} !== ${r}`)}};t.default=a},17214:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAUTH_CORS_HEADERS=t.PREFLIGHT_CORS_HEADERS=t.MCP_CORS_HEADERS=t.WELL_KNOWN_CORS_HEADERS=void 0,t.mergeCORSHeaders=function(e,r=t.WELL_KNOWN_CORS_HEADERS){return{...e,...r}},t.applyCORSHeaders=function(e,r=t.MCP_CORS_HEADERS){Object.entries(r).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})},t.WELL_KNOWN_CORS_HEADERS={"Access-Control-Allow-Origin":"*",Vary:"Origin"},t.MCP_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"mcp-session-id",Vary:"Origin"},t.PREFLIGHT_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, mcp-session-id, mcp-protocol-version",Vary:"Origin"},t.OAUTH_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, Accept, mcp-protocol-version","Access-Control-Expose-Headers":"Content-Type",Vary:"Origin"}},17306:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598);t.default=(e,t)=>(0,n.createHash)(e).update(t).digest()},17759:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new n.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};const n=r(39069)},18109:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryResumeTokenStore=void 0,t.verifyOrHints=async function(e,t,r,n){const a=Date.now();let s,c;if(r.debug&&i.logger.debug(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(s=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),n={"Content-Type":"application/json"};let i;if(t.apiKey&&(n["X-API-Key"]=t.apiKey),i="argus"===t.apiFormat?await fetch(`${r}/v1/reputation/${encodeURIComponent(e)}`,{method:"POST",headers:n,body:JSON.stringify({include_details:!1})}):await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:n}),!i.ok){if(404===i.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${i.status} ${i.statusText}`)}const o=await i.json(),a=o.score??50,s=(o.level??o.riskLevel??"unknown").toLowerCase(),c="low"===s||"medium"===s||"high"===s?s:"unknown";return{agentDid:o.agent_did??o.agentDid??e,score:a,totalInteractions:o.totalInteractions??0,successRate:o.successRate??0,riskLevel:c,updatedAt:o.calculatedAt?new Date(o.calculatedAt).getTime():o.updatedAt??Date.now()}}(e,r.kta),r.debug&&i.logger.debug(`[AuthHandshake] Reputation score: ${s.score}`),s.score<r.bouncer.minReputationScore)return r.debug&&i.logger.debug(`[AuthHandshake] Reputation ${s.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await o(e,t,r,"Agent reputation score below threshold"),reputation:s,reason:"Low reputation score"}}catch(e){i.logger.warn("[AuthHandshake] Failed to check reputation:",e)}try{c=await r.delegationVerifier.verify(e,t)}catch(n){i.logger.error("[AuthHandshake] Delegation verification failed:",n);const a=`Delegation verification error: ${n instanceof Error?n.message:"Unknown error"}`;return{authorized:!1,authError:await o(e,t,r,a),reason:a}}return c.valid&&c.delegation?(r.debug&&i.logger.debug(`[AuthHandshake] Delegation valid, authorized (${Date.now()-a}ms)`),{authorized:!0,delegation:c.delegation,credential:c.credential,reputation:s,reason:"Valid delegation found"}):(r.debug&&i.logger.debug(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-a}ms)`),{authorized:!1,authError:await o(e,t,r,c.reason??"No valid delegation found"),reputation:s,reason:c.reason??"No delegation"})},t.hasSensitiveScopes=function(e){const t=["write","delete","admin","payment","transfer","execute","modify"];return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))};const n=r(3051),i=r(46171);async function o(e,t,r,i){const o=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),a=Date.now()+(r.bouncer.resumeTokenTtl??6e5),s=new URL(r.bouncer.authorizationUrl);s.searchParams.set("agent_did",e),s.searchParams.set("scopes",t.join(",")),s.searchParams.set("resume_token",o);const c={title:"Authorization Required",hint:["link","qr"],authorizationCode:o.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(s.toString())}`};return(0,n.createNeedsAuthorizationError)({message:i,authorizationUrl:s.toString(),resumeToken:o,expiresAt:a,scopes:t,display:c})}t.MemoryResumeTokenStore=class{tokens=new Map;ttl;constructor(e=6e5){this.ttl=e}async create(e,t,r){const n=`rt_${Date.now()}_${Math.random().toString(36).substring(2,18)}`,i=Date.now();return this.tokens.set(n,{agentDid:e,scopes:t,createdAt:i,expiresAt:i+this.ttl,metadata:r,fulfilled:!1}),n}async get(e){const t=this.tokens.get(e);return t?Date.now()>t.expiresAt?(this.tokens.delete(e),null):t.fulfilled?null:{agentDid:t.agentDid,scopes:t.scopes,createdAt:t.createdAt,expiresAt:t.expiresAt,metadata:t.metadata}:null}async fulfill(e){const t=this.tokens.get(e);t&&(t.fulfilled=!0)}clear(){this.tokens.clear()}}},18610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}},18951:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5019);n.code='require("ajv/dist/runtime/uri").default',t.default=n},19265:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598),i=r(80384),o=r(90489),a=r(45935),s=r(81593),c=r(99135),u=r(60322),d=r(29994),l=r(71759),p=r(21444),f=r(39069),h=r(4268),m=r(58242);t.default=(e,t,r,g,v)=>{let y;if((0,c.isCryptoKey)(r))(0,u.checkEncCryptoKey)(r,e,"encrypt"),y=n.KeyObject.from(r);else{if(!(r instanceof Uint8Array||(0,d.default)(r)))throw new TypeError((0,l.default)(r,...m.types,"Uint8Array"));y=r}switch((0,o.default)(e,y),g?(0,i.default)(e,g):g=(0,p.default)(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return function(e,t,r,i,o){const c=parseInt(e.slice(1,4),10);(0,d.default)(r)&&(r=r.export());const u=r.subarray(c>>3),l=r.subarray(0,c>>3),p=`aes-${c}-cbc`;if(!(0,h.default)(p))throw new f.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);const m=(0,n.createCipheriv)(p,u,i),g=(0,a.concat)(m.update(t),m.final()),v=parseInt(e.slice(-3),10);return{ciphertext:g,tag:(0,s.default)(o,i,g,v,l,c),iv:i}}(e,t,y,g,v);case"A128GCM":case"A192GCM":case"A256GCM":return function(e,t,r,i,o){const a=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,h.default)(a))throw new f.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);const s=(0,n.createCipheriv)(a,r,i,{authTagLength:16});o.byteLength&&s.setAAD(o,{plaintextLength:t.length});const c=s.update(t);return s.final(),{ciphertext:c,tag:s.getAuthTag(),iv:i}}(e,t,y,g,v);default:throw new f.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}}},21070:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(24954).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=n},21444:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bitLength=o;const n=r(39069),i=r(84641);function o(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new n.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}t.default=e=>(0,i.default)(new Uint8Array(o(e)>>3))},21644:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryResumeTokenStore=t.hasSensitiveScopes=t.verifyOrHints=void 0;var n=r(18109);Object.defineProperty(t,"verifyOrHints",{enumerable:!0,get:function(){return n.verifyOrHints}}),Object.defineProperty(t,"hasSensitiveScopes",{enumerable:!0,get:function(){return n.hasSensitiveScopes}}),Object.defineProperty(t,"MemoryResumeTokenStore",{enumerable:!0,get:function(){return n.MemoryResumeTokenStore}})},22562:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createLocalJWKSet=function(e){const t=new c(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>s(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r};const n=r(68846),i=r(39069),o=r(71661);function a(e){return(0,o.default)(e)}function s(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class c{_jwks;_cached=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(a)}(e))throw new i.JWKSInvalid("JSON Web Key Set malformed");this._jwks=s(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},o=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new i.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}(r),a=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:s,length:c}=a;if(0===c)throw new i.JWKSNoMatchingKey;if(1!==c){const e=new i.JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of a)try{yield await u(t,e,r)}catch{}},e}return u(this._cached,s,r)}}async function u(e,t,r){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[r]){const e=await(0,n.importJWK)({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new i.JWKSInvalid("JSON Web Key Set members must be public keys");o[r]=e}return o[r]}},23137:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MCPIRuntimeBase=void 0;const n=r(4901),i=r(81296),o=r(36255),a=r(82906),s=r(65067),c=e=>"object"==typeof e&&null!==e;class u{crypto;clock;fetch;storage;nonceCache;identity;config;cachedIdentity;sessions=new Map;lastProof;userDidManager;interceptedCalls=new Map;cryptoService;proofVerifier;accessControlService;_extAppsAvailable;constructor(e){this.config=e,this.crypto=e.cryptoProvider,this.clock=e.clockProvider,this.fetch=e.fetchProvider,this.storage=e.storageProvider,this.nonceCache=e.nonceCacheProvider,this.identity=e.identityProvider,this.cryptoService=new i.CryptoService(this.crypto)}async initialize(){this.cachedIdentity=await this.identity.getIdentity(),this.config.identity?.generateUserDids&&(this.userDidManager=new s.UserDidManager({crypto:this.crypto,storage:this.config.identity?.userDidStorage?{get:async e=>await this.storage.get(`userDid:${e}`),set:async(e,t,r)=>{await this.storage.set(`userDid:${e}`,t)},delete:async e=>await this.storage.delete(`userDid:${e}`)}:void 0,useDidWeb:"persistent"===this.config.identity?.userDidStorage}));const e=this.nonceCache;"function"==typeof e.initialize&&await e.initialize(),this.config.audit?.enabled&&this.logAudit("runtime_initialized",{did:this.cachedIdentity.did,environment:this.config.environment||"development",userDidGeneration:this.config.identity?.generateUserDids?"enabled":"disabled"})}async getIdentity(){return this.cachedIdentity||(this.cachedIdentity=await this.identity.getIdentity()),this.cachedIdentity}async handleHandshake(e){const t=await this.getIdentity(),r=this.clock.now(),n=await this.generateSessionId();let i;if(this.userDidManager)try{const t=e.oauthIdentity;i=await this.userDidManager.getOrCreateUserDid(n,t)??void 0,this.config.audit?.enabled&&(i?console.error("[MCP-I] Resolved existing user DID for session:",{userDid:i.substring(0,20)+"...",hasOAuth:!!t,provider:t?.provider}):console.error("[MCP-I] Session started anonymous (no userDid):",{sessionId:n.substring(0,8)+"...",hasOAuth:!!t}))}catch(e){console.warn("[MCP-I] Failed to resolve user DID:",e)}const o=e=>{if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0},a=o(e.clientProtocolVersion),s=e.clientCapabilities,c=e.clientInfo,u=c||"string"==typeof a||void 0!==s?{name:o(c?.name)??"unknown",title:o(c?.title),version:o(c?.version),platform:o(c?.platform),vendor:o(c?.vendor),persistentId:o(c?.persistentId),clientId:o(c?.clientId)??crypto.randomUUID(),protocolVersion:a,capabilities:s}:void 0,d={id:n,clientDid:e.clientDid||i,userDid:i,agentDid:e.agentDid,serverDid:t.did,audience:e.audience,createdAt:r,expiresAt:this.clock.calculateExpiry(60*(this.config.session?.ttlMinutes||30)),clientInfo:u,identityState:i?"authenticated":"anonymous",oauthIdentity:e.oauthIdentity??void 0};this.sessions.set(n,d);const l={sessionId:n,agentDid:t.did,timestamp:r,capabilities:["identity","proof","audit"],...i&&{userDid:i}},p=await this.signData(l);return{...l,signature:p}}async updateSessionIdentity(e,t,r){const n=this.sessions.get(e);if(!n)throw new Error(`Session not found: ${e}`);n.userDid=t,n.identityState="authenticated",r&&(n.oauthIdentity=r),this.sessions.set(e,n),this.userDidManager&&await this.userDidManager.setUserDidForSession(e,t,r),this.config.audit?.enabled&&console.error("[MCP-I] Session identity updated (Phase 5):",{sessionId:e.substring(0,8)+"...",userDid:t.substring(0,20)+"...",provider:r?.provider,identityState:"authenticated"})}getSession(e){return this.sessions.get(e)}getConsentProvider(e){if(e.authorization){const t=e.authorization;if(("oauth"===t.type||"oauth2"===t.type||"password"===t.type||"idv"===t.type)&&t.provider)return t.provider}return e.oauthProvider}async processToolCall(e,t,r,i){if(this.config.toolProtectionService){const r=await this.getIdentity();this.config.audit?.enabled&&console.error("[MCP-I] Checking tool protection:",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegation:!(!i?.delegationToken&&!i?.consentProof)});const s=await this.config.toolProtectionService.checkToolProtection(e,r.did);if(s){if(!i?.delegationToken&&!i?.consentProof){const o={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},a=await this.generateResumeToken(o),u=this.buildConsentUrl(e,s.requiredScopes,i,a,void 0,this.getConsentProvider(s)),d=new n.DelegationRequiredError(e,s.requiredScopes,u,o,a);this.interceptedCalls.set(a,o),this.cleanupExpiredInterceptedCalls(),this.config.audit?.enabled&&console.warn("[MCP-I] BLOCKED: Tool requires delegation but none provided",{tool:e,requiredScopes:s.requiredScopes,agentDid:r.did.slice(0,20)+"...",resumeToken:d.resumeToken,consentUrl:u});const l=i?.clientInfo,p=c(l?.capabilities)?l.capabilities:void 0,f=this.buildConsentUIResult(e,s.requiredScopes,i,a,i?.projectId||void 0,i?.serverOrigin||void 0,p);if(f)return f;throw d}const u=i?.delegationToken,d=i?.consentProof;if(this.accessControlService)try{this.config.audit?.enabled&&console.error("[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!u,hasConsentProof:!!d,requiredScopes:s.requiredScopes});const a={agent_did:r.did,scopes:s.requiredScopes};i?.userDid&&(a.user_did=i.userDid,this.config.audit?.enabled&&console.error("[MCP-I] 🔐 Including user_did in verification request",{userDid:i.userDid.slice(0,20)+"..."})),u?a.delegation_token=u:d&&(a.credential_jwt=d),a.timestamp=this.clock.now(),(i?.clientDid||i?.clientId)&&(a.client_info={origin:i?.serverOrigin,user_agent:i?.userAgent});const c=await this.accessControlService.verifyDelegation(a,{delegationToken:u||void 0,credentialJwt:d||void 0});if(!c.data.valid){const o=c.data.reason||"Delegation token invalid or expired",a=c.data.error;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:o,errorCode:a?.code,errorMessage:a?.message,requiredScopes:s.requiredScopes});const u={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},d=await this.generateResumeToken(u),l=this.buildConsentUrl(e,s.requiredScopes,i,d,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(d,u),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,l,u,d)}const l=c.data.credential,p=l?.user_identifier,f=l?.user_id,h=i?.userDid;if(p&&h){const o=p===h||f===h,a=p.startsWith("did:");if((a||f)&&!o){p.substring(0,20),h.substring(0,20),this.config.audit?.enabled&&console.error("[MCP-I] 🔒 SECURITY: User identifier validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:p.substring(0,20)+"...",delegationUserId:f?f.substring(0,20)+"...":"N/A",sessionUserDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"...",reason:"user_identifier_mismatch",severity:"high"});const o={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},a=await this.generateResumeToken(o),c=this.buildConsentUrl(e,s.requiredScopes,i,a,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(a,o),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,c,o,a)}this.config.audit?.enabled&&console.error("[MCP-I] ✅ User identifier validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",userDid:h.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"...",matchType:o?"direct":"trusted_agentshield_verification",delegationIdentifierFormat:a?"did":"email_or_other"})}else p&&!h&&this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationUserIdentifier:p.substring(0,20)+"...",sessionId:i?.id?.substring(0,20)+"..."});const m=s.authorization,g=l?.authorization;if(m&&l){if(!g){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Tool requires authorization but credential missing auth data",{tool:e,agentDid:r.did.slice(0,20)+"...",toolAuth:m,note:"Credential exists but missing authorization metadata - rejecting for security"});const o={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},a=await this.generateResumeToken(o),c=this.buildConsentUrl(e,s.requiredScopes,i,a,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(a,o),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,c,o,a)}if(!(0,o.authorizationMatches)(g,m)){const o=m,a="string"==typeof o.provider?`:${o.provider}`:"",c="string"==typeof o.credentialType?`:${o.credentialType}`:"",u=`Authorization method mismatch: delegation has ${g.type}${g.provider?`:${g.provider}`:""}${g.credentialType?`:${g.credentialType}`:""} but tool requires ${m.type}${a}${c}`;this.config.audit?.enabled&&console.error("[MCP-I] ❌ Authorization method validation FAILED",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:u,delegationAuth:g,toolAuth:m});const d={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},l=await this.generateResumeToken(d),p=this.buildConsentUrl(e,s.requiredScopes,i,l,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(l,d),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,p,d,l)}this.config.audit?.enabled&&console.error("[MCP-I] ✅ Authorization method validation PASSED",{tool:e,agentDid:r.did.slice(0,20)+"...",authType:g.type,provider:g.provider||"N/A"})}this.config.audit?.enabled&&console.error("[MCP-I] ✅ Delegation verification SUCCEEDED",{tool:e,agentDid:r.did.slice(0,20)+"...",delegationId:c.data.delegation_id,credentialScopes:c.data.credential?.scopes,requiredScopes:s.requiredScopes})}catch(o){if(o instanceof n.DelegationRequiredError)throw o;if(o instanceof a.AgentShieldAPIError){this.config.audit?.enabled&&console.error("[MCP-I] ❌ Delegation verification error (API failure)",{tool:e,agentDid:r.did.slice(0,20)+"...",errorCode:o.code,errorMessage:o.message,errorDetails:o.details});const a={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},c=await this.generateResumeToken(a),u=this.buildConsentUrl(e,s.requiredScopes,i,c,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(c,a),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,u,a,c)}this.config.audit?.enabled&&console.error("[MCP-I] ❌ Unexpected error during delegation verification",{tool:e,agentDid:r.did.slice(0,20)+"...",error:o instanceof Error?o.message:String(o),errorStack:o instanceof Error?o.stack:void 0});const c={toolName:e,args:t,sessionId:i?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},u=await this.generateResumeToken(c),d=this.buildConsentUrl(e,s.requiredScopes,i,u,void 0,this.getConsentProvider(s));throw this.interceptedCalls.set(u,c),this.cleanupExpiredInterceptedCalls(),new n.DelegationRequiredError(e,s.requiredScopes,d,c,u)}else this.config.audit?.enabled&&console.warn("[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegationToken:!!u,hasConsentProof:!!d})}else this.config.audit?.enabled&&console.error("[MCP-I] Tool protection check passed (no delegation required)",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:"Tool not configured to require delegation"})}const s=await r(t),u=await this.createProof(s,i);return this.lastProof=u,this.config.audit?.enabled&&this.logAudit("tool_executed",{tool:e,sessionId:i?.id,timestamp:this.clock.now()}),s}async resumeToolCall(e,t,r){const n=this.interceptedCalls.get(e);if(!n)throw new Error(`Invalid or expired resume token: ${e}`);if(this.clock.hasExpired(n.expiresAt))throw this.interceptedCalls.delete(e),new Error(`Resume token expired: ${e}`);const i=this.sessions.get(n.sessionId);if(!i)throw new Error(`Session not found for intercepted call: ${n.sessionId}`);const o={...i,delegationToken:r},a=await this.processToolCall(n.toolName,n.args,t,o);return this.interceptedCalls.delete(e),a}async generateResumeToken(e){const t=await this.crypto.randomBytes(16);return`resume_${this.bytesToHex(t)}`}cleanupExpiredInterceptedCalls(){this.clock.now();for(const[e,t]of this.interceptedCalls.entries())this.clock.hasExpired(t.expiresAt)&&this.interceptedCalls.delete(e)}static CONSENT_UI_RESOURCE_URI="ui://mcpi-consent/authorize";hasUICapability(e){if(!e)return console.error("[MCP-I] hasUICapability: no clientCapabilities provided"),!1;try{const{getUiCapability:t,RESOURCE_MIME_TYPE:n}=r(41681),i=t(e),o=i?.mimeTypes?.includes(n)??!1;return console.error("[MCP-I] hasUICapability check:",{hasUI:o,uiCap:i?JSON.stringify(i):"null",capabilityKeys:Object.keys(e)}),o}catch{return console.error("[MCP-I] hasUICapability: ext-apps not available"),!1}}setExtAppsAvailable(e){this._extAppsAvailable=e}isExtAppsAvailable(){return!0===this._extAppsAvailable&&!0===this.config.inlineConsent}buildConsentUIResult(e,t,r,n,i,o,a,s="consent-only",c){if(this.hasUICapability(a),!this.isExtAppsAvailable())return null;const d=this.buildConsentUrl(e,t,r,n,i);return{content:[{type:"text",text:`Authorization required for tool "${e}". Please approve in the consent form below, or open this link to authorize in your browser: ${d}`}],structuredContent:{type:"consent_required",authMode:s,tool:e,scopes:t,agentDid:r?.agentDid||"",agentName:r?.agentName||"",sessionId:r?.id||"",projectId:i||"",resumeToken:n||"",serverUrl:o||"",consentUrl:d,...c?{provider:c}:{}},_meta:{ui:{resourceUri:u.CONSENT_UI_RESOURCE_URI},"ui/resourceUri":u.CONSENT_UI_RESOURCE_URI}}}buildConsentUrl(e,t,r,n,i,o){const a=new URLSearchParams({tool:e,scopes:t.join(","),session_id:r?.id||"",agent_did:r?.agentDid||""}),s=r?.agentName;return s&&a.set("agent_name",s),i&&a.set("project_id",i),n&&a.set("resume_token",n),o&&a.set("provider",o),`https://kya.vouched.id/bouncer/consent?${a.toString()}`}async issueNonce(e){const t=await this.generateNonce(),r=this.sessions.get(e),n=r?.agentDid||(await this.getIdentity()).did;return await this.nonceCache.add(t,300,n),t}async createProof(e,t){const r=await this.getIdentity(),n=this.clock.now();let i;if(t?.nonce)i=t.nonce;else{i=await this.generateNonce();const e=t?.agentDid||r.did;await this.nonceCache.add(i,300,e)}const o={data:e,timestamp:n,nonce:i,did:r.did,sessionId:t?.id,audience:t?.audience},a=await this.signData(o);return{timestamp:n,nonce:i,did:r.did,signature:a,algorithm:"Ed25519",sessionId:t?.id,audience:t?.audience}}async verifyProof(e,t){if(!(e&&"object"==typeof e&&"jws"in e&&"meta"in e))return this.verifyProofLegacy(e,c(t)?t:{});{const r=e,n=c(t)?t:void 0;if(!this.proofVerifier)return console.warn("[MCPIRuntimeBase] ProofVerifier not available, using fallback verification"),this.verifyProofLegacy(e,c(t)?t:{});try{const e=await this.fetch.resolveDID(r.meta.did),t=this.extractPublicKeyJwk(e,r.meta.kid);if(!t)return console.error("[MCPIRuntimeBase] Failed to extract public key JWK"),!1;const i=await this.proofVerifier.verifyProof(r,t);if(i.valid&&n){const e=this.proofVerifier.buildCanonicalPayload(r.meta);n.canonicalPayload=e}return i.valid}catch(e){return console.error("[MCPIRuntimeBase] Proof verification failed:",e),!1}}}async verifyProofLegacy(e,t){try{const r="string"==typeof t.nonce?t.nonce:void 0,n="string"==typeof t.did?t.did:void 0,i="number"==typeof t.timestamp?t.timestamp:void 0,o="string"==typeof t.signature?t.signature:void 0,a="string"==typeof t.sessionId?t.sessionId:void 0;if(!(r&&n&&i&&o))return!1;if(await this.nonceCache.has(r,n))return!1;if(!this.clock.isWithinSkew(i,this.config.session?.timestampSkewSeconds||300))return!1;const s=await this.fetch.resolveDID(n),c=this.extractPublicKey(s),u={data:e,timestamp:i,nonce:r,did:n,sessionId:a},d=(new TextEncoder).encode(JSON.stringify(u)),l=this.base64ToBytes(o),p=await this.crypto.verify(d,l,c);if(p){const e=60*(this.config.session?.ttlMinutes||30);await this.nonceCache.add(r,e,n)}return p}catch(e){return console.error("Proof verification failed:",e),!1}}async verifyProofJWS(e,t,r){if(!this.cryptoService)return console.error("[MCPIRuntimeBase] CryptoService not initialized"),!1;try{const n=void 0!==r?{detachedPayload:r}:void 0;return await this.cryptoService.verifyJWS(e,t,n)}catch(e){return console.error("[MCPIRuntimeBase] JWS verification failed:",e),!1}}async getCurrentSession(){for(const[e,t]of this.sessions)if(!this.clock.hasExpired(t.expiresAt))return t;return null}getLastProof(){return this.lastProof}createWellKnownHandler(e){return async t=>{const r=await this.getIdentity();if("/.well-known/did.json"===t){const e=this.createDIDDocument(r);return{status:200,headers:{"Content-Type":"application/did+json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(e,null,2)}}if("/.well-known/agent.json"===t){const t={id:r.did,capabilities:{"mcp-i":["handshake","signing","verification"]}};return(e?.serviceName||e?.serviceEndpoint)&&(t.metadata={...e?.serviceName&&{name:e.serviceName},...e?.serviceEndpoint&&{serviceEndpoint:e.serviceEndpoint}}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(t,null,2)}}if("/.well-known/mcp-identity"===t)return{did:r.did,publicKey:r.publicKey,serviceName:e?.serviceName||"MCP-I Service",serviceEndpoint:e?.serviceEndpoint||"https://example.com",timestamp:this.clock.now()};if("/.well-known/mcp.json"===t||"/.well-known/mcp/server-card.json"===t){const t=e?.serviceName||"mcp-i-server",n={$schema:"https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json",version:"1.0",protocolVersion:e?.protocolVersion||"2025-06-18",serverInfo:{name:t,title:e?.serviceTitle||e?.serviceName||"MCP-I Server",version:e?.serverVersion||"1.0.0"},description:e?.description||"MCP-I enabled server with cryptographic identity",...e?.iconUrl&&{iconUrl:e.iconUrl},...e?.documentationUrl&&{documentationUrl:e.documentationUrl},transport:{type:"streamable-http",endpoint:"/mcp"},capabilities:{tools:{listChanged:!0}},...e?.requiresAuth&&{authentication:{required:!0,schemes:e.authSchemes||["oauth2"]}},...e?.instructions&&{instructions:e.instructions},tools:"dynamic",_meta:{...e?.metadata,"mcp-i":{agentDid:r.did,publicKey:r.publicKey,generatedAt:this.clock.now()}}};return{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=3600":"no-store","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Content-Type"},body:JSON.stringify(n,null,2)}}if("/.well-known/mcp-client-config.json"===t){const t=e?.serviceEndpoint||"https://example.com",n=e?.serviceName||"mcp-i-server",i=`${t}/mcp`,o={[n]:{url:i,transport:"sse"}},a=Buffer.from(JSON.stringify(o)).toString("base64"),s=`cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(n)}&config=${encodeURIComponent(a)}`,c={claudeDesktop:{mcpServers:{[n]:{url:i,transport:"sse"}}},cursor:{mcpServers:{[n]:{url:i,transport:"sse"}}},cursorDeepLink:s,_meta:{serverName:n,serverUrl:t,mcpEndpoint:i,agentDid:r.did,generatedAt:this.clock.now(),instructions:"Copy the appropriate config section to your client configuration file."}};return{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(c,null,2)}}return null}}createDebugEndpoint(){return"production"===this.config.environment?null:async()=>{const e=await this.getIdentity(),t=await this.getCurrentSession();return{identity:{did:e.did,publicKey:e.publicKey},session:t,config:{environment:this.config.environment,timestampSkewSeconds:this.config.session?.timestampSkewSeconds,sessionTtlMinutes:this.config.session?.ttlMinutes},timestamp:this.clock.now()}}}getAuditLogger(){return{log:(e,t)=>this.logAudit(e,t)}}async rotateKeys(){const e=this.cachedIdentity?.did,t=await this.identity.rotateKeys();return this.cachedIdentity=t,this.config.audit?.enabled&&this.logAudit("keys_rotated",{oldDid:e,newDid:t.did,timestamp:this.clock.now()}),t}async signData(e){const t=await this.getIdentity(),r=(new TextEncoder).encode(JSON.stringify(e)),n=await this.crypto.sign(r,t.privateKey);return this.bytesToBase64(n)}async generateNonce(){const e=await this.crypto.randomBytes(32);return this.bytesToBase64(e)}async generateSessionId(){const e=await this.crypto.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=this.bytesToHex(e);return`mcpi_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}logAudit(e,t){if(!this.config.audit?.enabled)return;const r={event:e,data:this.config.audit.includePayloads?t:void 0,timestamp:this.clock.now(),timestampFormatted:this.clock.format(this.clock.now())},n=JSON.stringify(r);this.config.audit.logFunction?this.config.audit.logFunction(n):console.error("[AUDIT]",n)}createDIDDocument(e){return{"@context":["https://www.w3.org/ns/did/v1"],id:e.did,verificationMethod:[{id:`${e.did}#key-1`,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyBase64:e.publicKey}],authentication:[`${e.did}#key-1`],assertionMethod:[`${e.did}#key-1`]}}extractPublicKey(e){const t=c(e)?e.verificationMethod:void 0,r=Array.isArray(t)?t[0]:void 0;if(r?.publicKeyBase64)return String(r.publicKeyBase64);if(r?.publicKeyMultibase)return String(r.publicKeyMultibase);throw new Error("Public key not found in DID document")}extractPublicKeyJwk(e,t){const r=c(e)?e.verificationMethod:void 0,n=Array.isArray(r)?r:[],i=n.find(e=>{const r="string"==typeof e.type?e.type:void 0,n="string"==typeof e.id?e.id:void 0,i="Ed25519VerificationKey2020"===r||"JsonWebKey2020"===r,o=!t||n===t||n?.endsWith(`#${t}`);return i&&o})||n[0];if(i&&c(i.publicKeyJwk)){const e=i.publicKeyJwk;if("OKP"===e.kty&&"Ed25519"===e.crv)return e}return i?.publicKeyMultibase?(console.warn("[MCPIRuntimeBase] Multibase to JWK conversion not fully implemented"),null):null}bytesToBase64(e){return Buffer.from(e).toString("base64")}base64ToBytes(e){return new Uint8Array(Buffer.from(e,"base64"))}bytesToHex(e){return Buffer.from(e).toString("hex")}}t.MCPIRuntimeBase=u},23192:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractCanonicalData=t.createProofResponse=t.ProofGenerator=void 0;var n=r(56853);Object.defineProperty(t,"ProofGenerator",{enumerable:!0,get:function(){return n.ProofGenerator}}),Object.defineProperty(t,"createProofResponse",{enumerable:!0,get:function(){return n.createProofResponse}}),Object.defineProperty(t,"extractCanonicalData",{enumerable:!0,get:function(){return n.extractCanonicalData}})},23252:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(36023),i=r(24954),o=r(67218),a=r(88401),s={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:s,data:c,it:u}=e;"all"===u.opts.removeAdditional&&void 0===s.additionalProperties&&a.default.code(new n.KeywordCxt(u,a.default,"additionalProperties"));const d=(0,i.allSchemaProperties)(r);for(const e of d)u.definedProperties.add(e);u.opts.unevaluated&&d.length&&!0!==u.props&&(u.props=o.mergeEvaluated.props(t,(0,o.toHash)(d),u.props));const l=d.filter(e=>!(0,o.alwaysValidSchema)(u,r[e]));if(0===l.length)return;const p=t.name("valid");for(const r of l)f(r)?h(r):(t.if((0,i.propertyInData)(t,c,r,u.opts.ownProperties)),h(r),u.allErrors||t.else().var(p,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(p);function f(e){return u.opts.useDefaults&&!u.compositeRule&&void 0!==r[e].default}function h(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},p)}}};t.default=s},23665:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const n=r(38994),i=r(67218),o=r(24954),a={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return s(e,"additionalItems",t);r.items=!0,(0,i.alwaysValidSchema)(r,t)||e.ok((0,o.validateArray)(e))}};function s(e,t,r=e.schema){const{gen:o,parentSchema:a,data:s,keyword:c,it:u}=e;!function(e){const{opts:n,errSchemaPath:o}=u,a=r.length,s=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(n.strictTuples&&!s){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${t} are not specified or different at path "${o}"`;(0,i.checkStrictMode)(u,e,n.strictTuples)}}(a),u.opts.unevaluated&&r.length&&!0!==u.items&&(u.items=i.mergeEvaluated.items(o,r.length,u.items));const d=o.name("valid"),l=o.const("len",n._`${s}.length`);r.forEach((t,r)=>{(0,i.alwaysValidSchema)(u,t)||(o.if(n._`${l} > ${r}`,()=>e.subschema({keyword:c,schemaProp:r,dataProp:r},d)),e.ok(d))})}t.validateTuple=s,t.default=a},23967:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=23967,e.exports=t},24726:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=e=>Math.floor(e.getTime()/1e3)},24886:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CascadingRevocationManager=void 0,t.createCascadingRevocationManager=function(e,t){return new r(e,t)};class r{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,n=[],i=await this.graph.getNode(e);if(!i)throw new Error(`Delegation not found: ${e}`);const o=await this.graph.getDepth(e);if(o>r)throw new Error(`Delegation depth ${o} exceeds maximum ${r}`);const a=await this.revokeNode(i,!0,t.reason,t.dryRun);n.push(a),t.onRevoke&&await t.onRevoke(a);const s=await this.graph.getDescendants(e);for(const r of s){const i=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);n.push(i),t.onRevoke&&await t.onRevoke(i)}return n}async revokeNode(e,t,r,n,i){const o={delegationId:e.id,isRoot:t,parentId:i,timestamp:Date.now(),reason:r};if(n)return o;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return o}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t.reverse())if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,n]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(n,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}t.CascadingRevocationManager=r},24954:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const n=r(38994),i=r(67218),o=r(86660),a=r(67218);function s(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:n._`Object.prototype.hasOwnProperty`})}function c(e,t,r){return n._`${s(e)}.call(${t}, ${r})`}function u(e,t,r,i){const o=n._`${t}${(0,n.getProperty)(r)} === undefined`;return i?(0,n.or)(o,(0,n.not)(c(e,t,r))):o}function d(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:r,data:i,it:o}=e;r.if(u(r,i,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:n._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:r}},i,o){return(0,n.or)(...i.map(i=>(0,n.and)(u(e,t,i,r.ownProperties),n._`${o} = ${i}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=s,t.isOwnProperty=c,t.propertyInData=function(e,t,r,i){const o=n._`${t}${(0,n.getProperty)(r)} !== undefined`;return i?n._`${o} && ${c(e,t,r)}`:o},t.noPropertyInData=u,t.allSchemaProperties=d,t.schemaProperties=function(e,t){return d(t).filter(r=>!(0,i.alwaysValidSchema)(e,t[r]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:a,errorPath:s},it:c},u,d,l){const p=l?n._`${e}, ${t}, ${i}${a}`:t,f=[[o.default.instancePath,(0,n.strConcat)(o.default.instancePath,s)],[o.default.parentData,c.parentData],[o.default.parentDataProperty,c.parentDataProperty],[o.default.rootData,o.default.rootData]];c.opts.dynamicRef&&f.push([o.default.dynamicAnchors,o.default.dynamicAnchors]);const h=n._`${p}, ${r.object(...f)}`;return d!==n.nil?n._`${u}.call(${d}, ${h})`:n._`${u}(${h})`};const l=n._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},r){const i=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:n._`${"new RegExp"===o.code?l:(0,a.useFunc)(e,o)}(${r}, ${i})`})},t.validateArray=function(e){const{gen:t,data:r,keyword:o,it:a}=e,s=t.name("valid");if(a.allErrors){const e=t.let("valid",!0);return c(()=>t.assign(e,!1)),e}return t.var(s,!0),c(()=>t.break()),s;function c(a){const c=t.const("len",n._`${r}.length`);t.forRange("i",0,c,r=>{e.subschema({keyword:o,dataProp:r,dataPropType:i.Type.Num},s),t.if((0,n.not)(s),a)})}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:o,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(e=>(0,i.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((r,i)=>{const a=e.subschema({keyword:o,schemaProp:i,compositeRule:!0},c);t.assign(s,n._`${s} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,n.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}},25532:(e,t)=>{"use strict";function r(e){const t=e.length;let r,n=0,i=0;for(;i<t;)n++,r=e.charCodeAt(i++),r>=55296&&r<=56319&&i<t&&(r=e.charCodeAt(i),56320==(64512&r)&&i++);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'},26419:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const n=r(6247),i=r(238),o=r(28425),a=r(38994),s=r(67218);var c;function u(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(n.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(c||(t.DataType=c={})),t.getSchemaTypes=function(e){const t=u(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=u,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:n,opts:o}=e,s=function(e,t){return t?e.filter(e=>d.has(e)||"array"===t&&"array"===e):[]}(t,o.coerceTypes),u=t.length>0&&!(0===s.length&&1===t.length&&(0,i.schemaHasRulesForType)(e,t[0]));if(u){const i=p(t,n,o.strictNumbers,c.Wrong);r.if(i,()=>{s.length?function(e,t,r){const{gen:n,data:i,opts:o}=e,s=n.let("dataType",a._`typeof ${i}`),c=n.let("coerced",a._`undefined`);"array"===o.coerceTypes&&n.if(a._`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,a._`${i}[0]`).assign(s,a._`typeof ${i}`).if(p(t,i,o.strictNumbers),()=>n.assign(c,i))),n.if(a._`${c} !== undefined`);for(const e of r)(d.has(e)||"array"===e&&"array"===o.coerceTypes)&&u(e);function u(e){switch(e){case"string":return void n.elseIf(a._`${s} == "number" || ${s} == "boolean"`).assign(c,a._`"" + ${i}`).elseIf(a._`${i} === null`).assign(c,a._`""`);case"number":return void n.elseIf(a._`${s} == "boolean" || ${i} === null
5
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(c,a._`+${i}`);case"integer":return void n.elseIf(a._`${s} === "boolean" || ${i} === null
6
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,a._`+${i}`);case"boolean":return void n.elseIf(a._`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf(a._`${i} === "true" || ${i} === 1`).assign(c,!0);case"null":return n.elseIf(a._`${i} === "" || ${i} === 0 || ${i} === false`),void n.assign(c,null);case"array":n.elseIf(a._`${s} === "string" || ${s} === "number"
7
+ || ${s} === "boolean" || ${i} === null`).assign(c,a._`[${i}]`)}}n.else(),h(e),n.endIf(),n.if(a._`${c} !== undefined`,()=>{n.assign(i,c),function({gen:e,parentData:t,parentDataProperty:r},n){e.if(a._`${t} !== undefined`,()=>e.assign(a._`${t}[${r}]`,n))}(e,c)})}(e,t,s):h(e)})}return u};const d=new Set(["string","number","integer","boolean","null"]);function l(e,t,r,n=c.Correct){const i=n===c.Correct?a.operators.EQ:a.operators.NEQ;let o;switch(e){case"null":return a._`${t} ${i} null`;case"array":o=a._`Array.isArray(${t})`;break;case"object":o=a._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s(a._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return a._`typeof ${t} ${i} ${e}`}return n===c.Correct?o:(0,a.not)(o);function s(e=a.nil){return(0,a.and)(a._`typeof ${t} == "number"`,e,r?a._`isFinite(${t})`:a.nil)}}function p(e,t,r,n){if(1===e.length)return l(e[0],t,r,n);let i;const o=(0,s.toHash)(e);if(o.array&&o.object){const e=a._`typeof ${t} != "object"`;i=o.null?e:a._`!${t} || ${e}`,delete o.null,delete o.array,delete o.object}else i=a.nil;o.number&&delete o.integer;for(const e in o)i=(0,a.and)(i,l(e,t,r,n));return i}t.checkDataType=l,t.checkDataTypes=p;const f={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function h(e){const t=function(e){const{gen:t,data:r,schema:n}=e,i=(0,s.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}(e);(0,o.reportError)(t,f)}t.reportTypeError=h},27087:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.CryptoProvider=class{},t.ClockProvider=class{},t.FetchProvider=class{},t.StorageProvider=class{},t.NonceCacheProvider=class{},t.IdentityProvider=class{}},27399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthRequiredError=void 0;class r extends Error{toolName;requiredScopes;provider;oauthUrl;resumeToken;userDid;sessionId;authType;constructor(e){const{toolName:t,requiredScopes:r,provider:n,oauthUrl:i}=e;super(`OAuth required for tool "${t}" with provider "${n}". Required scopes: ${r.join(", ")}`),this.name="OAuthRequiredError",this.toolName=t,this.requiredScopes=r,this.provider=n,this.oauthUrl=i,this.resumeToken=e.resumeToken,this.userDid=e.userDid,this.sessionId=e.sessionId,this.authType=e.authType}}t.OAuthRequiredError=r},27464:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598),i=r(3508),o=r(39069),a=r(99135),s=r(29994),c=r(71759),u=r(58242);t.default=e=>{let t;if((0,a.isCryptoKey)(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=n.KeyObject.from(e)}else{if(!(0,s.default)(e)){if(e instanceof Uint8Array)return{kty:"oct",k:(0,i.encode)(e)};throw new TypeError((0,c.default)(e,...u.types,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new o.JOSENotSupported("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})}},28261:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends r{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class i extends r{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function o(e,...t){const r=[e[0]];let n=0;for(;n<t.length;)c(r,t[n]),r.push(e[++n]);return new i(r)}t._Code=i,t.nil=new i(""),t._=o;const a=new i("+");function s(e,...t){const r=[d(e[0])];let n=0;for(;n<t.length;)r.push(a),c(r,t[n]),r.push(a,d(e[++n]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const r=u(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new i(r)}function c(e,t){var r;t instanceof i?e.push(...t._items):t instanceof n?e.push(t):e.push("number"==typeof(r=t)||"boolean"==typeof r||null===r?r:d(Array.isArray(r)?r.join(","):r))}function u(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function d(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=s,t.addCodeArg=c,t.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:s`${e}${t}`},t.stringify=function(e){return new i(d(e))},t.safeStringify=d,t.getProperty=function(e){return"string"==typeof e&&t.IDENTIFIER.test(e)?new i(`.${e}`):o`[${e}]`},t.getEsmExportName=function(e){if("string"==typeof e&&t.IDENTIFIER.test(e))return new i(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},t.regexpCode=function(e){return new i(e.toString())}},28425:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const n=r(38994),i=r(67218),o=r(86660);function a(e,t){const r=e.const("err",t);e.if(n._`${o.default.vErrors} === null`,()=>e.assign(o.default.vErrors,n._`[${r}]`),n._`${o.default.vErrors}.push(${r})`),e.code(n._`${o.default.errors}++`)}function s(e,t){const{gen:r,validateName:i,schemaEnv:o}=e;o.$async?r.throw(n._`new ${e.ValidationError}(${t})`):(r.assign(n._`${i}.errors`,t),r.return(!1))}t.keywordError={message:({keyword:e})=>n.str`must pass "${e}" keyword validation`},t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?n.str`"${e}" keyword must be ${t} ($data)`:n.str`"${e}" keyword is invalid ($data)`},t.reportError=function(e,r=t.keywordError,i,o){const{it:c}=e,{gen:d,compositeRule:l,allErrors:p}=c,f=u(e,r,i);(null!=o?o:l||p)?a(d,f):s(c,n._`[${f}]`)},t.reportExtraError=function(e,r=t.keywordError,n){const{it:i}=e,{gen:c,compositeRule:d,allErrors:l}=i;a(c,u(e,r,n)),d||l||s(i,o.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(o.default.errors,t),e.if(n._`${o.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(n._`${o.default.vErrors}.length`,t),()=>e.assign(o.default.vErrors,null)))},t.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:i,errsCount:a,it:s}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,o.default.errors,a=>{e.const(c,n._`${o.default.vErrors}[${a}]`),e.if(n._`${c}.instancePath === undefined`,()=>e.assign(n._`${c}.instancePath`,(0,n.strConcat)(o.default.instancePath,s.errorPath))),e.assign(n._`${c}.schemaPath`,n.str`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign(n._`${c}.schema`,r),e.assign(n._`${c}.data`,i))})};const c={keyword:new n.Name("keyword"),schemaPath:new n.Name("schemaPath"),params:new n.Name("params"),propertyName:new n.Name("propertyName"),message:new n.Name("message"),schema:new n.Name("schema"),parentSchema:new n.Name("parentSchema")};function u(e,t,r){const{createErrors:i}=e.it;return!1===i?n._`{}`:function(e,t,r={}){const{gen:i,it:a}=e,s=[d(a,r),l(e,r)];return function(e,{params:t,message:r},i){const{keyword:a,data:s,schemaValue:u,it:d}=e,{opts:l,propertyName:p,topSchemaRef:f,schemaPath:h}=d;i.push([c.keyword,a],[c.params,"function"==typeof t?t(e):t||n._`{}`]),l.messages&&i.push([c.message,"function"==typeof r?r(e):r]),l.verbose&&i.push([c.schema,u],[c.parentSchema,n._`${f}${h}`],[o.default.data,s]),p&&i.push([c.propertyName,p])}(e,t,s),i.object(...s)}(e,t,r)}function d({errorPath:e},{instancePath:t}){const r=t?n.str`${e}${(0,i.getErrorPath)(t,i.Type.Str)}`:e;return[o.default.instancePath,(0,n.strConcat)(o.default.instancePath,r)]}function l({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:o}){let a=o?t:n.str`${t}/${e}`;return r&&(a=n.str`${a}${(0,i.getErrorPath)(r,i.Type.Str)}`),[c.schemaPath,a]}},28717:e=>{"use strict";e.exports=require("@kya-os/contracts/proof")},28825:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=r(51967),i=r(83959),o=r(29376),a=r(7456),s=["/properties"],c="http://json-schema.org/draft-07/schema";class u extends n.default{_addVocabularies(){super._addVocabularies(),i.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(a,s):a;this.addMetaSchema(e,c,!1),this.refs["http://json-schema.org/schema"]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}}t.Ajv=u,e.exports=t=u,e.exports.Ajv=u,Object.defineProperty(t,"__esModule",{value:!0}),t.default=u;var d=r(36023);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return d.KeywordCxt}});var l=r(38994);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var p=r(74383);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return p.default}});var f=r(4220);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return f.default}})},29376:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(15141),o=r(91688),a=r(4220),s=r(67218),c={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===i.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>n._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:c,parentSchema:u,it:d}=e,{oneOf:l}=u;if(!d.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const f=t.let("valid",!1),h=t.const("tag",n._`${r}${(0,n.getProperty)(p)}`);function m(r){const i=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:r},i);return e.mergeEvaluated(o,n.Name),i}t.if(n._`typeof ${h} == "string"`,()=>function(){const r=function(){var e;const t={},r=i(u);let n=!0;for(let t=0;t<l.length;t++){let u=l[t];if((null==u?void 0:u.$ref)&&!(0,s.schemaHasRulesButRef)(u,d.self.RULES)){const e=u.$ref;if(u=o.resolveRef.call(d.self,d.schemaEnv.root,d.baseId,e),u instanceof o.SchemaEnv&&(u=u.schema),void 0===u)throw new a.default(d.opts.uriResolver,d.baseId,e)}const f=null===(e=null==u?void 0:u.properties)||void 0===e?void 0:e[p];if("object"!=typeof f)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);n=n&&(r||i(u)),c(f,t)}if(!n)throw new Error(`discriminator: "${p}" must be required`);return t;function i({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)f(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const r of e.enum)f(r,t)}}function f(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(n._`${h} === ${e}`),t.assign(f,m(r[e]));t.else(),e.error(!1,{discrError:i.DiscrError.Mapping,tag:h,tagName:p}),t.endIf()}(),()=>e.error(!1,{discrError:i.DiscrError.Tag,tag:h,tagName:p})),e.ok(f)}};t.default=c},29820:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const n=r(38994),i=r(86660),o=r(24954),a=r(28425);function s(e){const{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,n._`${i.parentData}[${i.parentDataProperty}]`))}function c(e,t,r){if(void 0===r)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,n.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:i,schema:o,parentSchema:a,it:s}=e,u=t.macro.call(s.self,o,a,s),d=c(r,i,u);!1!==s.opts.validateSchema&&s.self.validateSchema(u,!0);const l=r.name("valid");e.subschema({schema:u,schemaPath:n.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:d,compositeRule:!0},l),e.pass(l,()=>e.error(!0))},t.funcKeywordCode=function(e,t){var r;const{gen:u,keyword:d,schema:l,parentSchema:p,$data:f,it:h}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(h,t);const m=!f&&t.compile?t.compile.call(h.self,l,p,h):t.validate,g=c(u,d,m),v=u.let("valid");function y(r=(t.async?n._`await `:n.nil)){const a=h.opts.passContext?i.default.this:i.default.self,s=!("compile"in t&&!f||!1===t.schema);u.assign(v,n._`${r}${(0,o.callValidateCode)(e,g,a,s)}`,t.modifying)}function _(e){var r;u.if((0,n.not)(null!==(r=t.valid)&&void 0!==r?r:v),e)}e.block$data(v,function(){if(!1===t.errors)y(),t.modifying&&s(e),_(()=>e.error());else{const r=t.async?function(){const e=u.let("ruleErrs",null);return u.try(()=>y(n._`await `),t=>u.assign(v,!1).if(n._`${t} instanceof ${h.ValidationError}`,()=>u.assign(e,n._`${t}.errors`),()=>u.throw(t))),e}():function(){const e=n._`${g}.errors`;return u.assign(e,null),y(n.nil),e}();t.modifying&&s(e),_(()=>function(e,t){const{gen:r}=e;r.if(n._`Array.isArray(${t})`,()=>{r.assign(i.default.vErrors,n._`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`).assign(i.default.errors,n._`${i.default.vErrors}.length`),(0,a.extendErrors)(e)},()=>e.error())}(e,r))}}),e.ok(null!==(r=t.valid)&&void 0!==r?r:v)},t.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},t.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");const a=i.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){const e=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},29994:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(57975);t.default=e=>n.types.isKeyObject(e)},30005:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CompactEncrypt=void 0;const n=r(92599);t.CompactEncrypt=class{_flattened;constructor(e){this._flattened=new n.FlattenedEncrypt(e)}setContentEncryptionKey(e){return this._flattened.setContentEncryptionKey(e),this}setInitializationVector(e){return this._flattened.setInitializationVector(e),this}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}setKeyManagementParameters(e){return this._flattened.setKeyManagementParameters(e),this}async encrypt(e,t){const r=await this._flattened.encrypt(e,t);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}},30124:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BatchDelegationService=void 0,t.BatchDelegationService=class{providerResolver;toolProtectionService;constructor(e,t){this.providerResolver=e,this.toolProtectionService=t}async groupToolsByProvider(e,t,r){const n=new Map;for(const i of e){const e=await this.toolProtectionService.checkToolProtection(i,r);if(!e?.requiresDelegation)continue;let o;try{o=await this.providerResolver.resolveProvider(e,t)}catch(e){console.warn(`[BatchDelegation] Could not resolve provider for tool "${i}", skipping`,e instanceof Error?e.message:String(e));continue}n.has(o)||n.set(o,{provider:o,tools:[],scopes:[],riskLevel:"medium"});const a=n.get(o);a.tools.push(i);const s=new Set([...a.scopes,...e.requiredScopes||[]]);if(a.scopes=Array.from(s),e.riskLevel){const t={low:1,medium:2,high:3,critical:4},r=t[a.riskLevel]||1;(t[e.riskLevel]||1)>r&&(a.riskLevel="critical"===e.riskLevel?"high":e.riskLevel)}}return n}async getToolsForProvider(e,t,r){return[]}}},30131:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FlattenedSign=void 0;const n=r(3508),i=r(80903),o=r(91146),a=r(39069),s=r(45935),c=r(89666),u=r(82880);t.FlattenedSign=class{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new a.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,o.default)(this._protectedHeader,this._unprotectedHeader))throw new a.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let d=!0;if((0,u.default)(a.JWSInvalid,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(d=this._protectedHeader.b64,"boolean"!=typeof d))throw new a.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=r;if("string"!=typeof l||!l)throw new a.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,c.checkKeyTypeWithJwk)(l,e,"sign");let p,f=this._payload;d&&(f=s.encoder.encode((0,n.encode)(f))),p=this._protectedHeader?s.encoder.encode((0,n.encode)(JSON.stringify(this._protectedHeader))):s.encoder.encode("");const h=(0,s.concat)(p,s.encoder.encode("."),f),m=await(0,i.default)(l,e,h),g={signature:(0,n.encode)(m),payload:""};return d&&(g.payload=s.decoder.decode(f)),this._unprotectedHeader&&(g.header=this._unprotectedHeader),this._protectedHeader&&(g.protected=s.decoder.decode(p)),g}}},30659:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(68997),i=r(89190),o=r(94280),a=r(78805),s=r(12189),c=r(33138),u=r(48870),d=r(11858),l=r(17080),p=r(65358),f=[n.default,i.default,o.default,a.default,s.default,c.default,u.default,d.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,p.default];t.default=f},30714:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const n=r(38994),i=r(67218),o={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>n.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>n._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?a(e,n):(0,i.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function a(e,t){const{gen:r,schema:o,data:a,keyword:s,it:c}=e;c.items=!0;const u=r.const("len",n._`${a}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(n._`${u} <= ${t.length}`);else if("object"==typeof o&&!(0,i.alwaysValidSchema)(c,o)){const o=r.var("valid",n._`${u} <= ${t.length}`);r.if((0,n.not)(o),()=>function(o){r.forRange("i",t.length,u,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:i.Type.Num},o),c.allErrors||r.if((0,n.not)(o),()=>r.break())})}(o)),e.ok(o)}}t.validateAdditionalItems=a,t.default=o},30845:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialIssuer=void 0,t.createDelegationIssuer=function(e,t){return new o(e,t)};const n=r(62408),i=r(63969);class o{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=(0,n.wrapDelegationAsVC)(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const i=this.canonicalizeVC(r),o=await this.signingFunction(i,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:o}}async createAndIssueDelegation(e,t={}){const r=Date.now(),n={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(n,t)}canonicalizeVC(e){return(0,i.canonicalizeJSON)(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}t.DelegationCredentialIssuer=o},30930:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const n=r(4220),i=r(24954),o=r(38994),a=r(86660),s=r(91688),c=r(67218),u={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:i}=e,{baseId:a,schemaEnv:c,validateName:u,opts:p,self:f}=i,{root:h}=c;if(("#"===r||"#/"===r)&&a===h.baseId)return function(){if(c===h)return l(e,u,c,c.$async);const r=t.scopeValue("root",{ref:h});return l(e,o._`${r}.validate`,h,h.$async)}();const m=s.resolveRef.call(f,h,a,r);if(void 0===m)throw new n.default(i.opts.uriResolver,a,r);return m instanceof s.SchemaEnv?function(t){const r=d(e,t);l(e,r,t,t.$async)}(m):function(n){const i=t.scopeValue("schema",!0===p.code.source?{ref:n,code:(0,o.stringify)(n)}:{ref:n}),a=t.name("valid"),s=e.subschema({schema:n,dataTypes:[],schemaPath:o.nil,topSchemaRef:i,errSchemaPath:r},a);e.mergeEvaluated(s),e.ok(a)}(m)}};function d(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):o._`${r.scopeValue("wrapper",{ref:t})}.validate`}function l(e,t,r,n){const{gen:s,it:u}=e,{allErrors:d,schemaEnv:l,opts:p}=u,f=p.passContext?a.default.this:o.nil;function h(e){const t=o._`${e}.errors`;s.assign(a.default.vErrors,o._`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`),s.assign(a.default.errors,o._`${a.default.vErrors}.length`)}function m(e){var t;if(!u.opts.unevaluated)return;const n=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==u.props)if(n&&!n.dynamicProps)void 0!==n.props&&(u.props=c.mergeEvaluated.props(s,n.props,u.props));else{const t=s.var("props",o._`${e}.evaluated.props`);u.props=c.mergeEvaluated.props(s,t,u.props,o.Name)}if(!0!==u.items)if(n&&!n.dynamicItems)void 0!==n.items&&(u.items=c.mergeEvaluated.items(s,n.items,u.items));else{const t=s.var("items",o._`${e}.evaluated.items`);u.items=c.mergeEvaluated.items(s,t,u.items,o.Name)}}n?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const r=s.let("valid");s.try(()=>{s.code(o._`await ${(0,i.callValidateCode)(e,t,f)}`),m(t),d||s.assign(r,!0)},e=>{s.if(o._`!(${e} instanceof ${u.ValidationError})`,()=>s.throw(e)),h(e),d||s.assign(r,!1)}),e.ok(r)}():e.result((0,i.callValidateCode)(e,t,f),()=>m(t),()=>h(t))}t.getValidate=d,t.callRef=l,t.default=u},31276:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EncryptJWT=void 0;const n=r(30005),i=r(45935),o=r(59333);class a extends o.ProduceJWT{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(e,t){const r=new n.CompactEncrypt(i.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),r.setProtectedHeader(this._protectedHeader),this._iv&&r.setInitializationVector(this._iv),this._cek&&r.setContentEncryptionKey(this._cek),this._keyManagementParameters&&r.setKeyManagementParameters(this._keyManagementParameters),r.encrypt(e,t)}}t.EncryptJWT=a},31961:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionManager=void 0,t.createHandshakeRequest=function(e){return{nonce:o.generateNonce(),audience:e,timestamp:Math.floor(Date.now()/1e3)}},t.validateHandshakeFormat=function(e){return"object"==typeof e&&null!==e&&"string"==typeof e.nonce&&e.nonce.length>0&&"string"==typeof e.audience&&e.audience.length>0&&"number"==typeof e.timestamp&&e.timestamp>0&&Number.isInteger(e.timestamp)};const n=r(48505),i=r(46171);class o{config;cryptoProvider;sessions=new Map;constructor(e,t={}){this.cryptoProvider=e,this.config={timestampSkewSeconds:t.timestampSkewSeconds??120,sessionTtlMinutes:t.sessionTtlMinutes??30,nonceCache:t.nonceCache??new n.MemoryNonceCacheProvider,...void 0!==t.absoluteSessionLifetime&&{absoluteSessionLifetime:t.absoluteSessionLifetime},...void 0!==t.serverDid&&{serverDid:t.serverDid}},this.config.nonceCache instanceof n.MemoryNonceCacheProvider&&i.logger.warn("[SessionManager] Using MemoryNonceCacheProvider — not suitable for multi-instance deployments. Use Redis, DynamoDB, or Cloudflare KV for production.")}setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust timestampSkewSeconds if needed.`}};if(await this.config.nonceCache.has(e.nonce,e.agentDid))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const n=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,n,e.agentDid);const i=await this.generateSessionId(),o=await this.buildClientInfo(e),a={sessionId:i,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,identityState:"anonymous",agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid},...o&&{clientInfo:o}};return this.sessions.set(i,a),{success:!0,session:a}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||void 0!==this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}async generateSessionId(){const e=await this.cryptoProvider.randomBytes(16);e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return`mcpi_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async generateClientId(){const e=await this.cryptoProvider.randomBytes(6);return`client_${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}normalizeClientInfoString(e){if("string"!=typeof e)return;const t=e.trim();return t.length>0?t:void 0}async buildClientInfo(e){if(!e.clientInfo&&"string"!=typeof e.clientProtocolVersion&&void 0===e.clientCapabilities)return;const t=e.clientInfo;return{name:this.normalizeClientInfoString(t?.name)??"unknown",title:this.normalizeClientInfoString(t?.title),version:this.normalizeClientInfoString(t?.version),platform:this.normalizeClientInfoString(t?.platform),vendor:this.normalizeClientInfoString(t?.vendor),persistentId:this.normalizeClientInfoString(t?.persistentId),clientId:this.normalizeClientInfoString(t?.clientId)??await this.generateClientId(),protocolVersion:this.normalizeClientInfoString(e.clientProtocolVersion),capabilities:e.clientCapabilities}}static generateNonce(){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let n=e-r.lastActivity>60*r.ttlMinutes;n||void 0===this.config.absoluteSessionLifetime||(n=e-r.createdAt>60*this.config.absoluteSessionLifetime),n&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}}t.SessionManager=o},32139:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={}},32299:(e,t)=>{"use strict";function r(e){return`agent:${e}:delegation`}function n(e,t,r){return r?`delegation:user:${e}:agent:${t}:project:${r}`:`delegation:user:${e}:agent:${t}`}function i(e){return`session:${e}`}function o(e,t){return`userDid:oauth:${e}:${t}`}function a(e,t){return`oauth:${e}:${t}`}function s(e){return`verified:${e}`}function c(e){return`nonce:${e}`}Object.defineProperty(t,"__esModule",{value:!0}),t.STORAGE_KEYS=void 0,t.legacyDelegationKey=r,t.compositeDelegationKey=n,t.sessionKey=i,t.userDidKey=o,t.oauthIdentityKey=a,t.verificationCacheKey=s,t.nonceKey=c,t.migrateDelegationKeys=async function(e,t={}){const r={migrated:0,failed:0,migrations:[],errors:[]};try{const i=(await e.list("agent:")).filter(e=>e.match(/^agent:[^:]+:delegation$/));console.error(`Found ${i.length} legacy delegation keys to migrate`);for(const o of i)try{const i=o.match(/^agent:([^:]+):delegation$/);if(!i){r.errors.push({key:o,error:"Invalid legacy key format"}),r.failed++;continue}const a=i[1],s=await e.get(o);if(!s)continue;let c,u=null;const d=await e.list("session:");for(const t of d){const r=await e.get(t);if(r)try{const e=JSON.parse(r);if(e.userDid&&e.agentDid===a){u=e.userDid;const r=t.match(/^session:(.+)$/);r&&(c=r[1]);break}}catch{}}if(t.resolveUserDid){const e=await t.resolveUserDid(a,c);e&&(u=e)}if(!u){r.errors.push({key:o,error:"Cannot resolve userDid - skipping migration"}),r.failed++;continue}const l=n(u,a);t.dryRun?(r.migrations.push({oldKey:o,newKey:l}),r.migrated++):(await e.set(l,s),r.migrations.push({oldKey:o,newKey:l}),r.migrated++,t.deleteOldKeys&&await e.delete(o))}catch(e){r.errors.push({key:o,error:e instanceof Error?e.message:String(e)}),r.failed++}}catch(e){r.errors.push({key:"migration",error:e instanceof Error?e.message:String(e)})}return r},t.STORAGE_KEYS={userDid:o,oauthIdentity:a,delegation:n,session:i,legacyDelegation:r,verificationCache:s,nonce:c}},32692:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?n.str`must contain at least ${e} valid item(s)`:n.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?n._`{minContains: ${e}}`:n._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:a,it:s}=e;let c,u;const{minContains:d,maxContains:l}=o;s.opts.next?(c=void 0===d?1:d,u=l):c=1;const p=t.const("len",n._`${a}.length`);if(e.setParams({min:c,max:u}),void 0===u&&0===c)return void(0,i.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==u&&c>u)return(0,i.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,i.alwaysValidSchema)(s,r)){let t=n._`${p} >= ${c}`;return void 0!==u&&(t=n._`${t} && ${p} <= ${u}`),void e.pass(t)}s.items=!0;const f=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);m(e,()=>t.if(e,()=>function(e){t.code(n._`${e}++`),void 0===u?t.if(n._`${e} >= ${c}`,()=>t.assign(f,!0).break()):(t.if(n._`${e} > ${u}`,()=>t.assign(f,!1).break()),1===c?t.assign(f,!0):t.if(n._`${e} >= ${c}`,()=>t.assign(f,!0)))}(r)))}function m(r,n){t.forRange("i",0,p,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:i.Type.Num,compositeRule:!0},r),n()})}void 0===u&&1===c?m(f,()=>t.if(f,()=>t.break())):0===c?(t.let(f,!0),void 0!==u&&t.if(n._`${a}.length > 0`,h)):(t.let(f,!1),h()),e.result(f,()=>e.reset())}};t.default=o},33138:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(24954),i=r(38994),o=r(67218),a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>i.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>i._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:a,data:s,$data:c,it:u}=e,{opts:d}=u;if(!c&&0===r.length)return;const l=r.length>=d.loopRequired;if(u.allErrors?function(){if(l||c)e.block$data(i.nil,p);else for(const t of r)(0,n.checkReportMissingProp)(e,t)}():function(){const o=t.let("missing");if(l||c){const r=t.let("valid",!0);e.block$data(r,()=>function(r,o){e.setParams({missingProperty:r}),t.forOf(r,a,()=>{t.assign(o,(0,n.propertyInData)(t,s,r,d.ownProperties)),t.if((0,i.not)(o),()=>{e.error(),t.break()})},i.nil)}(o,r)),e.ok(r)}else t.if((0,n.checkMissingProp)(e,r,o)),(0,n.reportMissingProp)(e,o),t.else()}(),d.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!n.has(e)){const t=`required property "${e}" is not defined at "${u.schemaEnv.baseId+u.errSchemaPath}" (strictRequired)`;(0,o.checkStrictMode)(u,t,u.opts.strictRequired)}}function p(){t.forOf("prop",a,r=>{e.setParams({missingProperty:r}),t.if((0,n.noPropertyInData)(t,s,r,d.ownProperties),()=>e.error())})}}};t.default=a},33330:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},33346:(e,t,r)=>{"use strict";function n(e){return e}function i(e){return e}function o(e){}function a(e){throw new Error}function s(e){}function c(e){const 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 u(e,t="|"){return e.map(e=>j(e)).join(t)}function d(e,t){return"bigint"==typeof t?t.toString():t}function l(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function p(e){return null==e}function f(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function h(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}function m(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function g(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function v(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function y(e){const t=Object.keys(e),r=t.map(t=>e[t]);return Promise.all(r).then(e=>{const r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})}function _(e=10){let t="";for(let r=0;r<e;r++)t+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return t}function b(e){return JSON.stringify(e)}r.r(t),r.d(t,{BIGINT_FORMAT_RANGES:()=>z,Class:()=>X,NUMBER_FORMAT_RANGES:()=>N,aborted:()=>L,allowsEval:()=>S,assert:()=>s,assertEqual:()=>n,assertIs:()=>o,assertNever:()=>a,assertNotEqual:()=>i,assignProp:()=>g,cached:()=>l,captureStackTrace:()=>w,cleanEnum:()=>G,cleanRegex:()=>f,clone:()=>T,createTransparentProxy:()=>A,defineLazy:()=>m,esc:()=>b,escapeRegex:()=>O,extend:()=>M,finalizeIssue:()=>H,floatSafeRemainder:()=>h,getElementAtPath:()=>v,getEnumValues:()=>c,getLengthableOrigin:()=>q,getParsedType:()=>P,getSizableOrigin:()=>V,isObject:()=>$,isPlainObject:()=>k,issue:()=>B,joinValues:()=>u,jsonStringifyReplacer:()=>d,merge:()=>K,normalizeParams:()=>C,nullish:()=>p,numKeys:()=>I,omit:()=>U,optionalKeys:()=>D,partial:()=>J,pick:()=>R,prefixIssues:()=>W,primitiveTypes:()=>x,promiseAllObject:()=>y,propertyKeyTypes:()=>E,randomString:()=>_,required:()=>Z,stringifyPrimitive:()=>j,unwrapMessage:()=>F});const w=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function $(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const S=l(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function k(e){if(!1===$(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==$(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function I(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}const P=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},E=new Set(["string","number","symbol"]),x=new Set(["string","number","bigint","boolean","symbol","undefined"]);function O(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function C(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function A(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,o)=>(t??(t=e()),Reflect.set(t,n,i,o)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})}function j(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function D(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}const N={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},z={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function R(e,t){const r={},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=n.shape[e])}return T(e,{...e._zod.def,shape:r,checks:[]})}function U(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return T(e,{...e._zod.def,shape:r,checks:[]})}function M(e,t){const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return g(this,"shape",r),r},checks:[]};return T(e,r)}function K(e,t){return T(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return g(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function J(e,t,r){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return T(t,{...t._zod.def,shape:i,checks:[]})}function Z(e,t,r){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return T(t,{...t._zod.def,shape:i,checks:[]})}function L(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r].continue)return!0;return!1}function W(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function F(e){return"string"==typeof e?e:e?.message}function H(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=F(e.inst?._zod.def?.error?.(e))??F(t?.error?.(e))??F(r.customError?.(e))??F(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function V(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function q(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function B(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function G(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}class X{constructor(...e){}}},33645:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateJwkThumbprint=u,t.calculateJwkThumbprintUri=async function(e,t){t??="sha256";const r=await u(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`};const n=r(17306),i=r(3508),o=r(39069),a=r(45935),s=r(71661),c=(e,t)=>{if("string"!=typeof e||!e)throw new o.JWKInvalid(`${t} missing or invalid`)};async function u(e,t){if(!(0,s.default)(e))throw new TypeError("JWK must be an object");if(t??="sha256","sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":c(e.crv,'"crv" (Curve) Parameter'),c(e.x,'"x" (X Coordinate) Parameter'),c(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":c(e.crv,'"crv" (Subtype of Key Pair) Parameter'),c(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":c(e.e,'"e" (Exponent) Parameter'),c(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":c(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new o.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}const u=a.encoder.encode(JSON.stringify(r));return(0,i.encode)(await(0,n.default)(t,u))}},34119:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598),i=r(57975),o=r(17759),a=r(9066),s=r(80903),c=r(47532),u=(0,i.promisify)(n.verify);t.default=async(e,t,r,i)=>{const d=(0,c.default)(e,t,"verify");if(e.startsWith("HS")){const t=await(0,s.default)(e,d,i),o=r;try{return n.timingSafeEqual(o,t)}catch{return!1}}const l=(0,o.default)(e),p=(0,a.default)(e,d);try{return await u(l,i,p,r)}catch{return!1}}},35638:(e,t,r)=>{"use strict";r.d(t,{v$:()=>i,EQ:()=>o}),r(98085);var n=r(83307);function i(e){const t=(0,n.BW)(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const i=(0,n.Lm)(r);if("string"!=typeof i)throw new Error("Schema method literal must be a string");return i}function o(e,t){const r=(0,n.xL)(e,t);if(!r.success)throw r.error;return r.data}Symbol("Let zodToJsonSchema decide on which parser to use"),r(92540)},36023:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const n=r(40564),i=r(26419),o=r(238),a=r(26419),s=r(76593),c=r(29820),u=r(3826),d=r(38994),l=r(86660),p=r(89008),f=r(67218),h=r(28425);function m({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,d._`${l.default.data}, ${l.default.valCxt}`,n.$async,()=>{e.code(d._`"use strict"; ${g(r,i)}`),function(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,d._`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,d._`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,d._`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,d._`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,d._`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,d._`""`),e.var(l.default.parentData,d._`undefined`),e.var(l.default.parentDataProperty,d._`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,d._`{}`)})}(e,i),e.code(o)}):e.func(t,d._`${l.default.data}, ${function(e){return d._`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?d._`, ${l.default.dynamicAnchors}={}`:d.nil}}={}`}(i)}`,n.$async,()=>e.code(g(r,i)).code(o))}function g(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?d._`/*# sourceURL=${r} */`:d.nil}function v({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function _(e){(0,f.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,f.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function b(e,t){if(e.opts.jtd)return $(e,[],!1,t);const r=(0,i.getSchemaTypes)(e.schema);$(e,r,!(0,i.coerceAndCheckDataType)(e,r),t)}function w({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){const o=r.$comment;if(!0===i.$comment)e.code(d._`${l.default.self}.logger.log(${o})`);else if("function"==typeof i.$comment){const r=d.str`${n}/$comment`,i=e.scopeValue("root",{ref:t.root});e.code(d._`${l.default.self}.opts.$comment(${o}, ${r}, ${i}.schema)`)}}function $(e,t,r,n){const{gen:i,schema:s,data:c,allErrors:u,opts:p,self:h}=e,{RULES:m}=h;function g(f){(0,o.shouldUseGroup)(s,f)&&(f.type?(i.if((0,a.checkDataType)(f.type,c,p.strictNumbers)),S(e,f),1===t.length&&t[0]===f.type&&r&&(i.else(),(0,a.reportTypeError)(e)),i.endIf()):S(e,f),u||i.if(d._`${l.default.errors} === ${n||0}`))}!s.$ref||!p.ignoreKeywordsWithRef&&(0,f.schemaHasRulesButRef)(s,m)?(p.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{k(e.dataTypes,t)||I(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)k(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&I(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const n in r){const i=r[n];if("object"==typeof i&&(0,o.shouldUseRule)(e.schema,i)){const{type:r}=i.definition;r.length&&!r.some(e=>{return n=e,(r=t).includes(n)||"number"===n&&r.includes("integer");var r,n})&&I(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes))}(e,t),i.block(()=>{for(const e of m.rules)g(e);g(m.post)})):i.block(()=>E(e,"$ref",m.all.$ref.definition))}function S(e,t){const{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,s.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,o.shouldUseRule)(n,r)&&E(e,r.keyword,r.definition,t.type)})}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function I(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,f.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){y(e)&&(_(e),v(e))?function(e){const{schema:t,opts:r,gen:n}=e;m(e,()=>{r.$comment&&t.$comment&&w(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,f.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(l.default.vErrors,null),n.let(l.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",d._`${r}.evaluated`),t.if(d._`${e.evaluated}.dynamicProps`,()=>t.assign(d._`${e.evaluated}.props`,d._`undefined`)),t.if(d._`${e.evaluated}.dynamicItems`,()=>t.assign(d._`${e.evaluated}.items`,d._`undefined`))}(e),b(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if(d._`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw(d._`new ${i}(${l.default.vErrors})`)):(t.assign(d._`${n}.errors`,l.default.vErrors),o.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof d.Name&&e.assign(d._`${t}.props`,r),n instanceof d.Name&&e.assign(d._`${t}.items`,n)}(e),t.return(d._`${l.default.errors} === 0`))}(e)})}(e):m(e,()=>(0,n.topBoolOrEmptySchema)(e))};class P{constructor(e,t,r){if((0,c.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,f.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",T(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,c.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",l.default.errors))}result(e,t,r){this.failResult((0,d.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,d.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(d._`${t} !== undefined && (${(0,d.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?h.reportExtraError:h.reportError)(this,this.def.error,t)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=d.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=d.nil,t=d.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:i,def:o}=this;r.if((0,d.or)(d._`${n} === undefined`,t)),e!==d.nil&&r.assign(e,!0),(i.length||o.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==d.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:i}=this;return(0,d.or)(function(){if(r.length){if(!(t instanceof d.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return d._`${(0,a.checkDataTypes)(e,t,i.opts.strictNumbers,a.DataType.Wrong)}`}return d.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return d._`!${r}(${t})`}return d.nil}())}subschema(e,t){const r=(0,u.getSubschema)(this.it,e);(0,u.extendSubschemaData)(r,this.it,e),(0,u.extendSubschemaMode)(r,e);const i={...this.it,...r,items:void 0,props:void 0};return function(e,t){y(e)&&(_(e),v(e))?function(e,t){const{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&w(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,p.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const o=n.const("_errs",l.default.errors);b(e,o),n.var(t,d._`${o} === ${l.default.errors}`)}(e,t):(0,n.boolOrEmptySchema)(e,t)}(i,t),i}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=f.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=f.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,d.Name)),!0}}function E(e,t,r,n){const i=new P(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,c.funcKeywordCode)(i,r):"macro"in r?(0,c.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,c.funcKeywordCode)(i,r)}t.KeywordCxt=P;const x=/^\/(?:[^~]|~0|~1)*$/,O=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function T(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(""===e)return l.default.rootData;if("/"===e[0]){if(!x.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=l.default.rootData}else{const a=O.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const s=+a[1];if(i=a[2],"#"===i){if(s>=t)throw new Error(c("property/index",s));return n[t-s]}if(s>t)throw new Error(c("data",s));if(o=r[t-s],!i)return o}let a=o;const s=i.split("/");for(const e of s)e&&(o=d._`${o}${(0,d.getProperty)((0,f.unescapeJsonPointer)(e))}`,a=d._`${a} && ${o}`);return a;function c(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}t.getData=T},36255:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessControlApiService=void 0,t.authorizationMatches=function(e,t){return!t||(!("credential"!==e.type||"oauth"!==t.type||!e.credentialType||!t.provider||e.credentialType!==t.provider)||e.type===t.type&&("oauth"===e.type?!t.provider||e.provider===t.provider:"verifiable_credential"!==e.type||(!t.credentialType||e.credentialType===t.credentialType)))};const n=r(82906),i=r(82906);function o(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}t.AccessControlApiService=class{config;metrics;constructor(e){const t=e.retryConfig||{};this.config={retryConfig:{maxRetries:t.maxRetries??3,initialDelayMs:t.initialDelayMs??100,maxDelayMs:t.maxDelayMs??5e3},logger:e.logger||(()=>{}),baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,sleepProvider:e.sleepProvider||(e=>new Promise(t=>setTimeout(t,e)))},this.metrics={successCount:0,errorCount:0,retryCount:0}}async fetchConfig(e){return this.retryWithBackoff(async()=>{const t=o(),r=`${this.config.baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e.agentDid)}`;this.config.logger(`[AccessControl] Fetching config for agent: ${e.agentDid}`,{correlationId:t,url:r});const a=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":t}}),s=await a.text(),c=this.parseResponseJSON(a,s);a.ok||this.handleErrorResponse(a,c);const u=n.toolProtectionConfigAPIResponseSchema.safeParse(c);if(!u.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:u.error.errors});return this.config.logger("[AccessControl] Config fetched successfully",{correlationId:t,agentDid:e.agentDid}),u.data})}async verifyDelegation(e,t){return this.retryWithBackoff(async()=>{const r=o(),a=`${this.config.baseUrl}/api/v1/bouncer/delegations/verify`,s={agent_did:e.agent_did};void 0!==e.scopes&&(s.scopes=e.scopes),void 0!==e.user_did&&(s.user_did=e.user_did),void 0!==e.credential_jwt?s.credential_jwt=e.credential_jwt:t?.credentialJwt&&(s.credential_jwt=t.credentialJwt),void 0!==e.delegation_token?s.delegation_token=e.delegation_token:t?.delegationToken&&(s.delegation_token=t.delegationToken),void 0!==e.timestamp&&(s.timestamp=e.timestamp),e.client_info&&(s.client_info=e.client_info);const c=Object.fromEntries(Object.entries(s).filter(([e,t])=>void 0!==t)),u=n.verifyDelegationRequestSchema.safeParse(c);if(!u.success&&(!u.error.errors.find(e=>e.path.includes("scopes")&&"Required"===e.message)||"scopes"in c))throw this.config.logger("[AccessControl] Validation failed:",{errors:u.error.errors,requestBody:s}),new i.AgentShieldAPIError("validation_error","Request validation failed",{zodErrors:u.error.errors});this.config.logger(`[AccessControl] Verifying delegation for agent: ${e.agent_did}`,{correlationId:r,url:a,hasScopes:(e.scopes?.length||0)>0});const d=await this.config.fetchProvider.fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":r},body:JSON.stringify(c)}),l=await d.text(),p=this.parseResponseJSON(d,l);d.ok||this.handleErrorResponse(d,p);const f=n.verifyDelegationAPIResponseSchema.safeParse(p);if(!f.success)throw new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:f.error.errors});return this.config.logger("[AccessControl] Delegation verified",{correlationId:r,agentDid:e.agent_did,valid:f.data.data.valid}),f.data})}async submitProofs(e){return this.retryWithBackoff(async()=>{const t=n.proofSubmissionRequestSchema.safeParse(e);if(!t.success){const r=JSON.stringify(t.error.errors,null,2);throw this.config.logger("[AccessControl] Proof submission validation failed:",{errors:t.error.errors,request:JSON.stringify(e,null,2)}),new i.AgentShieldAPIError("validation_error",`Request validation failed: ${r}`,{zodErrors:t.error.errors})}const r=t.data,a=o(),s=`${this.config.baseUrl}/api/v1/bouncer/proofs`;this.config.logger(`[AccessControl] Submitting ${e.proofs.length} proof(s)`,{correlationId:a,url:s,sessionId:e.session_id,delegationId:e.delegation_id});const c=await this.config.fetchProvider.fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Request-ID":a},body:JSON.stringify(r)}),u=await c.text();console.error("[AccessControl] 🔍 RAW API RESPONSE (before parsing):",{correlationId:a,status:c.status,statusText:c.statusText,headers:Object.fromEntries(c.headers.entries()),responseTextLength:u.length,responseTextPreview:u.substring(0,500),fullResponseText:u});const d=this.parseResponseJSON(c,u);if(console.error("[AccessControl] 🔍 PARSED RESPONSE DATA:",{correlationId:a,status:c.status,responseDataType:typeof d,responseDataKeys:Object.keys(d||{}),responseData:JSON.stringify(d,null,2)}),!c.ok){const t=d;if(t.error){const r=t.error.code||"api_error";if("all_proofs_rejected"===r&&400===c.status){const r=t.error.details,o={success:!1,accepted:0,rejected:r?.rejected||e.proofs.length,outcomes:{success:0,failed:0,blocked:0,error:r?.rejected||e.proofs.length},errors:r?.errors},a=n.proofSubmissionResponseSchema.safeParse(o);if(a.success)return a.data;throw new i.AgentShieldAPIError("invalid_response","Error response validation failed",{zodErrors:a.error.errors})}const o={...t.error.details||{},status:c.status};throw new i.AgentShieldAPIError(r,t.error.message||`API error: ${c.status}`,o)}let r="api_error";throw 400===c.status?r="validation_error":404===c.status&&(r=c.statusText.includes("delegation")?"delegation_not_found":"session_not_found"),new i.AgentShieldAPIError(r,`API request failed: ${c.status} ${c.statusText}`,{status:c.status,responseData:d})}const l=d,p={correlationId:a,hasSuccess:void 0!==l.success,hasData:void 0!==l.data,responseType:typeof d,responseKeys:Object.keys(d||{}),responseData:JSON.stringify(d,null,2).substring(0,2e3)};if(this.config.logger("[AccessControl] Raw response received",p),console.error("[AccessControl] Raw response received:",JSON.stringify(d,null,2)),void 0!==l.success&&l.data){let e;try{const t=l.data,r=JSON.parse(JSON.stringify(t));if("object"!=typeof r||null===r)throw new i.AgentShieldAPIError("invalid_response","Response data is not an object after cloning",{originalType:typeof t,clonedType:typeof r,clonedValue:r});e=r}catch(e){if(e instanceof i.AgentShieldAPIError)throw e;throw new i.AgentShieldAPIError("invalid_response","Failed to clone response data",{error:e instanceof Error?e.message:String(e),dataType:typeof l.data})}console.error("[AccessControl] 🔍 DATA OBJECT STRUCTURE (after deep clone):",{correlationId:a,dataKeys:Object.keys(e),hasAccepted:"accepted"in e,hasRejected:"rejected"in e,hasOutcomes:"outcomes"in e,hasErrors:"errors"in e,acceptedType:typeof e.accepted,acceptedValue:e.accepted,rejectedType:typeof e.rejected,rejectedValue:e.rejected,outcomesType:typeof e.outcomes,outcomesValue:e.outcomes,errorsType:typeof e.errors,errorsIsArray:Array.isArray(e.errors),fullData:JSON.stringify(e,null,2)});const t={success:!0===l.success,accepted:e.accepted,rejected:e.rejected};if("outcomes"in e&&void 0!==e.outcomes&&(t.outcomes=e.outcomes),"errors"in e&&void 0!==e.errors&&(t.errors=e.errors),console.error("[AccessControl] 🔍 VALIDATING DATA WITH SUCCESS:",{correlationId:a,dataWithSuccessKeys:Object.keys(t),hasSuccess:"success"in t,successValue:t.success,hasAccepted:"accepted"in t,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedValue:t.rejected,hasOutcomes:"outcomes"in t,outcomesValue:t.outcomes,fullDataWithSuccess:JSON.stringify(t,null,2)}),"number"!=typeof t.accepted||"number"!=typeof t.rejected)throw console.error("[AccessControl] ❌ MISSING REQUIRED FIELDS AFTER CONSTRUCTION:",{correlationId:a,hasAccepted:"accepted"in t,acceptedType:typeof t.accepted,acceptedValue:t.accepted,hasRejected:"rejected"in t,rejectedType:typeof t.rejected,rejectedValue:t.rejected,dataWithSuccessKeys:Object.keys(t),fullDataWithSuccess:JSON.stringify(t,null,2),dataToValidateKeys:Object.keys(e),fullDataToValidate:JSON.stringify(e,null,2),originalResponseData:JSON.stringify(d,null,2)}),new i.AgentShieldAPIError("invalid_response","Response data missing required fields (accepted/rejected)",{responseData:d,dataToValidate:e,dataWithSuccess:t});const r=n.proofSubmissionResponseSchema.safeParse(t);if(r.success)return this.config.logger("[AccessControl] Proofs submitted successfully (wrapped)",{correlationId:a,accepted:r.data.accepted,rejected:r.data.rejected}),r.data;{const n={correlationId:a,zodErrors:r.error.errors,zodErrorDetails:JSON.stringify(r.error.errors,null,2),dataToValidate:JSON.stringify(e,null,2).substring(0,2e3),dataWithSuccess:JSON.stringify(t,null,2).substring(0,2e3),dataKeys:Object.keys(e),dataWithSuccessKeys:Object.keys(t),originalResponse:JSON.stringify(d,null,2).substring(0,2e3)};throw this.config.logger("[AccessControl] Wrapped response validation failed",n),console.error("[AccessControl] Wrapped response validation failed",n),console.error("[AccessControl] Original wrapped response:",JSON.stringify(d,null,2)),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED - ${r.error.errors.length} error(s):`),r.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,JSON.stringify(r,null,2))}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(r.error.errors,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:r.error.errors,responseData:d})}}const f=n.proofSubmissionResponseSchema.safeParse(d);if(!f.success){const e={correlationId:a,zodErrors:f.error.errors,zodErrorDetails:JSON.stringify(f.error.errors,null,2),responseData:JSON.stringify(d,null,2),responseDataType:typeof d,responseKeys:Object.keys(d||{}),httpStatus:c.status,httpStatusText:c.statusText};throw this.config.logger("[AccessControl] Response validation failed",e),console.error("[AccessControl] Response validation failed",{zodErrors:f.error.errors,responseData:d}),console.error("[AccessControl] Response validation failed",e),console.error(`[AccessControl] ❌ ZOD VALIDATION FAILED (direct) - ${f.error.errors.length} error(s):`),f.error.errors.forEach((e,t)=>{const r={path:e.path.join(".")||"(root)",message:e.message,code:e.code};"received"in e&&(r.received=e.received),"expected"in e&&(r.expected=e.expected),"input"in e&&(r.input=e.input),console.error(`[AccessControl] Error ${t+1}:`,r)}),console.error("[AccessControl] ❌ Full ZOD errors JSON:",JSON.stringify(f.error.errors,null,2)),console.error("[AccessControl] ❌ ACTUAL RESPONSE DATA:",JSON.stringify(d,null,2)),new i.AgentShieldAPIError("invalid_response","Response validation failed",{zodErrors:f.error.errors,responseData:d})}return this.config.logger("[AccessControl] Proofs submitted successfully",{correlationId:a,accepted:f.data.accepted,rejected:f.data.rejected}),f.data})}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={successCount:0,errorCount:0,retryCount:0}}async retryWithBackoff(e,t=0){try{const t=await e();return this.metrics.successCount++,t}catch(r){const n=this.isRetryableError(r),{maxRetries:i,initialDelayMs:o,maxDelayMs:a}=this.config.retryConfig;if(n&&t<i){const r=Math.min(o*Math.pow(2,t),a);return this.metrics.retryCount++,this.config.logger(`Retrying after ${r}ms (attempt ${t+1}/${i})`),await this.sleep(r),this.retryWithBackoff(e,t+1)}throw this.metrics.errorCount++,r}}isRetryableError(e){if(e instanceof TypeError&&e.message.includes("fetch"))return!0;if(e instanceof i.AgentShieldAPIError){if("server_error"===e.code)return!0;const t=e.details?.status;if(t&&t>=500&&t<600)return!0;if(429===t)return!0}if(e instanceof Error){const t=e.message.toLowerCase();if(t.includes("timeout")||t.includes("timed out"))return!0}return!1}sleep(e){return this.config.sleepProvider(e)}parseResponseJSON(e,t){try{return JSON.parse(t)}catch(r){if(!e.ok){const r=this.mapStatusToErrorCode(e.status);throw new i.AgentShieldAPIError(r,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseText:t.substring(0,500)})}throw new i.AgentShieldAPIError("invalid_response",`Failed to parse response: ${r instanceof Error?r.message:String(r)}`,{responseText:t.substring(0,500)})}}mapStatusToErrorCode(e,t=""){return 400===e?"validation_error":401===e||403===e?"authentication_failed":404===e?"config_not_found":e>=500?"server_error":"api_error"}handleErrorResponse(e,t){const r=t;if(r.error){const t=r.error.code||"api_error",n={...r.error.details||{},status:e.status};throw new i.AgentShieldAPIError(t,r.error.message||`API error: ${e.status}`,n)}const n=this.mapStatusToErrorCode(e.status,e.statusText);throw new i.AgentShieldAPIError(n,`API request failed: ${e.status} ${e.statusText}`,{status:e.status,responseData:t})}}},37067:e=>{"use strict";e.exports=require("node:http")},37121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=void 0,t.createSchemaVerifier=function(e){return new r(e)};class r{schemasBaseUrl="https://schema.modelcontextprotocol-identity.io";schemaCache=new Map;constructor(e){e?.schemasBaseUrl&&(this.schemasBaseUrl=e.schemasBaseUrl)}async verifySchema(e,t){const r=[],n=[],i=[];let o;try{o=await this.fetchSchema(e.url)}catch(t){return{schema:e,compliant:!1,compliancePercentage:0,fields:[],issues:[`Failed to fetch schema: ${t instanceof Error?t.message:"Unknown error"}`],warnings:[],timestamp:Date.now()}}const a=this.resolveRef(o,o),s=this.validateAgainstSchema(t,a,o,"");r.push(...s.fields);for(const e of r)"fail"===e.status?n.push(`${e.fieldPath}: ${e.reason}`):"warning"===e.status&&i.push(`${e.fieldPath}: ${e.reason}`);const c=r.filter(e=>e.required),u=c.filter(e=>"pass"===e.status).length,d=c.length>0?u/c.length*100:100;return{schema:e,compliant:0===n.length&&d>=95,compliancePercentage:d,fields:r,issues:n,warnings:i,timestamp:Date.now()}}async verifyAll(e,t){const r=[],n=[];for(const i of e){const e=t.get(i.id);if(!e){n.push(`No implementation found for schema: ${i.id}`);continue}const o=await this.verifySchema(i,e);r.push(o),o.compliant||n.push(`${i.id}: ${o.issues.join(", ")}`)}const i=r.filter(e=>e.compliant).length,o=e.length>0?i/e.length*100:0;return{totalSchemas:e.length,compliantSchemas:i,overallCompliance:o,schemaReports:r,criticalIssues:n,timestamp:Date.now()}}validateAgainstSchema(e,t,r,n){const i=[];if((t=this.resolveRef(t,r)).oneOf||t.anyOf||t.allOf)return this.validateUnion(e,t,r,n);if("object"===t.type&&t.properties){const o=t.required||[];for(const[a,s]of Object.entries(t.properties)){const t=n?`${n}.${a}`:a,c=e?.[a],u=o.includes(a),d=this.checkField(t,c,s,r,u);if(i.push(d),void 0!==c&&"object"===s.type){const e=this.validateAgainstSchema(c,s,r,t);i.push(...e.fields)}}}if("array"===t.type&&e&&Array.isArray(e)){const o=this.validateArray(e,t,r,n);i.push(...o.fields)}return{fields:i}}validateUnion(e,t,r,n){const i=[];if(t.anyOf||t.oneOf){const o=t.anyOf||t.oneOf;let a=!1;for(const t of o){const o=this.resolveRef(t,r);try{if(this.matchesSchema(e,o,r)){const t=this.validateAgainstSchema(e,o,r,n);i.push(...t.fields),a=!0;break}}catch(e){continue}}!a&&n&&i.push({fieldPath:n,present:void 0!==e,expectedType:"oneOf/anyOf options",actualType:typeof e,typeMatches:!1,required:!0,status:"fail",reason:"Value does not match any of the schema options"})}if(t.allOf)for(const o of t.allOf){const t=this.resolveRef(o,r),a=this.validateAgainstSchema(e,t,r,n);i.push(...a.fields)}return{fields:i}}matchesSchema(e,t,r){if((t=this.resolveRef(t,r)).type){const r=Array.isArray(e)?"array":typeof e;if("integer"===t.type&&"number"===r){if(!Number.isInteger(e))return!1}else if(t.type!==r)return!1}if(void 0!==t.const&&e!==t.const)return!1;if(t.enum&&!t.enum.includes(e))return!1;if(t.pattern&&"string"==typeof e&&!new RegExp(t.pattern).test(e))return!1;if("object"===t.type&&t.required)for(const r of t.required)if(!(r in e))return!1;return!0}validateArray(e,t,r,n){const i=[];if(void 0!==t.minItems&&e.length<t.minItems&&i.push({fieldPath:`${n}.length`,present:!0,expectedType:`array with minItems: ${t.minItems}`,actualType:`array with length: ${e.length}`,typeMatches:!1,required:!0,status:"fail",reason:`Array length ${e.length} is less than minItems ${t.minItems}`}),Array.isArray(t.items)){for(let o=0;o<t.items.length;o++){const a=t.items[o],s=e[o],c=`${n}[${o}]`;if(void 0!==s){const e=this.resolveRef(a,r),t=this.validateAgainstSchema(s,e,r,c);i.push(...t.fields)}}if(void 0!==t.additionalItems&&e.length>t.items.length)for(let o=t.items.length;o<e.length;o++){const a=e[o],s=`${n}[${o}]`,c=this.validateAgainstSchema(a,t.additionalItems,r,s);i.push(...c.fields)}}else if(t.items)for(let o=0;o<e.length;o++){const a=e[o],s=`${n}[${o}]`,c=this.resolveRef(t.items,r),u=this.validateAgainstSchema(a,c,r,s);i.push(...u.fields)}if(t.contains){const o=this.resolveRef(t.contains,r);e.some(e=>this.matchesSchema(e,o,r))||i.push({fieldPath:`${n}.contains`,present:!0,expectedType:"array containing matching item",actualType:"array without matching item",typeMatches:!1,required:!0,status:"fail",reason:'Array does not contain any item matching the "contains" schema'})}return{fields:i}}checkField(e,t,r,n,i){r=this.resolveRef(r,n);const o=void 0!==t,a=this.getActualType(t);let s="unknown";return r.type?s=r.type:r.anyOf?s="anyOf":r.oneOf?s="oneOf":r.allOf&&(s="allOf"),i&&!o?{fieldPath:e,present:o,expectedType:s,actualType:a,typeMatches:!1,required:i,status:"fail",reason:"Required field missing"}:i||o?this.matchesSchema(t,r,n)?{fieldPath:e,present:o,expectedType:s,actualType:a,typeMatches:!0,required:i,status:"pass"}:{fieldPath:e,present:o,expectedType:s,actualType:a,typeMatches:!1,required:i,status:"fail",reason:"Type/value mismatch"}:{fieldPath:e,present:o,expectedType:s,actualType:a,typeMatches:!0,required:i,status:"pass"}}getActualType(e){return null===e?"null":Array.isArray(e)?"array":"number"==typeof e&&Number.isInteger(e)?"integer":typeof e}resolveRef(e,t){if(!e.$ref)return e;const r=e.$ref;if(r.startsWith("#/definitions/")){const e=r.substring(14);if(t.definitions&&t.definitions[e])return t.definitions[e]}if(r.startsWith("#/$defs/")){const e=r.substring(8);if(t.$defs&&t.$defs[e])return t.$defs[e]}return"#"===r?t:e}async fetchSchema(e){if(this.schemaCache.has(e))return this.schemaCache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.json();return this.schemaCache.set(e,r),r}catch(t){if(t instanceof Error)throw new Error(`Failed to fetch schema from ${e}: ${t.message}`);throw new Error(`Failed to fetch schema from ${e}: Unknown error`)}}generateReport(e){const t=[];t.push(`\n${"=".repeat(80)}`),t.push(`SCHEMA COMPLIANCE REPORT: ${e.schema.id}`),t.push(`${"=".repeat(80)}\n`),t.push(`Schema: ${e.schema.type} v${e.schema.version}`),t.push(`URL: ${e.schema.url}`),t.push("Status: "+(e.compliant?"✅ COMPLIANT":"❌ NON-COMPLIANT")),t.push(`Compliance: ${e.compliancePercentage.toFixed(1)}%\n`),e.issues.length>0&&(t.push(`\n🚨 ISSUES (${e.issues.length}):`),e.issues.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),e.warnings.length>0&&(t.push(`\n⚠️ WARNINGS (${e.warnings.length}):`),e.warnings.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),t.push("\n📊 FIELD DETAILS:\n");const r=e.fields.filter(e=>e.required),n=r.filter(e=>"pass"===e.status).length,i=r.filter(e=>"fail"===e.status).length,o=e.fields.filter(e=>"warning"===e.status).length;return t.push(` ✅ Pass: ${n}/${r.length} required fields`),t.push(` ❌ Fail: ${i}/${r.length} required fields`),t.push(` ⚠️ Warn: ${o} optional fields`),t.push(` 📝 Total: ${e.fields.length} fields checked\n`),t.push(`${"=".repeat(80)}\n`),t.join("\n")}generateFullReport(e){const t=[];return t.push(`\n${"=".repeat(80)}`),t.push("FULL SCHEMA COMPLIANCE REPORT"),t.push(`${"=".repeat(80)}\n`),t.push(`Total Schemas: ${e.totalSchemas}`),t.push(`Compliant: ${e.compliantSchemas}`),t.push("Non-Compliant: "+(e.totalSchemas-e.compliantSchemas)),t.push(`Overall Compliance: ${e.overallCompliance.toFixed(1)}%\n`),e.criticalIssues.length>0&&(t.push(`\n🚨 CRITICAL ISSUES (${e.criticalIssues.length}):`),e.criticalIssues.slice(0,10).forEach((e,r)=>{t.push(` ${r+1}. ${e}`)}),e.criticalIssues.length>10&&t.push(` ... and ${e.criticalIssues.length-10} more issues`)),t.push("\n📊 SCHEMA BREAKDOWN:\n"),e.schemaReports.forEach(e=>{const r=e.compliant?"✅":"❌",n=e.compliancePercentage.toFixed(1);t.push(` ${r} ${e.schema.id}: ${n}%`)}),t.push(`\n${"=".repeat(80)}\n`),t.join("\n")}}t.SchemaVerifier=r},37329:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateSecret=async function(e,t){let r;switch(e){case"HS256":case"HS384":case"HS512":case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128KW":case"A192KW":case"A256KW":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new a.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return(0,n.createSecretKey)((0,o.default)(new Uint8Array(r>>3)))},t.generateKeyPair=async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new a.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await s("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return s("ec",{namedCurve:"P-256"});case"ES256K":return s("ec",{namedCurve:"secp256k1"});case"ES384":return s("ec",{namedCurve:"P-384"});case"ES512":return s("ec",{namedCurve:"P-521"});case"Ed25519":return s("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return s("ed25519");case"Ed448":return s("ed448");default:throw new a.JOSENotSupported("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return s("ec",{namedCurve:e});case"X25519":return s("x25519");case"X448":return s("x448");default:throw new a.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new a.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}};const n=r(77598),i=r(57975),o=r(84641),a=r(39069),s=(0,i.promisify)(n.generateKeyPair)},37527:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(33346);const i=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${n.stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${n.joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Too big: expected ${e.origin??"value"} to have ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Too small: expected ${e.origin} to have ${r}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${n.joinValues(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function o(){return{localeError:i()}}},38296:(e,t,r)=>{"use strict";r.d(t,{FT:()=>Cr,TF:()=>Or,gd:()=>Ut,gH:()=>Mt,Sq:()=>at,WK:()=>br,K1:()=>Vr,TI:()=>qr,Mg:()=>Tt,n_:()=>dn,wR:()=>it,O4:()=>et,oQ:()=>Nt,Ql:()=>jt,Sc:()=>Dt,a8:()=>dt,rk:()=>vt,ZC:()=>bt,OR:()=>nt,aE:()=>Oe,Cs:()=>yn,zR:()=>zt,a5:()=>Rt,gW:()=>Er,FP:()=>jr,Nh:()=>bn,tC:()=>wt,_r:()=>kt,EV:()=>Ce,UJ:()=>Ve,Iu:()=>Te,b_:()=>Nr,ki:()=>At,Dn:()=>Pr,LW:()=>rt,lg:()=>Xe,vo:()=>Be,ig:()=>Qe,bZ:()=>Ze});var n=r(14074);const i=n.xIx("ZodISODateTime",(e,t)=>{n.KoL.init(e,t),_.init(e,t)});function o(e){return n.G1$(i,e)}const a=n.xIx("ZodISODate",(e,t)=>{n.v1L.init(e,t),_.init(e,t)}),s=n.xIx("ZodISOTime",(e,t)=>{n.Ax8.init(e,t),_.init(e,t)}),c=n.xIx("ZodISODuration",(e,t)=>{n.$Nv.init(e,t),_.init(e,t)}),u=(e,t)=>{n.a$H.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>n.Wk_(e,t)},flatten:{value:t=>n.JMU(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},d=(n.xIx("ZodError",u),n.xIx("ZodError",u,{Parent:Error})),l=n.Tjm(d),p=n.Rb(d),f=n.Ody(d),h=n.wGr(d),m=n.xIx("ZodType",(e,t)=>(n.W4S.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>n.o8B(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>l(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>f(e,t,r),e.parseAsync=async(t,r)=>p(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>h(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return n.fUZ(Pe,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e,t){const r=new n.QPK({check:"custom",...n.ZSL.normalizeParams(t)});return r._zod.check=e,r}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(n.ZSL.issue(e,r.value,t._zod.def));else{const i=e;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(n.ZSL.issue(i))}},e(r.value,r)),void 0);return t}(t)),e.overwrite=t=>e.check(n.bS9(t)),e.optional=()=>ge(e),e.nullable=()=>ye(e),e.nullish=()=>ge(ye(e)),e.nonoptional=t=>function(e,t){return new we({type:"nonoptional",innerType:e,...n.ZSL.normalizeParams(t)})}(e,t),e.array=()=>X(e),e.or=t=>re([e,t]),e.and=t=>ae(e,t),e.transform=t=>ke(e,he(t)),e.default=t=>{return r=t,new _e({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new be({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new $e({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>ke(e,t),e.readonly=()=>new Ie({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return n.fd.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>n.fd.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return n.fd.get(e);const r=e.clone();return n.fd.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),g=n.xIx("_ZodString",(e,t)=>{n.$vM.init(e,t),m.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(n.Fkv(...t)),e.includes=(...t)=>e.check(n.dRF(...t)),e.startsWith=(...t)=>e.check(n.$S2(...t)),e.endsWith=(...t)=>e.check(n.ERr(...t)),e.min=(...t)=>e.check(n.m9B(...t)),e.max=(...t)=>e.check(n.Ebs(...t)),e.length=(...t)=>e.check(n.YAm(...t)),e.nonempty=(...t)=>e.check(n.m9B(1,...t)),e.lowercase=t=>e.check(n.hH9(t)),e.uppercase=t=>e.check(n.qFb(t)),e.trim=()=>e.check(n.WN0()),e.normalize=(...t)=>e.check(n.loG(...t)),e.toLowerCase=()=>e.check(n.Ilv()),e.toUpperCase=()=>e.check(n.xYx())}),v=n.xIx("ZodString",(e,t)=>{n.$vM.init(e,t),g.init(e,t),e.email=t=>e.check(n.Mue(b,t)),e.url=t=>e.check(n.Fnx(S,t)),e.jwt=t=>e.check(n.rkn(U,t)),e.emoji=t=>e.check(n.aCo(k,t)),e.guid=t=>e.check(n.tB6(w,t)),e.uuid=t=>e.check(n.Bem($,t)),e.uuidv4=t=>e.check(n.nA($,t)),e.uuidv6=t=>e.check(n.pYI($,t)),e.uuidv7=t=>e.check(n.wAW($,t)),e.nanoid=t=>e.check(n.Dl9(I,t)),e.guid=t=>e.check(n.tB6(w,t)),e.cuid=t=>e.check(n.fsu(P,t)),e.cuid2=t=>e.check(n.BjO(E,t)),e.ulid=t=>e.check(n.CtB(x,t)),e.base64=t=>e.check(n.rty(N,t)),e.base64url=t=>e.check(n.cUp(z,t)),e.xid=t=>e.check(n.Pwh(O,t)),e.ksuid=t=>e.check(n._zn(T,t)),e.ipv4=t=>e.check(n.NyF(C,t)),e.ipv6=t=>e.check(n.$O6(A,t)),e.cidrv4=t=>e.check(n.UyX(j,t)),e.cidrv6=t=>e.check(n.gPm(D,t)),e.e164=t=>e.check(n.KBX(R,t)),e.datetime=t=>e.check(o(t)),e.date=t=>e.check(function(e){return n.dbS(a,e)}(t)),e.time=t=>e.check(function(e){return n.KnZ(s,e)}(t)),e.duration=t=>e.check(function(e){return n.f25(c,e)}(t))});function y(e){return n.Rle(v,e)}const _=n.xIx("ZodStringFormat",(e,t)=>{n.EYA.init(e,t),g.init(e,t)}),b=n.xIx("ZodEmail",(e,t)=>{n.qGO.init(e,t),_.init(e,t)}),w=n.xIx("ZodGUID",(e,t)=>{n.Zc9.init(e,t),_.init(e,t)}),$=n.xIx("ZodUUID",(e,t)=>{n.Znh.init(e,t),_.init(e,t)}),S=n.xIx("ZodURL",(e,t)=>{n.VYh.init(e,t),_.init(e,t)}),k=n.xIx("ZodEmoji",(e,t)=>{n.cG4.init(e,t),_.init(e,t)}),I=n.xIx("ZodNanoID",(e,t)=>{n.Pyd.init(e,t),_.init(e,t)}),P=n.xIx("ZodCUID",(e,t)=>{n.bl8.init(e,t),_.init(e,t)}),E=n.xIx("ZodCUID2",(e,t)=>{n.Zu1.init(e,t),_.init(e,t)}),x=n.xIx("ZodULID",(e,t)=>{n.g5t.init(e,t),_.init(e,t)}),O=n.xIx("ZodXID",(e,t)=>{n.TFq.init(e,t),_.init(e,t)}),T=n.xIx("ZodKSUID",(e,t)=>{n.GYt.init(e,t),_.init(e,t)}),C=n.xIx("ZodIPv4",(e,t)=>{n.Lc$.init(e,t),_.init(e,t)}),A=n.xIx("ZodIPv6",(e,t)=>{n.ZyE.init(e,t),_.init(e,t)}),j=n.xIx("ZodCIDRv4",(e,t)=>{n.CI7.init(e,t),_.init(e,t)}),D=n.xIx("ZodCIDRv6",(e,t)=>{n.CnV.init(e,t),_.init(e,t)}),N=n.xIx("ZodBase64",(e,t)=>{n.Dqv.init(e,t),_.init(e,t)}),z=n.xIx("ZodBase64URL",(e,t)=>{n.CQL.init(e,t),_.init(e,t)}),R=n.xIx("ZodE164",(e,t)=>{n.Oyg.init(e,t),_.init(e,t)}),U=n.xIx("ZodJWT",(e,t)=>{n.h80.init(e,t),_.init(e,t)}),M=n.xIx("ZodNumber",(e,t)=>{n.vzu.init(e,t),m.init(e,t),e.gt=(t,r)=>e.check(n.TxR(t,r)),e.gte=(t,r)=>e.check(n.qmM(t,r)),e.min=(t,r)=>e.check(n.qmM(t,r)),e.lt=(t,r)=>e.check(n.AuJ(t,r)),e.lte=(t,r)=>e.check(n.Zm2(t,r)),e.max=(t,r)=>e.check(n.Zm2(t,r)),e.int=t=>e.check(Z(t)),e.safe=t=>e.check(Z(t)),e.positive=t=>e.check(n.TxR(0,t)),e.nonnegative=t=>e.check(n.qmM(0,t)),e.negative=t=>e.check(n.AuJ(0,t)),e.nonpositive=t=>e.check(n.Zm2(0,t)),e.multipleOf=(t,r)=>e.check(n.HiR(t,r)),e.step=(t,r)=>e.check(n.HiR(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function K(e){return n.F7R(M,e)}const J=n.xIx("ZodNumberFormat",(e,t)=>{n.Iab.init(e,t),M.init(e,t)});function Z(e){return n.LKT(J,e)}const L=n.xIx("ZodBoolean",(e,t)=>{n.sFi.init(e,t),m.init(e,t)});function W(e){return n._Le(L,e)}const F=n.xIx("ZodNull",(e,t)=>{n.x89.init(e,t),m.init(e,t)});function H(e){return n.jwX(F,e)}const V=n.xIx("ZodUnknown",(e,t)=>{n.GPR.init(e,t),m.init(e,t)});function q(){return n.emL(V)}const B=n.xIx("ZodNever",(e,t)=>{n.Umr.init(e,t),m.init(e,t)});const G=n.xIx("ZodArray",(e,t)=>{n.$ps.init(e,t),m.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(n.m9B(t,r)),e.nonempty=t=>e.check(n.m9B(1,t)),e.max=(t,r)=>e.check(n.Ebs(t,r)),e.length=(t,r)=>e.check(n.YAm(t,r)),e.unwrap=()=>e.element});function X(e,t){return n.dZg(G,e,t)}const Y=n.xIx("ZodObject",(e,t)=>{n.L8f.init(e,t),m.init(e,t),n.ZSL.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>de(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:q()}),e.loose=()=>e.clone({...e._zod.def,catchall:q()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:n.G8g(B,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>n.ZSL.extend(e,t),e.merge=t=>n.ZSL.merge(e,t),e.pick=t=>n.ZSL.pick(e,t),e.omit=t=>n.ZSL.omit(e,t),e.partial=(...t)=>n.ZSL.partial(me,e,t[0]),e.required=(...t)=>n.ZSL.required(we,e,t[0])});function Q(e,t){const r={type:"object",get shape(){return n.ZSL.assignProp(this,"shape",{...e}),this.shape},...n.ZSL.normalizeParams(t)};return new Y(r)}function ee(e,t){return new Y({type:"object",get shape(){return n.ZSL.assignProp(this,"shape",{...e}),this.shape},catchall:q(),...n.ZSL.normalizeParams(t)})}const te=n.xIx("ZodUnion",(e,t)=>{n.L8w.init(e,t),m.init(e,t),e.options=t.options});function re(e,t){return new te({type:"union",options:e,...n.ZSL.normalizeParams(t)})}const ne=n.xIx("ZodDiscriminatedUnion",(e,t)=>{te.init(e,t),n.P0p.init(e,t)});function ie(e,t,r){return new ne({type:"union",options:t,discriminator:e,...n.ZSL.normalizeParams(r)})}const oe=n.xIx("ZodIntersection",(e,t)=>{n.LJA.init(e,t),m.init(e,t)});function ae(e,t){return new oe({type:"intersection",left:e,right:t})}const se=n.xIx("ZodRecord",(e,t)=>{n.hax.init(e,t),m.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ce(e,t,r){return new se({type:"record",keyType:e,valueType:t,...n.ZSL.normalizeParams(r)})}const ue=n.xIx("ZodEnum",(e,t)=>{n.VOE.init(e,t),m.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,i)=>{const o={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);o[n]=t.entries[n]}return new ue({...t,checks:[],...n.ZSL.normalizeParams(i),entries:o})},e.exclude=(e,i)=>{const o={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new ue({...t,checks:[],...n.ZSL.normalizeParams(i),entries:o})}});function de(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ue({type:"enum",entries:r,...n.ZSL.normalizeParams(t)})}const le=n.xIx("ZodLiteral",(e,t)=>{n.nuC.init(e,t),m.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function pe(e,t){return new le({type:"literal",values:Array.isArray(e)?e:[e],...n.ZSL.normalizeParams(t)})}const fe=n.xIx("ZodTransform",(e,t)=>{n.Wc_.init(e,t),m.init(e,t),e._zod.parse=(r,i)=>{r.addIssue=i=>{if("string"==typeof i)r.issues.push(n.ZSL.issue(i,r.value,t));else{const t=i;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(n.ZSL.issue(t))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(e=>(r.value=e,r)):(r.value=o,r)}});function he(e){return new fe({type:"transform",transform:e})}const me=n.xIx("ZodOptional",(e,t)=>{n.igI.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ge(e){return new me({type:"optional",innerType:e})}const ve=n.xIx("ZodNullable",(e,t)=>{n.ZQr.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ye(e){return new ve({type:"nullable",innerType:e})}const _e=n.xIx("ZodDefault",(e,t)=>{n.rvF.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),be=n.xIx("ZodPrefault",(e,t)=>{n.VFw.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType}),we=n.xIx("ZodNonOptional",(e,t)=>{n.N$X.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType}),$e=n.xIx("ZodCatch",(e,t)=>{n.t$E.init(e,t),m.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Se=n.xIx("ZodPipe",(e,t)=>{n._mk.init(e,t),m.init(e,t),e.in=t.in,e.out=t.out});function ke(e,t){return new Se({type:"pipe",in:e,out:t})}const Ie=n.xIx("ZodReadonly",(e,t)=>{n.Sbs.init(e,t),m.init(e,t)}),Pe=n.xIx("ZodCustom",(e,t)=>{n.b03.init(e,t),m.init(e,t)});function Ee(e,t){return ke(he(e),t)}Object.freeze({status:"aborted"});var xe=r(37527);r(7673),(0,n.$WB)((0,xe.A)());const Oe="2025-11-25",Te=[Oe,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ce="io.modelcontextprotocol/related-task",Ae="2.0",je=(De=e=>null!==e&&("object"==typeof e||"function"==typeof e),n.FOv(Pe,De??(()=>!0),undefined));var De;const Ne=re([y(),K().int()]),ze=y(),Re=(ee({ttl:re([K(),H()]).optional(),pollInterval:K().optional()}),Q({ttl:K().optional()})),Ue=Q({taskId:y()}),Me=ee({progressToken:Ne.optional(),[Ce]:Ue.optional()}),Ke=Q({_meta:Me.optional()}),Je=Ke.extend({task:Re.optional()}),Ze=e=>Je.safeParse(e).success,Le=Q({method:y(),params:Ke.loose().optional()}),We=Q({_meta:Me.optional()}),Fe=Q({method:y(),params:We.loose().optional()}),He=ee({_meta:Me.optional()}),Ve=re([y(),K().int()]),qe=Q({jsonrpc:pe(Ae),id:Ve,...Le.shape}).strict(),Be=e=>qe.safeParse(e).success,Ge=Q({jsonrpc:pe(Ae),...Fe.shape}).strict(),Xe=e=>Ge.safeParse(e).success,Ye=Q({jsonrpc:pe(Ae),id:Ve,result:He}).strict(),Qe=e=>Ye.safeParse(e).success;var et;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(et||(et={}));const tt=Q({jsonrpc:pe(Ae),id:Ve.optional(),error:Q({code:K().int(),message:y(),data:q().optional()})}).strict(),rt=e=>tt.safeParse(e).success,nt=re([qe,Ge,Ye,tt]),it=(re([Ye,tt]),He.strict()),ot=We.extend({requestId:Ve.optional(),reason:y().optional()}),at=Fe.extend({method:pe("notifications/cancelled"),params:ot}),st=Q({src:y(),mimeType:y().optional(),sizes:X(y()).optional(),theme:de(["light","dark"]).optional()}),ct=Q({icons:X(st).optional()}),ut=Q({name:y(),title:y().optional()}),dt=ut.extend({...ut.shape,...ct.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),lt=ae(Q({applyDefaults:W().optional()}),ce(y(),q())),pt=Ee(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,ae(Q({form:lt.optional(),url:je.optional()}),ce(y(),q()).optional())),ft=ee({list:je.optional(),cancel:je.optional(),requests:ee({sampling:ee({createMessage:je.optional()}).optional(),elicitation:ee({create:je.optional()}).optional()}).optional()}),ht=ee({list:je.optional(),cancel:je.optional(),requests:ee({tools:ee({call:je.optional()}).optional()}).optional()}),mt=Q({experimental:ce(y(),je).optional(),sampling:Q({context:je.optional(),tools:je.optional()}).optional(),elicitation:pt.optional(),roots:Q({listChanged:W().optional()}).optional(),tasks:ft.optional()}),gt=Ke.extend({protocolVersion:y(),capabilities:mt,clientInfo:dt}),vt=Le.extend({method:pe("initialize"),params:gt}),yt=Q({experimental:ce(y(),je).optional(),logging:je.optional(),completions:je.optional(),prompts:Q({listChanged:W().optional()}).optional(),resources:Q({subscribe:W().optional(),listChanged:W().optional()}).optional(),tools:Q({listChanged:W().optional()}).optional(),tasks:ht.optional()}),_t=He.extend({protocolVersion:y(),capabilities:yt,serverInfo:dt,instructions:y().optional()}),bt=Fe.extend({method:pe("notifications/initialized"),params:We.optional()}),wt=Le.extend({method:pe("ping"),params:Ke.optional()}),$t=Q({progress:K(),total:ge(K()),message:ge(y())}),St=Q({...We.shape,...$t.shape,progressToken:Ne}),kt=Fe.extend({method:pe("notifications/progress"),params:St}),It=Ke.extend({cursor:ze.optional()}),Pt=Le.extend({params:It.optional()}),Et=He.extend({nextCursor:ze.optional()}),xt=de(["working","input_required","completed","failed","cancelled"]),Ot=Q({taskId:y(),status:xt,ttl:re([K(),H()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:ge(K()),statusMessage:ge(y())}),Tt=He.extend({task:Ot}),Ct=We.merge(Ot),At=Fe.extend({method:pe("notifications/tasks/status"),params:Ct}),jt=Le.extend({method:pe("tasks/get"),params:Ke.extend({taskId:y()})}),Dt=He.merge(Ot),Nt=Le.extend({method:pe("tasks/result"),params:Ke.extend({taskId:y()})}),zt=(He.loose(),Pt.extend({method:pe("tasks/list")})),Rt=Et.extend({tasks:X(Ot)}),Ut=Le.extend({method:pe("tasks/cancel"),params:Ke.extend({taskId:y()})}),Mt=He.merge(Ot),Kt=Q({uri:y(),mimeType:ge(y()),_meta:ce(y(),q()).optional()}),Jt=Kt.extend({text:y()}),Zt=y().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Lt=Kt.extend({blob:Zt}),Wt=de(["user","assistant"]),Ft=Q({audience:X(Wt).optional(),priority:K().min(0).max(1).optional(),lastModified:o({offset:!0}).optional()}),Ht=Q({...ut.shape,...ct.shape,uri:y(),description:ge(y()),mimeType:ge(y()),annotations:Ft.optional(),_meta:ge(ee({}))}),Vt=Q({...ut.shape,...ct.shape,uriTemplate:y(),description:ge(y()),mimeType:ge(y()),annotations:Ft.optional(),_meta:ge(ee({}))}),qt=Pt.extend({method:pe("resources/list")}),Bt=Et.extend({resources:X(Ht)}),Gt=Pt.extend({method:pe("resources/templates/list")}),Xt=Et.extend({resourceTemplates:X(Vt)}),Yt=Ke.extend({uri:y()}),Qt=Yt,er=Le.extend({method:pe("resources/read"),params:Qt}),tr=He.extend({contents:X(re([Jt,Lt]))}),rr=Fe.extend({method:pe("notifications/resources/list_changed"),params:We.optional()}),nr=Yt,ir=Le.extend({method:pe("resources/subscribe"),params:nr}),or=Yt,ar=Le.extend({method:pe("resources/unsubscribe"),params:or}),sr=We.extend({uri:y()}),cr=Fe.extend({method:pe("notifications/resources/updated"),params:sr}),ur=Q({name:y(),description:ge(y()),required:ge(W())}),dr=Q({...ut.shape,...ct.shape,description:ge(y()),arguments:ge(X(ur)),_meta:ge(ee({}))}),lr=Pt.extend({method:pe("prompts/list")}),pr=Et.extend({prompts:X(dr)}),fr=Ke.extend({name:y(),arguments:ce(y(),y()).optional()}),hr=Le.extend({method:pe("prompts/get"),params:fr}),mr=Q({type:pe("text"),text:y(),annotations:Ft.optional(),_meta:ce(y(),q()).optional()}),gr=Q({type:pe("image"),data:Zt,mimeType:y(),annotations:Ft.optional(),_meta:ce(y(),q()).optional()}),vr=Q({type:pe("audio"),data:Zt,mimeType:y(),annotations:Ft.optional(),_meta:ce(y(),q()).optional()}),yr=Q({type:pe("tool_use"),name:y(),id:y(),input:ce(y(),q()),_meta:ce(y(),q()).optional()}),_r=Q({type:pe("resource"),resource:re([Jt,Lt]),annotations:Ft.optional(),_meta:ce(y(),q()).optional()}),br=re([mr,gr,vr,Ht.extend({type:pe("resource_link")}),_r]),wr=Q({role:Wt,content:br}),$r=He.extend({description:y().optional(),messages:X(wr)}),Sr=Fe.extend({method:pe("notifications/prompts/list_changed"),params:We.optional()}),kr=Q({title:y().optional(),readOnlyHint:W().optional(),destructiveHint:W().optional(),idempotentHint:W().optional(),openWorldHint:W().optional()}),Ir=Q({taskSupport:de(["required","optional","forbidden"]).optional()}),Pr=Q({...ut.shape,...ct.shape,description:y().optional(),inputSchema:Q({type:pe("object"),properties:ce(y(),je).optional(),required:X(y()).optional()}).catchall(q()),outputSchema:Q({type:pe("object"),properties:ce(y(),je).optional(),required:X(y()).optional()}).catchall(q()).optional(),annotations:kr.optional(),execution:Ir.optional(),_meta:ce(y(),q()).optional()}),Er=Pt.extend({method:pe("tools/list")}),xr=Et.extend({tools:X(Pr)}),Or=He.extend({content:X(br).default([]),structuredContent:ce(y(),q()).optional(),isError:W().optional()}),Tr=(Or.or(He.extend({toolResult:q()})),Je.extend({name:y(),arguments:ce(y(),q()).optional()})),Cr=Le.extend({method:pe("tools/call"),params:Tr}),Ar=Fe.extend({method:pe("notifications/tools/list_changed"),params:We.optional()}),jr=(Q({autoRefresh:W().default(!0),debounceMs:K().int().nonnegative().default(300)}),de(["debug","info","notice","warning","error","critical","alert","emergency"])),Dr=Ke.extend({level:jr}),Nr=Le.extend({method:pe("logging/setLevel"),params:Dr}),zr=We.extend({level:jr,logger:y().optional(),data:q()}),Rr=Fe.extend({method:pe("notifications/message"),params:zr}),Ur=Q({name:y().optional()}),Mr=Q({hints:X(Ur).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),Kr=Q({mode:de(["auto","required","none"]).optional()}),Jr=Q({type:pe("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:X(br).default([]),structuredContent:Q({}).loose().optional(),isError:W().optional(),_meta:ce(y(),q()).optional()}),Zr=ie("type",[mr,gr,vr]),Lr=ie("type",[mr,gr,vr,yr,Jr]),Wr=Q({role:Wt,content:re([Lr,X(Lr)]),_meta:ce(y(),q()).optional()}),Fr=Je.extend({messages:X(Wr),modelPreferences:Mr.optional(),systemPrompt:y().optional(),includeContext:de(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:X(y()).optional(),metadata:je.optional(),tools:X(Pr).optional(),toolChoice:Kr.optional()}),Hr=Le.extend({method:pe("sampling/createMessage"),params:Fr}),Vr=He.extend({model:y(),stopReason:ge(de(["endTurn","stopSequence","maxTokens"]).or(y())),role:Wt,content:Zr}),qr=He.extend({model:y(),stopReason:ge(de(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:Wt,content:re([Lr,X(Lr)])}),Br=Q({type:pe("boolean"),title:y().optional(),description:y().optional(),default:W().optional()}),Gr=Q({type:pe("string"),title:y().optional(),description:y().optional(),minLength:K().optional(),maxLength:K().optional(),format:de(["email","uri","date","date-time"]).optional(),default:y().optional()}),Xr=Q({type:de(["number","integer"]),title:y().optional(),description:y().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),Yr=Q({type:pe("string"),title:y().optional(),description:y().optional(),enum:X(y()),default:y().optional()}),Qr=Q({type:pe("string"),title:y().optional(),description:y().optional(),oneOf:X(Q({const:y(),title:y()})),default:y().optional()}),en=Q({type:pe("string"),title:y().optional(),description:y().optional(),enum:X(y()),enumNames:X(y()).optional(),default:y().optional()}),tn=re([Yr,Qr]),rn=re([Q({type:pe("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:Q({type:pe("string"),enum:X(y())}),default:X(y()).optional()}),Q({type:pe("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:Q({anyOf:X(Q({const:y(),title:y()}))}),default:X(y()).optional()})]),nn=re([en,tn,rn]),on=re([nn,Br,Gr,Xr]),an=re([Je.extend({mode:pe("form").optional(),message:y(),requestedSchema:Q({type:pe("object"),properties:ce(y(),on),required:X(y()).optional()})}),Je.extend({mode:pe("url"),message:y(),elicitationId:y(),url:y().url()})]),sn=Le.extend({method:pe("elicitation/create"),params:an}),cn=We.extend({elicitationId:y()}),un=Fe.extend({method:pe("notifications/elicitation/complete"),params:cn}),dn=He.extend({action:de(["accept","decline","cancel"]),content:Ee(e=>null===e?void 0:e,ce(y(),re([y(),K(),W(),X(y())])).optional())}),ln=Q({type:pe("ref/resource"),uri:y()}),pn=Q({type:pe("ref/prompt"),name:y()}),fn=Ke.extend({ref:re([pn,ln]),argument:Q({name:y(),value:y()}),context:Q({arguments:ce(y(),y()).optional()}).optional()}),hn=Le.extend({method:pe("completion/complete"),params:fn}),mn=He.extend({completion:ee({values:X(y()).max(100),total:ge(K().int()),hasMore:ge(W())})}),gn=Q({uri:y().startsWith("file://"),name:y().optional(),_meta:ce(y(),q()).optional()}),vn=Le.extend({method:pe("roots/list"),params:Ke.optional()}),yn=He.extend({roots:X(gn)}),_n=Fe.extend({method:pe("notifications/roots/list_changed"),params:We.optional()});re([wt,vt,hn,Nr,hr,lr,qt,Gt,er,ir,ar,Cr,Er,jt,Nt,zt,Ut]),re([at,kt,bt,_n,At]),re([it,Vr,qr,dn,yn,Dt,Rt,Tt]),re([wt,Hr,sn,vn,jt,Nt,zt,Ut]),re([at,kt,Rr,cr,rr,Ar,Sr,At,un]),re([it,_t,mn,$r,pr,Bt,Xt,tr,Or,xr,Dt,Rt,Tt]);class bn extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===et.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new wn(e.elicitations,t)}return new bn(e,t,r)}}class wn extends bn{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(et.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}},38563:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=[r(40424).default];t.default=n},38994:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const n=r(28261),i=r(44490);var o=r(28261);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return o.Name}});var a=r(44490);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class s{optimizeNodes(){return this}optimizeNames(e,t){return this}}class c extends s{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const r=e?i.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${n};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=C(this.rhs,e,t)),this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class u extends s{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof n.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=C(this.rhs,e,t),this}get names(){return T(this.lhs instanceof n.Name?{}:{...this.lhs.names},this.rhs)}}class d extends u{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class l extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class p extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class f extends s{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends s{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=C(this.code,e,t),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class m extends s{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const i=r[n];i.optimizeNames(e,t)||(A(e,i.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>O(e,t.names),{})}}class g extends m{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class v extends m{}class y extends g{}y.kind="else";class _ extends g{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof _?t:t.nodes:this.nodes.length?this:new _(j(e),t instanceof _?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=C(this.condition,e,t),this}get names(){const e=super.names;return T(e,this.condition),this.else&&O(e,this.else.names),e}}_.kind="if";class b extends g{}b.kind="for";class w extends b{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=C(this.iteration,e,t),this}get names(){return O(super.names,this.iteration.names)}}class $ extends b{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?i.varKinds.var:this.varKind,{name:r,from:n,to:o}=this;return`for(${t} ${r}=${n}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){const e=T(super.names,this.from);return T(e,this.to)}}class S extends b{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=C(this.iterable,e,t),this}get names(){return O(super.names,this.iterable.names)}}class k extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}k.kind="func";class I extends m{render(e){return"return "+super.render(e)}}I.kind="return";class P extends g{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&O(e,this.catch.names),this.finally&&O(e,this.finally.names),e}}class E extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}E.kind="catch";class x extends g{render(e){return"finally"+super.render(e)}}function O(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function T(e,t){return t instanceof n._CodeOrName?O(e,t.names):e}function C(e,t,r){return e instanceof n.Name?o(e):(i=e)instanceof n._Code&&i._items.some(e=>e instanceof n.Name&&1===t[e.str]&&void 0!==r[e.str])?new n._Code(e._items.reduce((e,t)=>(t instanceof n.Name&&(t=o(t)),t instanceof n._Code?e.push(...t._items):e.push(t),e),[])):e;var i;function o(e){const n=r[e.str];return void 0===n||1!==t[e.str]?e:(delete t[e.str],n)}}function A(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function j(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:n._`!${R(e)}`}x.kind="finally",t.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new i.Scope({parent:e}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const i=this._scope.toName(t);return void 0!==r&&n&&(this._constants[i.str]=r),this._leafNode(new c(e,i,r)),i}const(e,t,r){return this._def(i.varKinds.const,e,t,r)}let(e,t,r){return this._def(i.varKinds.let,e,t,r)}var(e,t,r){return this._def(i.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new u(e,t,r))}add(e,r){return this._leafNode(new d(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==n.nil&&this._leafNode(new h(e)),this}object(...e){const t=["{"];for(const[r,i]of e)t.length>1&&t.push(","),t.push(r),(r!==i||this.opts.es5)&&(t.push(":"),(0,n.addCodeArg)(t,i));return t.push("}"),new n._Code(t)}if(e,t,r){if(this._blockNode(new _(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(_,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new w(e),t)}forRange(e,t,r,n,o=(this.opts.es5?i.varKinds.var:i.varKinds.let)){const a=this._scope.toName(e);return this._for(new $(o,a,t,r),()=>n(a))}forOf(e,t,r,o=i.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=t instanceof n.Name?t:this.var("_arr",t);return this.forRange("_i",0,n._`${e}.length`,t=>{this.var(a,n._`${e}[${t}]`),r(a)})}return this._for(new S("of",o,a,t),()=>r(a))}forIn(e,t,r,o=(this.opts.es5?i.varKinds.var:i.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,n._`Object.keys(${t})`,r);const a=this._scope.toName(e);return this._for(new S("in",o,a,t),()=>r(a))}endFor(){return this._endBlockNode(b)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new p(e))}return(e){const t=new I;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(I)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new P;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new E(e),t(e)}return r&&(this._currNode=n.finally=new x,this.code(r)),this._endBlockNode(E,x)}throw(e){return this._leafNode(new f(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=n.nil,r,i){return this._blockNode(new k(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof _))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=j;const D=z(t.operators.AND);t.and=function(...e){return e.reduce(D)};const N=z(t.operators.OR);function z(e){return(t,r)=>t===n.nil?r:r===n.nil?t:n._`${R(t)} ${e} ${R(r)}`}function R(e){return e instanceof n.Name?e:n._`(${e})`}t.or=function(...e){return e.reduce(N)}},39069:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JWSSignatureVerificationFailed=t.JWKSTimeout=t.JWKSMultipleMatchingKeys=t.JWKSNoMatchingKey=t.JWKSInvalid=t.JWKInvalid=t.JWTInvalid=t.JWSInvalid=t.JWEInvalid=t.JWEDecryptionFailed=t.JOSENotSupported=t.JOSEAlgNotAllowed=t.JWTExpired=t.JWTClaimValidationFailed=t.JOSEError=void 0;class r 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)}}t.JOSEError=r,t.JWTClaimValidationFailed=class extends r{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},t.JWTExpired=class extends r{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}},t.JOSEAlgNotAllowed=class extends r{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},t.JOSENotSupported=class extends r{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},t.JWEDecryptionFailed=class extends r{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}},t.JWEInvalid=class extends r{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},t.JWSInvalid=class extends r{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},t.JWTInvalid=class extends r{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},t.JWKInvalid=class extends r{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},t.JWKSInvalid=class extends r{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},t.JWKSNoMatchingKey=class extends r{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}};class n extends r{[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)}}t.JWKSMultipleMatchingKeys=n,t.JWKSTimeout=class extends r{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}},t.JWSSignatureVerificationFailed=class extends r{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}},39409:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.compactVerify=async function(e,t,r){if(e instanceof Uint8Array&&(e=o.decoder.decode(e)),"string"!=typeof e)throw new i.JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:a,1:s,2:c,length:u}=e.split(".");if(3!==u)throw new i.JWSInvalid("Invalid Compact JWS");const d=await(0,n.flattenedVerify)({payload:s,protected:a,signature:c},t,r),l={payload:d.payload,protectedHeader:d.protectedHeader};return"function"==typeof t?{...l,key:d.key}:l};const n=r(55403),i=r(39069),o=r(45935)},40424:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n.str`must match format "${e}"`,params:({schemaCode:e})=>n._`{format: ${e}}`},code(e,t){const{gen:r,data:i,$data:o,schema:a,schemaCode:s,it:c}=e,{opts:u,errSchemaPath:d,schemaEnv:l,self:p}=c;u.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:p.formats,code:u.code.formats}),a=r.const("fDef",n._`${o}[${s}]`),c=r.let("fType"),d=r.let("format");r.if(n._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>r.assign(c,n._`${a}.type || "string"`).assign(d,n._`${a}.validate`),()=>r.assign(c,n._`"string"`).assign(d,a)),e.fail$data((0,n.or)(!1===u.strictSchema?n.nil:n._`${s} && !${d}`,function(){const e=l.$async?n._`(${a}.async ? await ${d}(${i}) : ${d}(${i}))`:n._`${d}(${i})`,r=n._`(typeof ${d} == "function" ? ${e} : ${d}.test(${i}))`;return n._`${d} && ${d} !== true && ${c} === ${t} && !${r}`}()))}():function(){const o=p.formats[a];if(!o)return void function(){if(!1!==u.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${d}"`}p.logger.warn(e())}();if(!0===o)return;const[s,c,f]=function(e){const t=e instanceof RegExp?(0,n.regexpCode)(e):u.code.formats?n._`${u.code.formats}${(0,n.getProperty)(a)}`:void 0,i=r.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,i]:[e.type||"string",e.validate,n._`${i}.validate`]}(o);s===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!l.$async)throw new Error("async format in sync schema");return n._`await ${f}(${i})`}return"function"==typeof c?n._`${f}(${i})`:n._`${f}.test(${i})`}())}())}};t.default=i},40554:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(72425),i=r(50550),o=r(7918),a=r(80338),s=r(3508),c=r(32139),u=r(94726),d=r(39069),l=r(72545),p=r(89666),f=r(6093);t.default=async function(e,t,r,h,m={}){let g,v,y;switch((0,p.default)(e,r,"encrypt"),r=await(c.default.normalizePublicKey?.(r,e))||r,e){case"dir":y=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!i.ecdhAllowed(r))throw new d.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const{apu:o,apv:a}=m;let{epk:c}=m;c||=(await i.generateEpk(r)).privateKey;const{x:p,y:f,crv:_,kty:b}=await(0,l.exportJWK)(c),w=await i.deriveKey(r,c,"ECDH-ES"===e?t:e,"ECDH-ES"===e?(0,u.bitLength)(t):parseInt(e.slice(-5,-2),10),o,a);if(v={epk:{x:p,crv:_,kty:b}},"EC"===b&&(v.epk.y=f),o&&(v.apu=(0,s.encode)(o)),a&&(v.apv=(0,s.encode)(a)),"ECDH-ES"===e){y=w;break}y=h||(0,u.default)(t);const $=e.slice(-6);g=await(0,n.wrap)($,w,y);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":y=h||(0,u.default)(t),g=await(0,a.encrypt)(e,r,y);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{y=h||(0,u.default)(t);const{p2c:n,p2s:i}=m;({encryptedKey:g,...v}=await(0,o.encrypt)(e,r,y,n,i));break}case"A128KW":case"A192KW":case"A256KW":y=h||(0,u.default)(t),g=await(0,n.wrap)(e,r,y);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{y=h||(0,u.default)(t);const{iv:n}=m;({encryptedKey:g,...v}=await(0,f.wrap)(e,r,y,n));break}default:throw new d.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:y,encryptedKey:g,parameters:v}}},40564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const n=r(28425),i=r(38994),o=r(86660),a={message:"boolean schema is false"};function s(e,t){const{gen:r,data:i}=e,o={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,n.reportError)(o,a,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:n}=e;!1===r?s(e,!1):"object"==typeof r&&!0===r.$async?t.return(o.default.data):(t.assign(i._`${n}.errors`,null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),s(e)):r.var(t,!0)}},41681:(e,t,r)=>{"use strict";r.r(t),r.d(t,{EXTENSION_ID:()=>Uf,RESOURCE_MIME_TYPE:()=>Nf,RESOURCE_URI_META_KEY:()=>Df,getUiCapability:()=>Mf,registerAppResource:()=>Rf,registerAppTool:()=>zf});var n=r(58421),i=r(38296),o=Object.defineProperty,a=(e,t)=>{for(var r in t)o(e,r,{get:t[r],enumerable:!0,configurable:!0,set:e=>t[r]=()=>e})},s={};a(s,{xor:()=>Fl,xid:()=>Ad,void:()=>Al,uuidv7:()=>vd,uuidv6:()=>gd,uuidv4:()=>md,uuid:()=>hd,util:()=>g,url:()=>_d,uppercase:()=>Hs,unknown:()=>xl,union:()=>Ll,undefined:()=>$l,ulid:()=>Td,uint64:()=>yl,uint32:()=>ll,tuple:()=>Xl,trim:()=>ec,treeifyError:()=>Ce,transform:()=>hp,toUpperCase:()=>rc,toLowerCase:()=>tc,toJSONSchema:()=>Ou,templateLiteral:()=>Jp,symbol:()=>bl,superRefine:()=>Yp,success:()=>Op,stringbool:()=>rf,stringFormat:()=>el,string:()=>sd,strictObject:()=>Kl,startsWith:()=>qs,slugify:()=>nc,size:()=>Ks,setErrorMap:()=>cf,set:()=>op,safeParseAsync:()=>Bu,safeParse:()=>qu,safeEncodeAsync:()=>rd,safeEncode:()=>ed,safeDecodeAsync:()=>nd,safeDecode:()=>td,registry:()=>xa,regexes:()=>it,regex:()=>Ws,refine:()=>Xp,record:()=>Ql,readonly:()=>Mp,property:()=>Gs,promise:()=>Fp,prettifyError:()=>je,preprocess:()=>of,prefault:()=>Ip,positive:()=>js,pipe:()=>Np,partialRecord:()=>ep,parseAsync:()=>Vu,parse:()=>Hu,overwrite:()=>Ys,optional:()=>gp,object:()=>Ml,number:()=>ol,nullish:()=>wp,nullable:()=>bp,null:()=>kl,normalize:()=>Qs,nonpositive:()=>Ns,nonoptional:()=>Ep,nonnegative:()=>zs,never:()=>Tl,negative:()=>Ds,nativeEnum:()=>cp,nanoid:()=>kd,nan:()=>jp,multipleOf:()=>Rs,minSize:()=>Ms,minLength:()=>Zs,mime:()=>Xs,meta:()=>ef,maxSize:()=>Us,maxLength:()=>Js,map:()=>np,mac:()=>Ud,lte:()=>Ts,lt:()=>Os,lowercase:()=>Fs,looseRecord:()=>tp,looseObject:()=>Jl,locales:()=>xi,literal:()=>dp,length:()=>Ls,lazy:()=>Lp,ksuid:()=>Dd,keyof:()=>Rl,jwt:()=>Yd,json:()=>nf,iso:()=>Du,ipv6:()=>Kd,ipv4:()=>zd,intersection:()=>Bl,int64:()=>vl,int32:()=>dl,int:()=>sl,instanceof:()=>tf,includes:()=>Vs,httpUrl:()=>bd,hostname:()=>tl,hex:()=>rl,hash:()=>nl,guid:()=>pd,gte:()=>As,gt:()=>Cs,globalRegistry:()=>Oa,getErrorMap:()=>uf,function:()=>Vp,fromJSONSchema:()=>hf,formatError:()=>Te,float64:()=>ul,float32:()=>cl,flattenError:()=>Oe,file:()=>pp,exactOptional:()=>yp,enum:()=>sp,endsWith:()=>Bs,encodeAsync:()=>Yu,encode:()=>Gu,emoji:()=>$d,email:()=>dd,e164:()=>Gd,discriminatedUnion:()=>Vl,describe:()=>Qp,decodeAsync:()=>Qu,decode:()=>Xu,date:()=>Dl,custom:()=>Gp,cuid2:()=>xd,cuid:()=>Pd,core:()=>c,config:()=>m,coerce:()=>mf,codec:()=>Rp,clone:()=>G,cidrv6:()=>Wd,cidrv4:()=>Zd,check:()=>Bp,catch:()=>Cp,boolean:()=>fl,bigint:()=>ml,base64url:()=>qd,base64:()=>Hd,array:()=>zl,any:()=>Pl,_function:()=>Vp,_default:()=>Sp,_ZodString:()=>od,ZodXor:()=>Wl,ZodXID:()=>Cd,ZodVoid:()=>Cl,ZodUnknown:()=>El,ZodUnion:()=>Zl,ZodUndefined:()=>wl,ZodUUID:()=>fd,ZodURL:()=>yd,ZodULID:()=>Od,ZodType:()=>id,ZodTuple:()=>Gl,ZodTransform:()=>fp,ZodTemplateLiteral:()=>Kp,ZodSymbol:()=>_l,ZodSuccess:()=>xp,ZodStringFormat:()=>cd,ZodString:()=>ad,ZodSet:()=>ip,ZodRecord:()=>Yl,ZodRealError:()=>Fu,ZodReadonly:()=>Up,ZodPromise:()=>Wp,ZodPrefault:()=>kp,ZodPipe:()=>Dp,ZodOptional:()=>mp,ZodObject:()=>Ul,ZodNumberFormat:()=>al,ZodNumber:()=>il,ZodNullable:()=>_p,ZodNull:()=>Sl,ZodNonOptional:()=>Pp,ZodNever:()=>Ol,ZodNanoID:()=>Sd,ZodNaN:()=>Ap,ZodMap:()=>rp,ZodMAC:()=>Rd,ZodLiteral:()=>up,ZodLazy:()=>Zp,ZodKSUID:()=>jd,ZodJWT:()=>Xd,ZodIssueCode:()=>sf,ZodIntersection:()=>ql,ZodISOTime:()=>Mu,ZodISODuration:()=>Ju,ZodISODateTime:()=>Nu,ZodISODate:()=>Ru,ZodIPv6:()=>Md,ZodIPv4:()=>Nd,ZodGUID:()=>ld,ZodFunction:()=>Hp,ZodFirstPartyTypeKind:()=>af,ZodFile:()=>lp,ZodExactOptional:()=>vp,ZodError:()=>Wu,ZodEnum:()=>ap,ZodEmoji:()=>wd,ZodEmail:()=>ud,ZodE164:()=>Bd,ZodDiscriminatedUnion:()=>Hl,ZodDefault:()=>$p,ZodDate:()=>jl,ZodCustomStringFormat:()=>Qd,ZodCustom:()=>qp,ZodCodec:()=>zp,ZodCatch:()=>Tp,ZodCUID2:()=>Ed,ZodCUID:()=>Id,ZodCIDRv6:()=>Ld,ZodCIDRv4:()=>Jd,ZodBoolean:()=>pl,ZodBigIntFormat:()=>gl,ZodBigInt:()=>hl,ZodBase64URL:()=>Vd,ZodBase64:()=>Fd,ZodArray:()=>Nl,ZodAny:()=>Il,TimePrecision:()=>ts,NEVER:()=>u,$output:()=>Ia,$input:()=>Pa,$brand:()=>l});var c={};a(c,{version:()=>Mr,util:()=>g,treeifyError:()=>Ce,toJSONSchema:()=>Ou,toDotPath:()=>Ae,safeParseAsync:()=>Je,safeParse:()=>Me,safeEncodeAsync:()=>tt,safeEncode:()=>Xe,safeDecodeAsync:()=>nt,safeDecode:()=>Qe,registry:()=>xa,regexes:()=>it,process:()=>Uc,prettifyError:()=>je,parseAsync:()=>Re,parse:()=>Ne,meta:()=>Dc,locales:()=>xi,isValidJWT:()=>mn,isValidBase64URL:()=>pn,isValidBase64:()=>dn,initializeContext:()=>Rc,globalRegistry:()=>Oa,globalConfig:()=>h,formatError:()=>Te,flattenError:()=>Oe,finalize:()=>Kc,extractDefs:()=>Mc,encodeAsync:()=>Ve,encode:()=>Le,describe:()=>jc,decodeAsync:()=>Be,decode:()=>Fe,createToJSONSchemaMethod:()=>Zc,createStandardJSONSchemaMethod:()=>Lc,config:()=>m,clone:()=>G,_xor:()=>ac,_xid:()=>Wa,_void:()=>Is,_uuidv7:()=>Ra,_uuidv6:()=>za,_uuidv4:()=>Na,_uuid:()=>Da,_url:()=>Ua,_uppercase:()=>Hs,_unknown:()=>Ss,_union:()=>oc,_undefined:()=>bs,_ulid:()=>La,_uint64:()=>ys,_uint32:()=>ps,_tuple:()=>uc,_trim:()=>ec,_transform:()=>vc,_toUpperCase:()=>rc,_toLowerCase:()=>tc,_templateLiteral:()=>Pc,_symbol:()=>_s,_superRefine:()=>Cc,_success:()=>$c,_stringbool:()=>Nc,_stringFormat:()=>zc,_string:()=>Ta,_startsWith:()=>qs,_slugify:()=>nc,_size:()=>Ks,_set:()=>pc,_safeParseAsync:()=>Ke,_safeParse:()=>Ue,_safeEncodeAsync:()=>et,_safeEncode:()=>Ge,_safeDecodeAsync:()=>rt,_safeDecode:()=>Ye,_regex:()=>Ws,_refine:()=>Tc,_record:()=>dc,_readonly:()=>Ic,_property:()=>Gs,_promise:()=>xc,_positive:()=>js,_pipe:()=>kc,_parseAsync:()=>ze,_parse:()=>De,_overwrite:()=>Ys,_optional:()=>yc,_number:()=>as,_nullable:()=>_c,_null:()=>ws,_normalize:()=>Qs,_nonpositive:()=>Ns,_nonoptional:()=>wc,_nonnegative:()=>zs,_never:()=>ks,_negative:()=>Ds,_nativeEnum:()=>hc,_nanoid:()=>Ka,_nan:()=>xs,_multipleOf:()=>Rs,_minSize:()=>Ms,_minLength:()=>Zs,_min:()=>As,_mime:()=>Xs,_maxSize:()=>Us,_maxLength:()=>Js,_max:()=>Ts,_map:()=>lc,_mac:()=>qa,_lte:()=>Ts,_lt:()=>Os,_lowercase:()=>Fs,_literal:()=>mc,_length:()=>Ls,_lazy:()=>Ec,_ksuid:()=>Fa,_jwt:()=>es,_isoTime:()=>is,_isoDuration:()=>os,_isoDateTime:()=>rs,_isoDate:()=>ns,_ipv6:()=>Va,_ipv4:()=>Ha,_intersection:()=>cc,_int64:()=>vs,_int32:()=>ls,_int:()=>cs,_includes:()=>Vs,_guid:()=>ja,_gte:()=>As,_gt:()=>Cs,_float64:()=>ds,_float32:()=>us,_file:()=>gc,_enum:()=>fc,_endsWith:()=>Bs,_encodeAsync:()=>He,_encode:()=>Ze,_emoji:()=>Ma,_email:()=>Aa,_e164:()=>Qa,_discriminatedUnion:()=>sc,_default:()=>bc,_decodeAsync:()=>qe,_decode:()=>We,_date:()=>Ps,_custom:()=>Oc,_cuid2:()=>Za,_cuid:()=>Ja,_coercedString:()=>Ca,_coercedNumber:()=>ss,_coercedDate:()=>Es,_coercedBoolean:()=>hs,_coercedBigint:()=>gs,_cidrv6:()=>Ga,_cidrv4:()=>Ba,_check:()=>Ac,_catch:()=>Sc,_boolean:()=>fs,_bigint:()=>ms,_base64url:()=>Ya,_base64:()=>Xa,_array:()=>ic,_any:()=>$s,TimePrecision:()=>ts,NEVER:()=>u,JSONSchemaGenerator:()=>Tu,JSONSchema:()=>Cu,Doc:()=>Ur,$output:()=>Ia,$input:()=>Pa,$constructor:()=>d,$brand:()=>l,$ZodXor:()=>Jn,$ZodXID:()=>Yr,$ZodVoid:()=>On,$ZodUnknown:()=>En,$ZodUnion:()=>Mn,$ZodUndefined:()=>kn,$ZodUUID:()=>Wr,$ZodURL:()=>Hr,$ZodULID:()=>Xr,$ZodType:()=>Kr,$ZodTuple:()=>Hn,$ZodTransform:()=>ri,$ZodTemplateLiteral:()=>$i,$ZodSymbol:()=>Sn,$ZodSuccess:()=>pi,$ZodStringFormat:()=>Zr,$ZodString:()=>Jr,$ZodSet:()=>Xn,$ZodRegistry:()=>Ea,$ZodRecord:()=>qn,$ZodRealError:()=>xe,$ZodReadonly:()=>bi,$ZodPromise:()=>ki,$ZodPrefault:()=>ui,$ZodPipe:()=>mi,$ZodOptional:()=>ii,$ZodObjectJIT:()=>Rn,$ZodObject:()=>zn,$ZodNumberFormat:()=>_n,$ZodNumber:()=>yn,$ZodNullable:()=>ai,$ZodNull:()=>In,$ZodNonOptional:()=>di,$ZodNever:()=>xn,$ZodNanoID:()=>qr,$ZodNaN:()=>hi,$ZodMap:()=>Bn,$ZodMAC:()=>sn,$ZodLiteral:()=>ei,$ZodLazy:()=>Ii,$ZodKSUID:()=>Qr,$ZodJWT:()=>gn,$ZodIntersection:()=>Ln,$ZodISOTime:()=>rn,$ZodISODuration:()=>nn,$ZodISODateTime:()=>en,$ZodISODate:()=>tn,$ZodIPv6:()=>an,$ZodIPv4:()=>on,$ZodGUID:()=>Lr,$ZodFunction:()=>Si,$ZodFile:()=>ti,$ZodExactOptional:()=>oi,$ZodError:()=>Ee,$ZodEnum:()=>Qn,$ZodEncodeError:()=>f,$ZodEmoji:()=>Vr,$ZodEmail:()=>Fr,$ZodE164:()=>hn,$ZodDiscriminatedUnion:()=>Zn,$ZodDefault:()=>si,$ZodDate:()=>Tn,$ZodCustomStringFormat:()=>vn,$ZodCustom:()=>Pi,$ZodCodec:()=>vi,$ZodCheckUpperCase:()=>Tr,$ZodCheckStringFormat:()=>Er,$ZodCheckStartsWith:()=>Ar,$ZodCheckSizeEquals:()=>Sr,$ZodCheckRegex:()=>xr,$ZodCheckProperty:()=>Nr,$ZodCheckOverwrite:()=>Rr,$ZodCheckNumberFormat:()=>_r,$ZodCheckMultipleOf:()=>yr,$ZodCheckMinSize:()=>$r,$ZodCheckMinLength:()=>Ir,$ZodCheckMimeType:()=>zr,$ZodCheckMaxSize:()=>wr,$ZodCheckMaxLength:()=>kr,$ZodCheckLowerCase:()=>Or,$ZodCheckLessThan:()=>gr,$ZodCheckLengthEquals:()=>Pr,$ZodCheckIncludes:()=>Cr,$ZodCheckGreaterThan:()=>vr,$ZodCheckEndsWith:()=>jr,$ZodCheckBigIntFormat:()=>br,$ZodCheck:()=>hr,$ZodCatch:()=>fi,$ZodCUID2:()=>Gr,$ZodCUID:()=>Br,$ZodCIDRv6:()=>un,$ZodCIDRv4:()=>cn,$ZodBoolean:()=>bn,$ZodBigIntFormat:()=>$n,$ZodBigInt:()=>wn,$ZodBase64URL:()=>fn,$ZodBase64:()=>ln,$ZodAsyncError:()=>p,$ZodArray:()=>An,$ZodAny:()=>Pn});var u=Object.freeze({status:"aborted"});function d(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:a,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);let i=a.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){let t=o[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class o extends i{}function a(e){var t;let i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var l=Symbol("zod_brand");class p extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class f extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}var h={};function m(e){return e&&Object.assign(h,e),h}var g={};function v(e){return e}function y(e){return e}function _(e){}function b(e){throw Error("Unexpected value in exhaustive check")}function w(e){}function $(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 S(e,t="|"){return e.map(e=>Q(e)).join(t)}function k(e,t){return"bigint"==typeof t?t.toString():t}function I(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function P(e){return null==e}function E(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function x(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){let e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let o=r>i?r:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}a(g,{unwrapMessage:()=>pe,uint8ArrayToHex:()=>ke,uint8ArrayToBase64url:()=>$e,uint8ArrayToBase64:()=>be,stringifyPrimitive:()=>Q,slugify:()=>M,shallowClone:()=>W,safeExtend:()=>ae,required:()=>ue,randomString:()=>R,propertyKeyTypes:()=>V,promiseAllObject:()=>z,primitiveTypes:()=>q,prefixIssues:()=>le,pick:()=>ne,partial:()=>ce,parsedType:()=>ge,optionalKeys:()=>ee,omit:()=>ie,objectClone:()=>C,numKeys:()=>F,nullish:()=>P,normalizeParams:()=>X,mergeDefs:()=>j,merge:()=>se,jsonStringifyReplacer:()=>k,joinValues:()=>S,issue:()=>ve,isPlainObject:()=>L,isObject:()=>J,hexToUint8Array:()=>Se,getSizableOrigin:()=>he,getParsedType:()=>H,getLengthableOrigin:()=>me,getEnumValues:()=>$,getElementAtPath:()=>N,floatSafeRemainder:()=>x,finalizeIssue:()=>fe,extend:()=>oe,escapeRegex:()=>B,esc:()=>U,defineLazy:()=>T,createTransparentProxy:()=>Y,cloneDef:()=>D,clone:()=>G,cleanRegex:()=>E,cleanEnum:()=>ye,captureStackTrace:()=>K,cached:()=>I,base64urlToUint8Array:()=>we,base64ToUint8Array:()=>_e,assignProp:()=>A,assertNotEqual:()=>y,assertNever:()=>b,assertIs:()=>_,assertEqual:()=>v,assert:()=>w,allowsEval:()=>Z,aborted:()=>de,NUMBER_FORMAT_RANGES:()=>te,Class:()=>Ie,BIGINT_FORMAT_RANGES:()=>re});var O=Symbol("evaluating");function T(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==O)return void 0===n&&(n=O,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function C(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function A(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function j(...e){let t={};for(let r of e){let e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function D(e){return j(e._zod.def)}function N(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function z(e){let t=Object.keys(e),r=t.map(t=>e[t]);return Promise.all(r).then(e=>{let r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})}function R(e=10){let t="";for(let r=0;r<e;r++)t+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return t}function U(e){return JSON.stringify(e)}function M(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var K="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function J(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Z=I(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function L(e){if(!1===J(e))return!1;let t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;let r=t.prototype;return!1!==J(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function W(e){return L(e)?{...e}:Array.isArray(e)?[...e]:e}function F(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var H=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw Error(`Unknown data type: ${t}`)}},V=new Set(["string","number","symbol"]),q=new Set(["string","number","bigint","boolean","symbol","undefined"]);function B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G(e,t,r){let n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function X(e){let t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Y(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,o)=>(t??(t=e()),Reflect.set(t,n,i,o)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})}function Q(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function ee(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}var te={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},re={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ne(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");return G(e,j(e._zod.def,{get shape(){let e={};for(let n in t){if(!(n in r.shape))throw Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return A(this,"shape",e),e},checks:[]}))}function ie(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=j(e._zod.def,{get shape(){let n={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return A(this,"shape",n),n},checks:[]});return G(e,i)}function oe(e,t){if(!L(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=j(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return A(this,"shape",r),r}});return G(e,n)}function ae(e,t){if(!L(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=j(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return A(this,"shape",r),r}});return G(e,r)}function se(e,t){let r=j(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return A(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return G(e,r)}function ce(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=j(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(let t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return A(this,"shape",i),i},checks:[]});return G(t,i)}function ue(e,t,r){let n=j(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(let t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return A(this,"shape",i),i}});return G(t,n)}function de(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function le(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function pe(e){return"string"==typeof e?e:e?.message}function fe(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=pe(e.inst?._zod.def?.error?.(e))??pe(t?.error?.(e))??pe(r.customError?.(e))??pe(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function he(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function me(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ge(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}function ve(...e){let[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function ye(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function _e(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 be(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function we(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");return _e(t+"=".repeat((4-t.length%4)%4))}function $e(e){return be(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Se(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r}function ke(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}class Ie{constructor(...e){}}var Pe=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,k,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ee=d("$ZodError",Pe),xe=d("$ZodError",Pe,{Parent:Error});function Oe(e,t=e=>e.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Te(e,t=e=>e.message){let r={_errors:[]},n=e=>{for(let i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>n({issues:e}));else if("invalid_key"===i.code)n({issues:i.issues});else if("invalid_element"===i.code)n({issues:i.issues});else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){let r=i.path[n];n!==i.path.length-1?e[r]=e[r]||{_errors:[]}:(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))),e=e[r],n++}}};return n(e),r}function Ce(e,t=e=>e.message){let r={errors:[]},n=(e,i=[])=>{var o,a;for(let s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>n({issues:e},s.path));else if("invalid_key"===s.code)n({issues:s.issues},s.path);else if("invalid_element"===s.code)n({issues:s.issues},s.path);else{let e=[...i,...s.path];if(0===e.length){r.errors.push(t(s));continue}let n=r,c=0;for(;c<e.length;){let r=e[c],i=c===e.length-1;"string"==typeof r?(n.properties??(n.properties={}),(o=n.properties)[r]??(o[r]={errors:[]}),n=n.properties[r]):(n.items??(n.items=[]),(a=n.items)[r]??(a[r]={errors:[]}),n=n.items[r]),i&&n.errors.push(t(s)),c++}}};return n(e),r}function Ae(e){let t=[],r=e.map(e=>"object"==typeof e?e.key:e);for(let e of r)"number"==typeof e?t.push(`[${e}]`):"symbol"==typeof e?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push("."),t.push(e));return t.join("")}function je(e){let t=[],r=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of r)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Ae(e.path)}`);return t.join("\n")}var De=e=>(t,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new p;if(a.issues.length){let t=new(i?.Err??e)(a.issues.map(e=>fe(e,o,m())));throw K(t,i?.callee),t}return a.value},Ne=De(xe),ze=e=>async(t,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let t=new(i?.Err??e)(a.issues.map(e=>fe(e,o,m())));throw K(t,i?.callee),t}return a.value},Re=ze(xe),Ue=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new p;return o.issues.length?{success:!1,error:new(e??Ee)(o.issues.map(e=>fe(e,i,m())))}:{success:!0,data:o.value}},Me=Ue(xe),Ke=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>fe(e,i,m())))}:{success:!0,data:o.value}},Je=Ke(xe),Ze=e=>(t,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return De(e)(t,r,i)},Le=Ze(xe),We=e=>(t,r,n)=>De(e)(t,r,n),Fe=We(xe),He=e=>async(t,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ze(e)(t,r,i)},Ve=He(xe),qe=e=>async(t,r,n)=>ze(e)(t,r,n),Be=qe(xe),Ge=e=>(t,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Ue(e)(t,r,i)},Xe=Ge(xe),Ye=e=>(t,r,n)=>Ue(e)(t,r,n),Qe=Ye(xe),et=e=>async(t,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Ke(e)(t,r,i)},tt=et(xe),rt=e=>async(t,r,n)=>Ke(e)(t,r,n),nt=rt(xe),it={};a(it,{xid:()=>ct,uuid7:()=>vt,uuid6:()=>gt,uuid4:()=>mt,uuid:()=>ht,uppercase:()=>Bt,unicodeEmail:()=>wt,undefined:()=>Vt,ulid:()=>st,time:()=>Mt,string:()=>Jt,sha512_hex:()=>lr,sha512_base64url:()=>fr,sha512_base64:()=>pr,sha384_hex:()=>cr,sha384_base64url:()=>dr,sha384_base64:()=>ur,sha256_hex:()=>or,sha256_base64url:()=>sr,sha256_base64:()=>ar,sha1_hex:()=>rr,sha1_base64url:()=>ir,sha1_base64:()=>nr,rfc5322Email:()=>bt,number:()=>Wt,null:()=>Ht,nanoid:()=>dt,md5_hex:()=>Qt,md5_base64url:()=>tr,md5_base64:()=>er,mac:()=>xt,lowercase:()=>qt,ksuid:()=>ut,ipv6:()=>Et,ipv4:()=>Pt,integer:()=>Lt,idnEmail:()=>$t,html5Email:()=>_t,hostname:()=>jt,hex:()=>Gt,guid:()=>ft,extendedDuration:()=>pt,emoji:()=>It,email:()=>yt,e164:()=>Nt,duration:()=>lt,domain:()=>Dt,datetime:()=>Kt,date:()=>Rt,cuid2:()=>at,cuid:()=>ot,cidrv6:()=>Tt,cidrv4:()=>Ot,browserEmail:()=>St,boolean:()=>Ft,bigint:()=>Zt,base64url:()=>At,base64:()=>Ct});var ot=/^[cC][^\s-]{8,}$/,at=/^[0-9a-z]+$/,st=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ct=/^[0-9a-vA-V]{20}$/,ut=/^[A-Za-z0-9]{27}$/,dt=/^[a-zA-Z0-9_-]{21}$/,lt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,pt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ft=/^([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})$/,ht=e=>e?new 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)$/,mt=ht(4),gt=ht(6),vt=ht(7),yt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_t=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,bt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,wt=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$t=wt,St=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,kt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function It(){return new RegExp(kt,"u")}var Pt=/^(?:(?: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])$/,Et=/^(([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}|:))$/,xt=e=>{let t=B(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Ot=/^((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])$/,Tt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ct=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,At=/^[A-Za-z0-9_-]*$/,jt=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Dt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Nt=/^\+[1-9]\d{6,14}$/,zt="(?:(?:\\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])))",Rt=new RegExp(`^${zt}$`);function Ut(e){return"number"==typeof e.precision?-1===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Mt(e){return new RegExp(`^${Ut(e)}$`)}function Kt(e){let t=Ut({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${zt}T(?:${n})$`)}var Jt=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),Zt=/^-?\d+n?$/,Lt=/^-?\d+$/,Wt=/^-?\d+(?:\.\d+)?$/,Ft=/^(?:true|false)$/i,Ht=/^null$/i,Vt=/^undefined$/i,qt=/^[^A-Z]*$/,Bt=/^[^a-z]*$/,Gt=/^[0-9a-fA-F]*$/;function Xt(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Yt(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Qt=/^[0-9a-fA-F]{32}$/,er=Xt(22,"=="),tr=Yt(22),rr=/^[0-9a-fA-F]{40}$/,nr=Xt(27,"="),ir=Yt(27),or=/^[0-9a-fA-F]{64}$/,ar=Xt(43,"="),sr=Yt(43),cr=/^[0-9a-fA-F]{96}$/,ur=Xt(64,""),dr=Yt(64),lr=/^[0-9a-fA-F]{128}$/,pr=Xt(86,"=="),fr=Yt(86),hr=d("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),mr={number:"number",bigint:"bigint",object:"date"},gr=d("$ZodCheckLessThan",(e,t)=>{hr.init(e,t);let r=mr[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vr=d("$ZodCheckGreaterThan",(e,t)=>{hr.init(e,t);let r=mr[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yr=d("$ZodCheckMultipleOf",(e,t)=>{hr.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value!==BigInt(0):0!==x(r.value,t.value))&&r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),_r=d("$ZodCheckNumberFormat",(e,t)=>{hr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,o]=te[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=o,r&&(n.pattern=Lt)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s))return void a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}))}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),br=d("$ZodCheckBigIntFormat",(e,t)=>{hr.init(e,t);let[r,n]=re[t.format];e._zod.onattach.push(e=>{let i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{let o=i.value;o<r&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),o>n&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),wr=d("$ZodCheckMaxSize",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;n.size<=t.maximum||r.issues.push({origin:he(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$r=d("$ZodCheckMinSize",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;n.size>=t.minimum||r.issues.push({origin:he(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Sr=d("$ZodCheckSizeEquals",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let n=r.value,i=n.size;if(i===t.size)return;let o=i>t.size;r.issues.push({origin:he(n),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),kr=d("$ZodCheckMaxLength",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;if(n.length<=t.maximum)return;let i=me(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Ir=d("$ZodCheckMinLength",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;if(n.length>=t.minimum)return;let i=me(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Pr=d("$ZodCheckLengthEquals",(e,t)=>{var r;hr.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!P(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let n=r.value,i=n.length;if(i===t.length)return;let o=me(n),a=i>t.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Er=d("$ZodCheckStringFormat",(e,t)=>{var r,n;hr.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),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})}):(n=e._zod).check??(n.check=()=>{})}),xr=d("$ZodCheckRegex",(e,t)=>{Er.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})}}),Or=d("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=qt),Er.init(e,t)}),Tr=d("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bt),Er.init(e,t)}),Cr=d("$ZodCheckIncludes",(e,t)=>{hr.init(e,t);let r=B(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),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})}}),Ar=d("$ZodCheckStartsWith",(e,t)=>{hr.init(e,t);let r=new RegExp(`^${B(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}}),jr=d("$ZodCheckEndsWith",(e,t)=>{hr.init(e,t);let r=new RegExp(`.*${B(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(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})}});function Dr(e,t,r){e.issues.length&&t.issues.push(...le(r,e.issues))}var Nr=d("$ZodCheckProperty",(e,t)=>{hr.init(e,t),e._zod.check=e=>{let r=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(r=>Dr(r,e,t.property));Dr(r,e,t.property)}}),zr=d("$ZodCheckMimeType",(e,t)=>{hr.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),Rr=d("$ZodCheckOverwrite",(e,t)=>{hr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Ur{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(let e of n)this.content.push(e)}compile(){let e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}var Mr={major:4,minor:3,patch:5},Kr=d("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Mr;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let t of n)for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,i=de(e);for(let o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===r?.async)throw new p;if(n||a instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(i||(i=de(e,t)))});else{if(e.issues.length===t)continue;i||(i=de(e,t))}}return n?n.then(()=>e):e},r=(r,i,o)=>{if(de(r))return r.aborted=!0,r;let a=t(i,n,o);if(a instanceof Promise){if(!1===o.async)throw new p;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){let t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,o)):r(t,i,o)}let a=e._zod.parse(i,o);if(a instanceof Promise){if(!1===o.async)throw new p;return a.then(e=>t(e,n,o))}return t(a,n,o)}}T(e,"~standard",()=>({validate:t=>{try{let r=Me(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Je(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Jr=d("$ZodString",(e,t)=>{Kr.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jt(e._zod.bag),e._zod.parse=(r,n)=>{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}}),Zr=d("$ZodStringFormat",(e,t)=>{Er.init(e,t),Jr.init(e,t)}),Lr=d("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ft),Zr.init(e,t)}),Wr=d("$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=ht(e))}else t.pattern??(t.pattern=ht());Zr.init(e,t)}),Fr=d("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yt),Zr.init(e,t)}),Hr=d("$ZodURL",(e,t)=>{Zr.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),i=new URL(n);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(t.normalize?r.value=i.href:r.value=n)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Vr=d("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=It()),Zr.init(e,t)}),qr=d("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=dt),Zr.init(e,t)}),Br=d("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ot),Zr.init(e,t)}),Gr=d("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=at),Zr.init(e,t)}),Xr=d("$ZodULID",(e,t)=>{t.pattern??(t.pattern=st),Zr.init(e,t)}),Yr=d("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ct),Zr.init(e,t)}),Qr=d("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ut),Zr.init(e,t)}),en=d("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Kt(t)),Zr.init(e,t)}),tn=d("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Rt),Zr.init(e,t)}),rn=d("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Mt(t)),Zr.init(e,t)}),nn=d("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=lt),Zr.init(e,t)}),on=d("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Pt),Zr.init(e,t),e._zod.bag.format="ipv4"}),an=d("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Et),Zr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),sn=d("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=xt(t.delimiter)),Zr.init(e,t),e._zod.bag.format="mac"}),cn=d("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ot),Zr.init(e,t)}),un=d("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Tt),Zr.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(2!==n.length)throw Error();let[e,t]=n;if(!t)throw Error();let r=Number(t);if(`${r}`!==t)throw Error();if(r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function dn(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var ln=d("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ct),Zr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{dn(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function pn(e){if(!At.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return dn(t.padEnd(4*Math.ceil(t.length/4),"="))}var fn=d("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=At),Zr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{pn(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),hn=d("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Nt),Zr.init(e,t)});function mn(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var gn=d("$ZodJWT",(e,t)=>{Zr.init(e,t),e._zod.check=r=>{mn(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),vn=d("$ZodCustomStringFormat",(e,t)=>{Zr.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),yn=d("$ZodNumber",(e,t)=>{Kr.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wt,e._zod.parse=(r,n)=>{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 o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),_n=d("$ZodNumberFormat",(e,t)=>{_r.init(e,t),yn.init(e,t)}),bn=d("$ZodBoolean",(e,t)=>{Kr.init(e,t),e._zod.pattern=Ft,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(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}}),wn=d("$ZodBigInt",(e,t)=>{Kr.init(e,t),e._zod.pattern=Zt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),$n=d("$ZodBigIntFormat",(e,t)=>{br.init(e,t),wn.init(e,t)}),Sn=d("$ZodSymbol",(e,t)=>{Kr.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return"symbol"==typeof n||t.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),t}}),kn=d("$ZodUndefined",(e,t)=>{Kr.init(e,t),e._zod.pattern=Vt,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,r)=>{let n=t.value;return typeof n>"u"||t.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),t}}),In=d("$ZodNull",(e,t)=>{Kr.init(e,t),e._zod.pattern=Ht,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),Pn=d("$ZodAny",(e,t)=>{Kr.init(e,t),e._zod.parse=e=>e}),En=d("$ZodUnknown",(e,t)=>{Kr.init(e,t),e._zod.parse=e=>e}),xn=d("$ZodNever",(e,t)=>{Kr.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),On=d("$ZodVoid",(e,t)=>{Kr.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return typeof n>"u"||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}}),Tn=d("$ZodDate",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),r}});function Cn(e,t,r){e.issues.length&&t.issues.push(...le(r,e.issues)),t.value[r]=e.value}var An=d("$ZodArray",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let o=[];for(let e=0;e<i.length;e++){let a=i[e],s=t.element._zod.run({value:a,issues:[]},n);s instanceof Promise?o.push(s.then(t=>Cn(t,r,e))):Cn(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function jn(e,t,r,n,i){if(e.issues.length){if(i&&!(r in n))return;t.issues.push(...le(r,e.issues))}void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Dn(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=ee(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Nn(e,t,r,n,i,o){let a=[],s=i.keySet,c=i.catchall._zod,u=c.def.type,d="optional"===c.optout;for(let i in t){if(s.has(i))continue;if("never"===u){a.push(i);continue}let o=c.run({value:t[i],issues:[]},n);o instanceof Promise?e.push(o.then(e=>jn(e,r,i,t,d))):jn(o,r,i,t,d)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}var zn=d("$ZodObject",(e,t)=>{if(Kr.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let r=I(()=>Dn(t));T(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(let e of n.values)r[t].add(e)}}return r});let n,i=J,o=t.catchall;e._zod.parse=(t,a)=>{n??(n=r.value);let s=t.value;if(!i(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let c=[],u=n.shape;for(let e of n.keys){let r=u[e],n="optional"===r._zod.optout,i=r._zod.run({value:s[e],issues:[]},a);i instanceof Promise?c.push(i.then(r=>jn(r,t,e,s,n))):jn(i,t,e,s,n)}return o?Nn(c,s,t,a,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),Rn=d("$ZodObjectJIT",(e,t)=>{zn.init(e,t);let r,n,i=e._zod.parse,o=I(()=>Dn(t)),a=J,s=!h.jitless,c=s&&Z.value,u=t.catchall;e._zod.parse=(d,l)=>{n??(n=o.value);let p=d.value;return a(p)?s&&c&&!1===l?.async&&!0!==l.jitless?(r||(r=(e=>{let t=new Ur(["shape","payload","ctx"]),r=o.value,n=e=>{let t=U(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),a=0;for(let e of r.keys)i[e]="key_"+a++;t.write("const newResult = {};");for(let o of r.keys){let r=i[o],a=U(o),s="optional"===e[o]?._zod?.optout;t.write(`const ${r} = ${n(o)};`),s?t.write(`\n if (${r}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${r}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${r}.value;\n }\n \n `):t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),d=r(d,l),u?Nn([],p,d,l,n,e):d):i(d,l):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function Un(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!de(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>fe(e,n,m())))}),t)}var Mn=d("$ZodUnion",(e,t)=>{Kr.init(e,t),T(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),T(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),T(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),T(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>E(e.source)).join("|")})$`)}});let r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let a=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Un(t,i,e,o)):Un(s,i,e,o)}});function Kn(e,t,r,n){let i=e.filter(e=>0===e.issues.length);return 1===i.length?(t.value=i[0].value,t):(0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>fe(e,n,m())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}var Jn=d("$ZodXor",(e,t)=>{Mn.init(e,t),t.inclusive=!1;let r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let a=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},o);t instanceof Promise?(s.push(t),a=!0):s.push(t)}return a?Promise.all(s).then(t=>Kn(t,i,e,o)):Kn(s,i,e,o)}}),Zn=d("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Mn.init(e,t);let r=e._zod.parse;T(e._zod,"propValues",()=>{let e={};for(let r of t.options){let n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(let n of r)e[t].add(n)}}return e});let n=I(()=>{let e=t.options,r=new Map;for(let n of e){let e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,o)=>{let a=i.value;if(!J(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;let s=n.value.get(a?.[t.discriminator]);return s?s._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),i)}}),Ln=d("$ZodIntersection",(e,t)=>{Kr.init(e,t),e._zod.parse=(e,r)=>{let n=e.value,i=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,r])=>Fn(e,t,r)):Fn(e,i,o)}});function Wn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(L(e)&&L(t)){let r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(let r of n){let n=Wn(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=Wn(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fn(e,t,r){let n,i=new Map;for(let r of t.issues)if("unrecognized_keys"===r.code){n??(n=r);for(let e of r.keys)i.has(e)||i.set(e,{}),i.get(e).l=!0}else e.issues.push(r);for(let t of r.issues)if("unrecognized_keys"===t.code)for(let e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);let o=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&n&&e.issues.push({...n,keys:o}),de(e))return e;let a=Wn(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Hn=d("$ZodTuple",(e,t)=>{Kr.init(e,t);let r=t.items;e._zod.parse=(n,i)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let a=[],s=[...r].reverse().findIndex(e=>"optional"!==e._zod.optin),c=-1===s?0:r.length-s;if(!t.rest){let t=o.length>r.length,i=o.length<c-1;if(t||i)return n.issues.push({...t?{code:"too_big",maximum:r.length,inclusive:!0}:{code:"too_small",minimum:r.length},input:o,inst:e,origin:"array"}),n}let u=-1;for(let e of r){if(u++,u>=o.length&&u>=c)continue;let t=e._zod.run({value:o[u],issues:[]},i);t instanceof Promise?a.push(t.then(e=>Vn(e,n,u))):Vn(t,n,u)}if(t.rest){let e=o.slice(r.length);for(let r of e){u++;let e=t.rest._zod.run({value:r,issues:[]},i);e instanceof Promise?a.push(e.then(e=>Vn(e,n,u))):Vn(e,n,u)}}return a.length?Promise.all(a).then(()=>n):n}});function Vn(e,t,r){e.issues.length&&t.issues.push(...le(r,e.issues)),t.value[r]=e.value}var qn=d("$ZodRecord",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!L(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let o=[],a=t.keyType._zod.values;if(a){r.value={};let s,c=new Set;for(let e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){c.add("number"==typeof e?e.toString():e);let a=t.valueType._zod.run({value:i[e],issues:[]},n);a instanceof Promise?o.push(a.then(t=>{t.issues.length&&r.issues.push(...le(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...le(e,a.issues)),r.value[e]=a.value)}for(let e in i)c.has(e)||(s=s??[],s.push(e));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:s})}else{r.value={};for(let a of Reflect.ownKeys(i)){if("__proto__"===a)continue;let s=t.keyType._zod.run({value:a,issues:[]},n);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Wt.test(a)&&s.issues.length&&s.issues.some(e=>"invalid_type"===e.code&&"number"===e.expected)){let e=t.keyType._zod.run({value:Number(a),issues:[]},n);if(e instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?r.value[a]=i[a]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>fe(e,n,m())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:i[a],issues:[]},n);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&r.issues.push(...le(a,e.issues)),r.value[s.value]=e.value})):(c.issues.length&&r.issues.push(...le(a,c.issues)),r.value[s.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Bn=d("$ZodMap",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let o=[];r.value=new Map;for(let[a,s]of i){let c=t.keyType._zod.run({value:a,issues:[]},n),u=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||u instanceof Promise?o.push(Promise.all([c,u]).then(([t,o])=>{Gn(t,o,r,a,i,e,n)})):Gn(c,u,r,a,i,e,n)}return o.length?Promise.all(o).then(()=>r):r}});function Gn(e,t,r,n,i,o,a){e.issues.length&&(V.has(typeof n)?r.issues.push(...le(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(e=>fe(e,a,m()))})),t.issues.length&&(V.has(typeof n)?r.issues.push(...le(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:n,issues:t.issues.map(e=>fe(e,a,m()))})),r.value.set(e.value,t.value)}var Xn=d("$ZodSet",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let o=[];r.value=new Set;for(let e of i){let i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?o.push(i.then(e=>Yn(e,r))):Yn(i,r)}return o.length?Promise.all(o).then(()=>r):r}});function Yn(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Qn=d("$ZodEnum",(e,t)=>{Kr.init(e,t);let r=$(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(e=>V.has(typeof e)).map(e=>"string"==typeof e?B(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{let o=t.value;return n.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),ei=d("$ZodLiteral",(e,t)=>{if(Kr.init(e,t),0===t.values.length)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?B(e):e?B(e.toString()):String(e)).join("|")})$`),e._zod.parse=(n,i)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),ti=d("$ZodFile",(e,t)=>{Kr.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return n instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),t}}),ri=d("$ZodTransform",(e,t)=>{Kr.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new f(e.constructor.name);let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(r.value=e,r));if(i instanceof Promise)throw new p;return r.value=i,r}});function ni(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}var ii=d("$ZodOptional",(e,t)=>{Kr.init(e,t),e._zod.optin="optional",e._zod.optout="optional",T(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),T(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?new RegExp(`^(${E(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>ni(t,e.value)):ni(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),oi=d("$ZodExactOptional",(e,t)=>{ii.init(e,t),T(e._zod,"values",()=>t.innerType._zod.values),T(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),ai=d("$ZodNullable",(e,t)=>{Kr.init(e,t),T(e._zod,"optin",()=>t.innerType._zod.optin),T(e._zod,"optout",()=>t.innerType._zod.optout),T(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?new RegExp(`^(${E(e.source)}|null)$`):void 0}),T(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),si=d("$ZodDefault",(e,t)=>{Kr.init(e,t),e._zod.optin="optional",T(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>ci(e,t)):ci(n,t)}});function ci(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var ui=d("$ZodPrefault",(e,t)=>{Kr.init(e,t),e._zod.optin="optional",T(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),di=d("$ZodNonOptional",(e,t)=>{Kr.init(e,t),T(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>li(t,e)):li(i,e)}});function li(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var pi=d("$ZodSuccess",(e,t)=>{Kr.init(e,t),e._zod.parse=(e,r)=>{if("backward"===r.direction)throw new f("ZodSuccess");let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}}),fi=d("$ZodCatch",(e,t)=>{Kr.init(e,t),T(e._zod,"optin",()=>t.innerType._zod.optin),T(e._zod,"optout",()=>t.innerType._zod.optout),T(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>fe(e,r,m()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>fe(e,r,m()))},input:e.value}),e.issues=[]),e)}}),hi=d("$ZodNaN",(e,t)=>{Kr.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),mi=d("$ZodPipe",(e,t)=>{Kr.init(e,t),T(e._zod,"values",()=>t.in._zod.values),T(e._zod,"optin",()=>t.in._zod.optin),T(e._zod,"optout",()=>t.out._zod.optout),T(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>gi(e,t.in,r)):gi(n,t.in,r)}let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>gi(e,t.out,r)):gi(n,t.out,r)}});function gi(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var vi=d("$ZodCodec",(e,t)=>{Kr.init(e,t),T(e._zod,"values",()=>t.in._zod.values),T(e._zod,"optin",()=>t.in._zod.optin),T(e._zod,"optout",()=>t.out._zod.optout),T(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("forward"===(r.direction||"forward")){let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>yi(e,t,r)):yi(n,t,r)}{let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>yi(e,t,r)):yi(n,t,r)}}});function yi(e,t,r){if(e.issues.length)return e.aborted=!0,e;if("forward"===(r.direction||"forward")){let n=t.transform(e.value,e);return n instanceof Promise?n.then(n=>_i(e,n,t.out,r)):_i(e,n,t.out,r)}{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(n=>_i(e,n,t.in,r)):_i(e,n,t.in,r)}}function _i(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}var bi=d("$ZodReadonly",(e,t)=>{Kr.init(e,t),T(e._zod,"propValues",()=>t.innerType._zod.propValues),T(e._zod,"values",()=>t.innerType._zod.values),T(e._zod,"optin",()=>t.innerType?._zod?.optin),T(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(wi):wi(n)}});function wi(e){return e.value=Object.freeze(e.value),e}var $i=d("$ZodTemplateLiteral",(e,t)=>{Kr.init(e,t);let r=[];for(let e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let n=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else{if(null!==e&&!q.has(typeof e))throw Error(`Invalid template literal part: ${e}`);r.push(B(`${e}`))}e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>"string"!=typeof r.value?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),Si=d("$ZodFunction",(e,t)=>(Kr.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if("function"!=typeof t)throw Error("implement() must be called with a function");return function(...r){let n=e._def.input?Ne(e._def.input,r):r,i=Reflect.apply(t,this,n);return e._def.output?Ne(e._def.output,i):i}},e.implementAsync=t=>{if("function"!=typeof t)throw Error("implementAsync() must be called with a function");return async function(...r){let n=e._def.input?await Re(e._def.input,r):r,i=await Reflect.apply(t,this,n);return e._def.output?await Re(e._def.output,i):i}},e._zod.parse=(t,r)=>"function"!=typeof t.value?(t.issues.push({code:"invalid_type",expected:"function",input:t.value,inst:e}),t):(e._def.output&&"promise"===e._def.output._zod.def.type?t.value=e.implementAsync(t.value):t.value=e.implement(t.value),t),e.input=(...t)=>{let r=e.constructor;return Array.isArray(t[0])?new r({type:"function",input:new Hn({type:"tuple",items:t[0],rest:t[1]}),output:e._def.output}):new r({type:"function",input:t[0],output:e._def.output})},e.output=t=>new e.constructor({type:"function",input:e._def.input,output:t}),e)),ki=d("$ZodPromise",(e,t)=>{Kr.init(e,t),e._zod.parse=(e,r)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},r))}),Ii=d("$ZodLazy",(e,t)=>{Kr.init(e,t),T(e._zod,"innerType",()=>t.getter()),T(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),T(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),T(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),T(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),Pi=d("$ZodCustom",(e,t)=>{hr.init(e,t),Kr.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>Ei(t,r,n,e));Ei(i,r,n,e)}});function Ei(e,t,r,n){if(!e){let e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(ve(e))}}var xi={};a(xi,{zhTW:()=>wa,zhCN:()=>_a,yo:()=>Sa,vi:()=>va,uz:()=>ma,ur:()=>fa,uk:()=>da,ua:()=>la,tr:()=>ca,th:()=>aa,ta:()=>ia,sv:()=>ra,sl:()=>ea,ru:()=>Yo,pt:()=>Bo,ps:()=>Fo,pl:()=>Vo,ota:()=>Lo,no:()=>Jo,nl:()=>Mo,ms:()=>Ro,mk:()=>No,lt:()=>jo,ko:()=>Oo,km:()=>Po,kh:()=>Eo,ka:()=>ko,ja:()=>$o,it:()=>bo,is:()=>yo,id:()=>go,hy:()=>ho,hu:()=>uo,he:()=>so,frCA:()=>oo,fr:()=>no,fi:()=>to,fa:()=>Qi,es:()=>Xi,eo:()=>Bi,en:()=>Vi,de:()=>Fi,da:()=>Li,cs:()=>Ji,ca:()=>Mi,bg:()=>Ri,be:()=>Ni,az:()=>Ai,ar:()=>Ti});var Oi=()=>{let e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}let r={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`مدخلات غير مقبولة: يفترض إدخال instanceof ${e.expected}، ولكن تم إدخال ${i}`:`مدخلات غير مقبولة: يفترض إدخال ${t}، ولكن تم إدخال ${i}`}case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${Q(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()} ${n.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()} ${n.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${r[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${S(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};function Ti(){return{localeError:Oi()}}var Ci=()=>{let e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Yanlış dəyər: gözlənilən instanceof ${e.expected}, daxil olan ${i}`:`Yanlış dəyər: gözlənilən ${t}, daxil olan ${i}`}case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${Q(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()} ${n.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${r[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function Ai(){return{localeError:Ci()}}function ji(e,t,r,n){let i=Math.abs(e),o=i%10,a=i%100;return a>=11&&a<=19?n:1===o?t:o>=2&&o<=4?r:n}var Di=()=>{let e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}let r={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},n={nan:"NaN",number:"лік",array:"масіў"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Няправільны ўвод: чакаўся instanceof ${e.expected}, атрымана ${i}`:`Няправільны ўвод: чакаўся ${t}, атрымана ${i}`}case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${Q(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);if(n){let t=ji(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${n.verb} ${r}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);if(n){let t=ji(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${n.verb} ${r}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${r[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${S(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};function Ni(){return{localeError:Di()}}var zi=()=>{let e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function t(t){return e[t]??null}let r={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},n={nan:"NaN",number:"число",array:"масив"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Невалиден вход: очакван instanceof ${e.expected}, получен ${i}`:`Невалиден вход: очакван ${t}, получен ${i}`}case"invalid_value":return 1===e.values.length?`Невалиден вход: очакван ${Q(e.values[0])}`:`Невалидна опция: очаквано едно от ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Твърде голямо: очаква се ${e.origin??"стойност"} да съдържа ${r}${e.maximum.toString()} ${n.unit??"елемента"}`:`Твърде голямо: очаква се ${e.origin??"стойност"} да бъде ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Твърде малко: очаква се ${e.origin} да съдържа ${r}${e.minimum.toString()} ${n.unit}`:`Твърде малко: очаква се ${e.origin} да бъде ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;if("starts_with"===t.format)return`Невалиден низ: трябва да започва с "${t.prefix}"`;if("ends_with"===t.format)return`Невалиден низ: трябва да завършва с "${t.suffix}"`;if("includes"===t.format)return`Невалиден низ: трябва да включва "${t.includes}"`;if("regex"===t.format)return`Невалиден низ: трябва да съвпада с ${t.pattern}`;let n="Невалиден";return"emoji"===t.format&&(n="Невалидно"),"datetime"===t.format&&(n="Невалидно"),"date"===t.format&&(n="Невалидна"),"time"===t.format&&(n="Невалидно"),"duration"===t.format&&(n="Невалидна"),`${n} ${r[t.format]??e.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${e.divisor}`;case"unrecognized_keys":return`Неразпознат${e.keys.length>1?"и":""} ключ${e.keys.length>1?"ове":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${e.origin}`;case"invalid_union":default:return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${e.origin}`}}};function Ri(){return{localeError:zi()}}var Ui=()=>{let e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}let r={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Tipus invàlid: s'esperava instanceof ${e.expected}, s'ha rebut ${i}`:`Tipus invàlid: s'esperava ${t}, s'ha rebut ${i}`}case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${Q(e.values[0])}`:`Opció invàlida: s'esperava una de ${S(e.values," o ")}`;case"too_big":{let r=e.inclusive?"com a màxim":"menys de",n=t(e.origin);return n?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${r} ${e.maximum.toString()} ${n.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${r} ${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?"com a mínim":"més de",n=t(e.origin);return n?`Massa petit: s'esperava que ${e.origin} contingués ${r} ${e.minimum.toString()} ${n.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${r} ${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${r[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};function Mi(){return{localeError:Ui()}}var Ki=()=>{let e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}let r={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},n={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Neplatný vstup: očekáváno instanceof ${e.expected}, obdrženo ${i}`:`Neplatný vstup: očekáváno ${t}, obdrženo ${i}`}case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${Q(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${r}${e.maximum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${r}${e.minimum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${r[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${S(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};function Ji(){return{localeError:Ki()}}var Zi=()=>{let e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function t(t){return e[t]??null}let r={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},n={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ugyldigt input: forventede instanceof ${e.expected}, fik ${i}`:`Ugyldigt input: forventede ${t}, fik ${i}`}case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${Q(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",i=t(e.origin),o=n[e.origin]??e.origin;return i?`For stor: forventede ${o??"value"} ${i.verb} ${r} ${e.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${o??"value"} havde ${r} ${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",i=t(e.origin),o=n[e.origin]??e.origin;return i?`For lille: forventede ${o} ${i.verb} ${r} ${e.minimum.toString()} ${i.unit}`:`For lille: forventede ${o} havde ${r} ${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${r[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${S(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};function Li(){return{localeError:Zi()}}var Wi=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}let r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},n={nan:"NaN",number:"Zahl",array:"Array"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ungültige Eingabe: erwartet instanceof ${e.expected}, erhalten ${i}`:`Ungültige Eingabe: erwartet ${t}, erhalten ${i}`}case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${Q(e.values[0])}`:`Ungültige Option: erwartet eine von ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ${n.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ist`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ${n.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ist`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${S(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};function Fi(){return{localeError:Wi()}}var Hi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(t){return e[t]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input);return`Invalid input: expected ${t}, received ${n[r]??r}`}case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Q(e.values[0])}`:`Invalid option: expected one of ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Too big: expected ${e.origin??"value"} to have ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Too small: expected ${e.origin} to have ${r}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function Vi(){return{localeError:Hi()}}var qi=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}let r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},n={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Nevalida enigo: atendiĝis instanceof ${e.expected}, riceviĝis ${i}`:`Nevalida enigo: atendiĝis ${t}, riceviĝis ${i}`}case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${Q(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()} ${n.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Tro malgranda: atendiĝis ke ${e.origin} havu ${r}${e.minimum.toString()} ${n.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${r[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};function Bi(){return{localeError:qi()}}var Gi=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}let r={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Entrada inválida: se esperaba instanceof ${e.expected}, recibido ${i}`:`Entrada inválida: se esperaba ${t}, recibido ${i}`}case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${Q(e.values[0])}`:`Opción inválida: se esperaba una de ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",i=t(e.origin),o=n[e.origin]??e.origin;return i?`Demasiado grande: se esperaba que ${o??"valor"} tuviera ${r}${e.maximum.toString()} ${i.unit??"elementos"}`:`Demasiado grande: se esperaba que ${o??"valor"} fuera ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",i=t(e.origin),o=n[e.origin]??e.origin;return i?`Demasiado pequeño: se esperaba que ${o} tuviera ${r}${e.minimum.toString()} ${i.unit}`:`Demasiado pequeño: se esperaba que ${o} fuera ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${r[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${n[e.origin]??e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${n[e.origin]??e.origin}`}}};function Xi(){return{localeError:Gi()}}var Yi=()=>{let e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}let r={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},n={nan:"NaN",number:"عدد",array:"آرایه"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`ورودی نامعتبر: می‌بایست instanceof ${e.expected} می‌بود، ${i} دریافت شد`:`ورودی نامعتبر: می‌بایست ${t} می‌بود، ${i} دریافت شد`}case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: می‌بایست ${Q(e.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${S(e.values,"|")} می‌بود`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} باشد`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} باشد`}case"invalid_format":{let t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${r[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${S(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};function Qi(){return{localeError:Yi()}}var eo=()=>{let e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}let r={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Virheellinen tyyppi: odotettiin instanceof ${e.expected}, oli ${i}`:`Virheellinen tyyppi: odotettiin ${t}, oli ${i}`}case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${Q(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Liian suuri: ${n.subject} täytyy olla ${r}${e.maximum.toString()} ${n.unit}`.trim():`Liian suuri: arvon täytyy olla ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Liian pieni: ${n.subject} täytyy olla ${r}${e.minimum.toString()} ${n.unit}`.trim():`Liian pieni: arvon täytyy olla ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${r[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${S(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function to(){return{localeError:eo()}}var ro=()=>{let e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}let r={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},n={nan:"NaN",number:"nombre",array:"tableau"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Entrée invalide : instanceof ${e.expected} attendu, ${i} reçu`:`Entrée invalide : ${t} attendu, ${i} reçu`}case"invalid_value":return 1===e.values.length?`Entrée invalide : ${Q(e.values[0])} attendu`:`Option invalide : une valeur parmi ${S(e.values,"|")} attendue`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Trop grand : ${e.origin??"valeur"} doit ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Trop petit : ${e.origin} doit ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : ${e.origin} doit être ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${S(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function no(){return{localeError:ro()}}var io=()=>{let e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}let r={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Entrée invalide : attendu instanceof ${e.expected}, reçu ${i}`:`Entrée invalide : attendu ${t}, reçu ${i}`}case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${Q(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"≤":"<",n=t(e.origin);return n?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${r}${e.maximum.toString()} ${n.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?"≥":">",n=t(e.origin);return n?`Trop petit : attendu que ${e.origin} ait ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : attendu que ${e.origin} soit ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${S(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function oo(){return{localeError:io()}}var ao=()=>{let e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},r=t=>t?e[t]:void 0,n=t=>{let n=r(t);return n?n.label:t??e.unknown.label},i=e=>`ה${n(e)}`,o=e=>"f"===(r(e)?.gender??"m")?"צריכה להיות":"צריך להיות",a=e=>e?t[e]??null:null,s={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},c={nan:"NaN"};return t=>{switch(t.code){case"invalid_type":{let r=t.expected,i=c[r??""]??n(r),o=ge(t.input),a=c[o]??e[o]?.label??o;return/^[A-Z]/.test(t.expected)?`קלט לא תקין: צריך להיות instanceof ${t.expected}, התקבל ${a}`:`קלט לא תקין: צריך להיות ${i}, התקבל ${a}`}case"invalid_value":{if(1===t.values.length)return`ערך לא תקין: הערך חייב להיות ${Q(t.values[0])}`;let e=t.values.map(e=>Q(e));if(2===t.values.length)return`ערך לא תקין: האפשרויות המתאימות הן ${e[0]} או ${e[1]}`;let r=e[e.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${e.slice(0,-1).join(", ")} או ${r}`}case"too_big":{let e=a(t.origin),r=i(t.origin??"value");if("string"===t.origin)return`${e?.longLabel??"ארוך"} מדי: ${r} צריכה להכיל ${t.maximum.toString()} ${e?.unit??""} ${t.inclusive?"או פחות":"לכל היותר"}`.trim();if("number"===t.origin)return`גדול מדי: ${r} צריך להיות ${t.inclusive?`קטן או שווה ל-${t.maximum}`:`קטן מ-${t.maximum}`}`;if("array"===t.origin||"set"===t.origin)return`גדול מדי: ${r} ${"set"===t.origin?"צריכה":"צריך"} להכיל ${t.inclusive?`${t.maximum} ${e?.unit??""} או פחות`:`פחות מ-${t.maximum} ${e?.unit??""}`}`.trim();let n=t.inclusive?"<=":"<",s=o(t.origin??"value");return e?.unit?`${e.longLabel} מדי: ${r} ${s} ${n}${t.maximum.toString()} ${e.unit}`:`${e?.longLabel??"גדול"} מדי: ${r} ${s} ${n}${t.maximum.toString()}`}case"too_small":{let e=a(t.origin),r=i(t.origin??"value");if("string"===t.origin)return`${e?.shortLabel??"קצר"} מדי: ${r} צריכה להכיל ${t.minimum.toString()} ${e?.unit??""} ${t.inclusive?"או יותר":"לפחות"}`.trim();if("number"===t.origin)return`קטן מדי: ${r} צריך להיות ${t.inclusive?`גדול או שווה ל-${t.minimum}`:`גדול מ-${t.minimum}`}`;if("array"===t.origin||"set"===t.origin){let n="set"===t.origin?"צריכה":"צריך";return 1===t.minimum&&t.inclusive?`קטן מדי: ${r} ${n} להכיל ${t.origin,"לפחות פריט אחד"}`:`קטן מדי: ${r} ${n} להכיל ${t.inclusive?`${t.minimum} ${e?.unit??""} או יותר`:`יותר מ-${t.minimum} ${e?.unit??""}`}`.trim()}let n=t.inclusive?">=":">",s=o(t.origin??"value");return e?.unit?`${e.shortLabel} מדי: ${r} ${s} ${n}${t.minimum.toString()} ${e.unit}`:`${e?.shortLabel??"קטן"} מדי: ${r} ${s} ${n}${t.minimum.toString()}`}case"invalid_format":{let e=t;if("starts_with"===e.format)return`המחרוזת חייבת להתחיל ב "${e.prefix}"`;if("ends_with"===e.format)return`המחרוזת חייבת להסתיים ב "${e.suffix}"`;if("includes"===e.format)return`המחרוזת חייבת לכלול "${e.includes}"`;if("regex"===e.format)return`המחרוזת חייבת להתאים לתבנית ${e.pattern}`;let r=s[e.format];return`${r?.label??e.format} לא ${"f"===(r?.gender??"m")?"תקינה":"תקין"}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${t.divisor}`;case"unrecognized_keys":return`מפתח${t.keys.length>1?"ות":""} לא מזוה${t.keys.length>1?"ים":"ה"}: ${S(t.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${i(t.origin??"array")}`}}};function so(){return{localeError:ao()}}var co=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}let r={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},n={nan:"NaN",number:"szám",array:"tömb"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Érvénytelen bemenet: a várt érték instanceof ${e.expected}, a kapott érték ${i}`:`Érvénytelen bemenet: a várt érték ${t}, a kapott érték ${i}`}case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${Q(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${r}${e.maximum.toString()} ${n.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${r}${e.minimum.toString()} ${n.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${r[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};function uo(){return{localeError:co()}}function lo(e,t,r){return 1===Math.abs(e)?t:r}function po(e){if(!e)return"";let t=e[e.length-1];return e+(["ա","ե","ը","ի","ո","ու","օ"].includes(t)?"ն":"ը")}var fo=()=>{let e={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function t(t){return e[t]??null}let r={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},n={nan:"NaN",number:"թիվ",array:"զանգված"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Սխալ մուտքագրում․ սպասվում էր instanceof ${e.expected}, ստացվել է ${i}`:`Սխալ մուտքագրում․ սպասվում էր ${t}, ստացվել է ${i}`}case"invalid_value":return 1===e.values.length?`Սխալ մուտքագրում․ սպասվում էր ${Q(e.values[1])}`:`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);if(n){let t=lo(Number(e.maximum),n.unit.one,n.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${po(e.origin??"արժեք")} կունենա ${r}${e.maximum.toString()} ${t}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${po(e.origin??"արժեք")} լինի ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);if(n){let t=lo(Number(e.minimum),n.unit.one,n.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${po(e.origin)} կունենա ${r}${e.minimum.toString()} ${t}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${po(e.origin)} լինի ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Սխալ տող․ պետք է սկսվի "${t.prefix}"-ով`:"ends_with"===t.format?`Սխալ տող․ պետք է ավարտվի "${t.suffix}"-ով`:"includes"===t.format?`Սխալ տող․ պետք է պարունակի "${t.includes}"`:"regex"===t.format?`Սխալ տող․ պետք է համապատասխանի ${t.pattern} ձևաչափին`:`Սխալ ${r[t.format]??e.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${e.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${e.keys.length>1?"ներ":""}. ${S(e.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${po(e.origin)}-ում`;case"invalid_union":default:return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${po(e.origin)}-ում`}}};function ho(){return{localeError:fo()}}var mo=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}let r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Input tidak valid: diharapkan instanceof ${e.expected}, diterima ${i}`:`Input tidak valid: diharapkan ${t}, diterima ${i}`}case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${Q(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: diharapkan ${e.origin} memiliki ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${r[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};function go(){return{localeError:mo()}}var vo=()=>{let e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}let r={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},n={nan:"NaN",number:"númer",array:"fylki"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Rangt gildi: Þú slóst inn ${i} þar sem á að vera instanceof ${e.expected}`:`Rangt gildi: Þú slóst inn ${i} þar sem á að vera ${t}`}case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${Q(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${r}${e.maximum.toString()} ${n.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${r}${e.minimum.toString()} ${n.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${r[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${S(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};function yo(){return{localeError:vo()}}var _o=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}let r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"numero",array:"vettore"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Input non valido: atteso instanceof ${e.expected}, ricevuto ${i}`:`Input non valido: atteso ${t}, ricevuto ${i}`}case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${Q(e.values[0])}`:`Opzione non valida: atteso uno tra ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Troppo grande: ${e.origin??"valore"} deve avere ${r}${e.maximum.toString()} ${n.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Troppo piccolo: ${e.origin} deve avere ${r}${e.minimum.toString()} ${n.unit}`:`Troppo piccolo: ${e.origin} deve essere ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${S(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};function bo(){return{localeError:_o()}}var wo=()=>{let e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}let r={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},n={nan:"NaN",number:"数値",array:"配列"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`無効な入力: instanceof ${e.expected}が期待されましたが、${i}が入力されました`:`無効な入力: ${t}が期待されましたが、${i}が入力されました`}case"invalid_value":return 1===e.values.length?`無効な入力: ${Q(e.values[0])}が期待されました`:`無効な選択: ${S(e.values,"、")}のいずれかである必要があります`;case"too_big":{let r=e.inclusive?"以下である":"より小さい",n=t(e.origin);return n?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n.unit??"要素"}${r}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r}必要があります`}case"too_small":{let r=e.inclusive?"以上である":"より大きい",n=t(e.origin);return n?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n.unit}${r}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r}必要があります`}case"invalid_format":{let t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${r[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${S(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};function $o(){return{localeError:wo()}}var So=()=>{let e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function t(t){return e[t]??null}let r={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},n={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`არასწორი შეყვანა: მოსალოდნელი instanceof ${e.expected}, მიღებული ${i}`:`არასწორი შეყვანა: მოსალოდნელი ${t}, მიღებული ${i}`}case"invalid_value":return 1===e.values.length?`არასწორი შეყვანა: მოსალოდნელი ${Q(e.values[0])}`:`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${S(e.values,"|")}-დან`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ზედმეტად დიდი: მოსალოდნელი ${e.origin??"მნიშვნელობა"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit}`:`ზედმეტად დიდი: მოსალოდნელი ${e.origin??"მნიშვნელობა"} იყოს ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`ზედმეტად პატარა: მოსალოდნელი ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`ზედმეტად პატარა: მოსალოდნელი ${e.origin} იყოს ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`არასწორი სტრინგი: უნდა იწყებოდეს "${t.prefix}"-ით`:"ends_with"===t.format?`არასწორი სტრინგი: უნდა მთავრდებოდეს "${t.suffix}"-ით`:"includes"===t.format?`არასწორი სტრინგი: უნდა შეიცავდეს "${t.includes}"-ს`:"regex"===t.format?`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${t.pattern}`:`არასწორი ${r[t.format]??e.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${e.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${e.keys.length>1?"ები":"ი"}: ${S(e.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${e.origin}-ში`;case"invalid_union":default:return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${e.origin}-ში`}}};function ko(){return{localeError:So()}}var Io=()=>{let e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}let r={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},n={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${e.expected} ប៉ុន្តែទទួលបាន ${i}`:`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${t} ប៉ុន្តែទទួលបាន ${i}`}case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${Q(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()} ${n.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()} ${n.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${r[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${S(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};function Po(){return{localeError:Io()}}function Eo(){return Po()}var xo=()=>{let e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}let r={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`잘못된 입력: 예상 타입은 instanceof ${e.expected}, 받은 타입은 ${i}입니다`:`잘못된 입력: 예상 타입은 ${t}, 받은 타입은 ${i}입니다`}case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${Q(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${S(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let r=e.inclusive?"이하":"미만",n="미만"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${r}${n}`}case"too_small":{let r=e.inclusive?"이상":"초과",n="이상"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${r}${n}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${r[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${S(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};function Oo(){return{localeError:xo()}}var To=e=>e.charAt(0).toUpperCase()+e.slice(1);function Co(e){let t=Math.abs(e),r=t%10,n=t%100;return n>=11&&n<=19||0===r?"many":1===r?"one":"few"}var Ao=()=>{let e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(t,r,n,i){let o=e[t]??null;return null===o?o:{unit:o.unit[r],verb:o.verb[i][n?"inclusive":"notInclusive"]}}let r={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},n={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Gautas tipas ${i}, o tikėtasi - instanceof ${e.expected}`:`Gautas tipas ${i}, o tikėtasi - ${t}`}case"invalid_value":return 1===e.values.length?`Privalo būti ${Q(e.values[0])}`:`Privalo būti vienas iš ${S(e.values,"|")} pasirinkimų`;case"too_big":{let r=n[e.origin]??e.origin,i=t(e.origin,Co(Number(e.maximum)),e.inclusive??!1,"smaller");if(i?.verb)return`${To(r??e.origin??"reikšmė")} ${i.verb} ${e.maximum.toString()} ${i.unit??"elementų"}`;let o=e.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${To(r??e.origin??"reikšmė")} turi būti ${o} ${e.maximum.toString()} ${i?.unit}`}case"too_small":{let r=n[e.origin]??e.origin,i=t(e.origin,Co(Number(e.minimum)),e.inclusive??!1,"bigger");if(i?.verb)return`${To(r??e.origin??"reikšmė")} ${i.verb} ${e.minimum.toString()} ${i.unit??"elementų"}`;let o=e.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${To(r??e.origin??"reikšmė")} turi būti ${o} ${e.minimum.toString()} ${i?.unit}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Eilutė privalo prasidėti "${t.prefix}"`:"ends_with"===t.format?`Eilutė privalo pasibaigti "${t.suffix}"`:"includes"===t.format?`Eilutė privalo įtraukti "${t.includes}"`:"regex"===t.format?`Eilutė privalo atitikti ${t.pattern}`:`Neteisingas ${r[t.format]??e.format}`}case"not_multiple_of":return`Skaičius privalo būti ${e.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${e.keys.length>1?"i":"as"} rakt${e.keys.length>1?"ai":"as"}: ${S(e.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":default:return"Klaidinga įvestis";case"invalid_element":{let t=n[e.origin]??e.origin;return`${To(t??e.origin??"reikšmė")} turi klaidingą įvestį`}}}};function jo(){return{localeError:Ao()}}var Do=()=>{let e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}let r={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},n={nan:"NaN",number:"број",array:"низа"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Грешен внес: се очекува instanceof ${e.expected}, примено ${i}`:`Грешен внес: се очекува ${t}, примено ${i}`}case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Q(e.values[0])}`:`Грешана опција: се очекува една ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${r}${e.maximum.toString()} ${n.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Премногу мал: се очекува ${e.origin} да има ${r}${e.minimum.toString()} ${n.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${S(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};function No(){return{localeError:Do()}}var zo=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}let r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"nombor"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Input tidak sah: dijangka instanceof ${e.expected}, diterima ${i}`:`Input tidak sah: dijangka ${t}, diterima ${i}`}case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${Q(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: dijangka ${e.origin??"nilai"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: dijangka ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${r[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${S(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};function Ro(){return{localeError:zo()}}var Uo=()=>{let e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function t(t){return e[t]??null}let r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},n={nan:"NaN",number:"getal"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ongeldige invoer: verwacht instanceof ${e.expected}, ontving ${i}`:`Ongeldige invoer: verwacht ${t}, ontving ${i}`}case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${Q(e.values[0])}`:`Ongeldige optie: verwacht één van ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin),i="date"===e.origin?"laat":"string"===e.origin?"lang":"groot";return n?`Te ${i}: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} ${n.unit??"elementen"} ${n.verb}`:`Te ${i}: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} is`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin),i="date"===e.origin?"vroeg":"string"===e.origin?"kort":"klein";return n?`Te ${i}: verwacht dat ${e.origin} ${r}${e.minimum.toString()} ${n.unit} ${n.verb}`:`Te ${i}: verwacht dat ${e.origin} ${r}${e.minimum.toString()} is`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};function Mo(){return{localeError:Uo()}}var Ko=()=>{let e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}let r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"tall",array:"liste"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ugyldig input: forventet instanceof ${e.expected}, fikk ${i}`:`Ugyldig input: forventet ${t}, fikk ${i}`}case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${Q(e.values[0])}`:`Ugyldig valg: forventet en av ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()} ${n.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()} ${n.unit}`:`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${r[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${S(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};function Jo(){return{localeError:Ko()}}var Zo=()=>{let e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}let r={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},n={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Fâsit giren: umulan instanceof ${e.expected}, alınan ${i}`:`Fâsit giren: umulan ${t}, alınan ${i}`}case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${Q(e.values[0])}`:`Fâsit tercih: mûteberler ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} ${n.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} olmalıydı.`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} ${n.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${r[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function Lo(){return{localeError:Zo()}}var Wo=()=>{let e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}let r={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},n={nan:"NaN",number:"عدد",array:"ارې"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`ناسم ورودي: باید instanceof ${e.expected} وای, مګر ${i} ترلاسه شو`:`ناسم ورودي: باید ${t} وای, مګر ${i} ترلاسه شو`}case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${Q(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${S(e.values,"|")} څخه وای`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} وي`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} وي`}case"invalid_format":{let t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${r[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${S(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};function Fo(){return{localeError:Wo()}}var Ho=()=>{let e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}let r={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},n={nan:"NaN",number:"liczba",array:"tablica"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${e.expected}, otrzymano ${i}`:`Nieprawidłowe dane wejściowe: oczekiwano ${t}, otrzymano ${i}`}case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${Q(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.maximum.toString()} ${n.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.minimum.toString()} ${n.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${r[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};function Vo(){return{localeError:Ho()}}var qo=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}let r={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN",number:"número",null:"nulo"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Tipo inválido: esperado instanceof ${e.expected}, recebido ${i}`:`Tipo inválido: esperado ${t}, recebido ${i}`}case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${Q(e.values[0])}`:`Opção inválida: esperada uma das ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${r}${e.maximum.toString()} ${n.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Muito pequeno: esperado que ${e.origin} tivesse ${r}${e.minimum.toString()} ${n.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${r[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function Bo(){return{localeError:qo()}}function Go(e,t,r,n){let i=Math.abs(e),o=i%10,a=i%100;return a>=11&&a<=19?n:1===o?t:o>=2&&o<=4?r:n}var Xo=()=>{let e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}let r={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},n={nan:"NaN",number:"число",array:"массив"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Неверный ввод: ожидалось instanceof ${e.expected}, получено ${i}`:`Неверный ввод: ожидалось ${t}, получено ${i}`}case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${Q(e.values[0])}`:`Неверный вариант: ожидалось одно из ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);if(n){let t=Go(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${r}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);if(n){let t=Go(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${r}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${r[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};function Yo(){return{localeError:Xo()}}var Qo=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}let r={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},n={nan:"NaN",number:"število",array:"tabela"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Neveljaven vnos: pričakovano instanceof ${e.expected}, prejeto ${i}`:`Neveljaven vnos: pričakovano ${t}, prejeto ${i}`}case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${Q(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${r}${e.maximum.toString()} ${n.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Premajhno: pričakovano, da bo ${e.origin} imelo ${r}${e.minimum.toString()} ${n.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${r[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${S(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};function ea(){return{localeError:Qo()}}var ta=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}let r={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},n={nan:"NaN",number:"antal",array:"lista"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ogiltig inmatning: förväntat instanceof ${e.expected}, fick ${i}`:`Ogiltig inmatning: förväntat ${t}, fick ${i}`}case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${Q(e.values[0])}`:`Ogiltigt val: förväntade en av ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()} ${n.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()} ${n.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${r[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${S(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};function ra(){return{localeError:ta()}}var na=()=>{let e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}let r={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${e.expected}, பெறப்பட்டது ${i}`:`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${t}, பெறப்பட்டது ${i}`}case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${Q(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${S(e.values,"|")} இல் ஒன்று`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ${n.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ${n.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${r[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};function ia(){return{localeError:na()}}var oa=()=>{let e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}let r={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},n={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${e.expected} แต่ได้รับ ${i}`:`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${t} แต่ได้รับ ${i}`}case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${Q(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"ไม่เกิน":"น้อยกว่า",n=t(e.origin);return n?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()} ${n.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?"อย่างน้อย":"มากกว่า",n=t(e.origin);return n?`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()} ${n.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${r[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${S(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function aa(){return{localeError:oa()}}var sa=()=>{let e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}let r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Geçersiz değer: beklenen instanceof ${e.expected}, alınan ${i}`:`Geçersiz değer: beklenen ${t}, alınan ${i}`}case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${Q(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()} ${n.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${r[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};function ca(){return{localeError:sa()}}var ua=()=>{let e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}let r={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},n={nan:"NaN",number:"число",array:"масив"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Неправильні вхідні дані: очікується instanceof ${e.expected}, отримано ${i}`:`Неправильні вхідні дані: очікується ${t}, отримано ${i}`}case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${Q(e.values[0])}`:`Неправильна опція: очікується одне з ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Занадто велике: очікується, що ${e.origin??"значення"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Занадто мале: очікується, що ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${r[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${S(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};function da(){return{localeError:ua()}}function la(){return da()}var pa=()=>{let e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}let r={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},n={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`غلط ان پٹ: instanceof ${e.expected} متوقع تھا، ${i} موصول ہوا`:`غلط ان پٹ: ${t} متوقع تھا، ${i} موصول ہوا`}case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${Q(e.values[0])} متوقع تھا`:`غلط آپشن: ${S(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`بہت بڑا: ${e.origin??"ویلیو"} کے ${r}${e.maximum.toString()} ${n.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${r}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`بہت چھوٹا: ${e.origin} کے ${r}${e.minimum.toString()} ${n.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${r}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${r[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${S(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};function fa(){return{localeError:pa()}}var ha=()=>{let e={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function t(t){return e[t]??null}let r={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},n={nan:"NaN",number:"raqam",array:"massiv"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Noto‘g‘ri kirish: kutilgan instanceof ${e.expected}, qabul qilingan ${i}`:`Noto‘g‘ri kirish: kutilgan ${t}, qabul qilingan ${i}`}case"invalid_value":return 1===e.values.length?`Noto‘g‘ri kirish: kutilgan ${Q(e.values[0])}`:`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Juda katta: kutilgan ${e.origin??"qiymat"} ${r}${e.maximum.toString()} ${n.unit} ${n.verb}`:`Juda katta: kutilgan ${e.origin??"qiymat"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Juda kichik: kutilgan ${e.origin} ${r}${e.minimum.toString()} ${n.unit} ${n.verb}`:`Juda kichik: kutilgan ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Noto‘g‘ri satr: "${t.prefix}" bilan boshlanishi kerak`:"ends_with"===t.format?`Noto‘g‘ri satr: "${t.suffix}" bilan tugashi kerak`:"includes"===t.format?`Noto‘g‘ri satr: "${t.includes}" ni o‘z ichiga olishi kerak`:"regex"===t.format?`Noto‘g‘ri satr: ${t.pattern} shabloniga mos kelishi kerak`:`Noto‘g‘ri ${r[t.format]??e.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${e.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${e.keys.length>1?"lar":""}: ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} dagi kalit noto‘g‘ri`;case"invalid_union":default:return"Noto‘g‘ri kirish";case"invalid_element":return`${e.origin} da noto‘g‘ri qiymat`}}};function ma(){return{localeError:ha()}}var ga=()=>{let e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}let r={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},n={nan:"NaN",number:"số",array:"mảng"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Đầu vào không hợp lệ: mong đợi instanceof ${e.expected}, nhận được ${i}`:`Đầu vào không hợp lệ: mong đợi ${t}, nhận được ${i}`}case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${Q(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Quá nhỏ: mong đợi ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${r[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${S(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};function va(){return{localeError:ga()}}var ya=()=>{let e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}let r={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},n={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`无效输入:期望 instanceof ${e.expected},实际接收 ${i}`:`无效输入:期望 ${t},实际接收 ${i}`}case"invalid_value":return 1===e.values.length?`无效输入:期望 ${Q(e.values[0])}`:`无效选项:期望以下之一 ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()} ${n.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${r[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${S(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};function _a(){return{localeError:ya()}}var ba=()=>{let e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}let r={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},n={nan:"NaN"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`無效的輸入值:預期為 instanceof ${e.expected},但收到 ${i}`:`無效的輸入值:預期為 ${t},但收到 ${i}`}case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${Q(e.values[0])}`:`無效的選項:預期為以下其中之一 ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()} ${n.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()} ${n.unit}`:`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${r[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${S(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};function wa(){return{localeError:ba()}}var $a=()=>{let e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}let r={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},n={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return e=>{switch(e.code){case"invalid_type":{let t=n[e.expected]??e.expected,r=ge(e.input),i=n[r]??r;return/^[A-Z]/.test(e.expected)?`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${e.expected}, àmọ̀ a rí ${i}`:`Ìbáwọlé aṣìṣe: a ní láti fi ${t}, àmọ̀ a rí ${i}`}case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${Q(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${S(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${n.verb} ${r}${e.maximum} ${n.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${r}${e.maximum}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${n.verb} ${r}${e.minimum} ${n.unit}`:`Kéré ju: a ní láti jẹ́ ${r}${e.minimum}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${r[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${S(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};function Sa(){return{localeError:$a()}}var ka,Ia=Symbol("ZodOutput"),Pa=Symbol("ZodInput");class Ea{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function xa(){return new Ea}(ka=globalThis).__zod_globalRegistry??(ka.__zod_globalRegistry=xa());var Oa=globalThis.__zod_globalRegistry;function Ta(e,t){return new e({type:"string",...X(t)})}function Ca(e,t){return new e({type:"string",coerce:!0,...X(t)})}function Aa(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...X(t)})}function ja(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...X(t)})}function Da(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...X(t)})}function Na(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(t)})}function za(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(t)})}function Ra(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(t)})}function Ua(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...X(t)})}function Ma(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...X(t)})}function Ka(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(t)})}function Ja(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...X(t)})}function Za(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(t)})}function La(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...X(t)})}function Wa(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...X(t)})}function Fa(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(t)})}function Ha(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(t)})}function Va(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(t)})}function qa(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...X(t)})}function Ba(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(t)})}function Ga(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(t)})}function Xa(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...X(t)})}function Ya(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...X(t)})}function Qa(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...X(t)})}function es(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...X(t)})}var ts={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function rs(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(t)})}function ns(e,t){return new e({type:"string",format:"date",check:"string_format",...X(t)})}function is(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...X(t)})}function os(e,t){return new e({type:"string",format:"duration",check:"string_format",...X(t)})}function as(e,t){return new e({type:"number",checks:[],...X(t)})}function ss(e,t){return new e({type:"number",coerce:!0,checks:[],...X(t)})}function cs(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...X(t)})}function us(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...X(t)})}function ds(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...X(t)})}function ls(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...X(t)})}function ps(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...X(t)})}function fs(e,t){return new e({type:"boolean",...X(t)})}function hs(e,t){return new e({type:"boolean",coerce:!0,...X(t)})}function ms(e,t){return new e({type:"bigint",...X(t)})}function gs(e,t){return new e({type:"bigint",coerce:!0,...X(t)})}function vs(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...X(t)})}function ys(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...X(t)})}function _s(e,t){return new e({type:"symbol",...X(t)})}function bs(e,t){return new e({type:"undefined",...X(t)})}function ws(e,t){return new e({type:"null",...X(t)})}function $s(e){return new e({type:"any"})}function Ss(e){return new e({type:"unknown"})}function ks(e,t){return new e({type:"never",...X(t)})}function Is(e,t){return new e({type:"void",...X(t)})}function Ps(e,t){return new e({type:"date",...X(t)})}function Es(e,t){return new e({type:"date",coerce:!0,...X(t)})}function xs(e,t){return new e({type:"nan",...X(t)})}function Os(e,t){return new gr({check:"less_than",...X(t),value:e,inclusive:!1})}function Ts(e,t){return new gr({check:"less_than",...X(t),value:e,inclusive:!0})}function Cs(e,t){return new vr({check:"greater_than",...X(t),value:e,inclusive:!1})}function As(e,t){return new vr({check:"greater_than",...X(t),value:e,inclusive:!0})}function js(e){return Cs(0,e)}function Ds(e){return Os(0,e)}function Ns(e){return Ts(0,e)}function zs(e){return As(0,e)}function Rs(e,t){return new yr({check:"multiple_of",...X(t),value:e})}function Us(e,t){return new wr({check:"max_size",...X(t),maximum:e})}function Ms(e,t){return new $r({check:"min_size",...X(t),minimum:e})}function Ks(e,t){return new Sr({check:"size_equals",...X(t),size:e})}function Js(e,t){return new kr({check:"max_length",...X(t),maximum:e})}function Zs(e,t){return new Ir({check:"min_length",...X(t),minimum:e})}function Ls(e,t){return new Pr({check:"length_equals",...X(t),length:e})}function Ws(e,t){return new xr({check:"string_format",format:"regex",...X(t),pattern:e})}function Fs(e){return new Or({check:"string_format",format:"lowercase",...X(e)})}function Hs(e){return new Tr({check:"string_format",format:"uppercase",...X(e)})}function Vs(e,t){return new Cr({check:"string_format",format:"includes",...X(t),includes:e})}function qs(e,t){return new Ar({check:"string_format",format:"starts_with",...X(t),prefix:e})}function Bs(e,t){return new jr({check:"string_format",format:"ends_with",...X(t),suffix:e})}function Gs(e,t,r){return new Nr({check:"property",property:e,schema:t,...X(r)})}function Xs(e,t){return new zr({check:"mime_type",mime:e,...X(t)})}function Ys(e){return new Rr({check:"overwrite",tx:e})}function Qs(e){return Ys(t=>t.normalize(e))}function ec(){return Ys(e=>e.trim())}function tc(){return Ys(e=>e.toLowerCase())}function rc(){return Ys(e=>e.toUpperCase())}function nc(){return Ys(e=>M(e))}function ic(e,t,r){return new e({type:"array",element:t,...X(r)})}function oc(e,t,r){return new e({type:"union",options:t,...X(r)})}function ac(e,t,r){return new e({type:"union",options:t,inclusive:!1,...X(r)})}function sc(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...X(n)})}function cc(e,t,r){return new e({type:"intersection",left:t,right:r})}function uc(e,t,r,n){let i=r instanceof Kr;return new e({type:"tuple",items:t,rest:i?r:null,...X(i?n:r)})}function dc(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...X(n)})}function lc(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...X(n)})}function pc(e,t,r){return new e({type:"set",valueType:t,...X(r)})}function fc(e,t,r){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(e=>[e,e])):t,...X(r)})}function hc(e,t,r){return new e({type:"enum",entries:t,...X(r)})}function mc(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...X(r)})}function gc(e,t){return new e({type:"file",...X(t)})}function vc(e,t){return new e({type:"transform",transform:t})}function yc(e,t){return new e({type:"optional",innerType:t})}function _c(e,t){return new e({type:"nullable",innerType:t})}function bc(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():W(r)}})}function wc(e,t,r){return new e({type:"nonoptional",innerType:t,...X(r)})}function $c(e,t){return new e({type:"success",innerType:t})}function Sc(e,t,r){return new e({type:"catch",innerType:t,catchValue:"function"==typeof r?r:()=>r})}function kc(e,t,r){return new e({type:"pipe",in:t,out:r})}function Ic(e,t){return new e({type:"readonly",innerType:t})}function Pc(e,t,r){return new e({type:"template_literal",parts:t,...X(r)})}function Ec(e,t){return new e({type:"lazy",getter:t})}function xc(e,t){return new e({type:"promise",innerType:t})}function Oc(e,t,r){let n=X(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Tc(e,t,r){return new e({type:"custom",check:"custom",fn:t,...X(r)})}function Cc(e){let t=Ac(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(ve(e,r.value,t._zod.def));else{let n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(ve(n))}},e(r.value,r)));return t}function Ac(e,t){let r=new hr({check:"custom",...X(t)});return r._zod.check=e,r}function jc(e){let t=new hr({check:"describe"});return t._zod.onattach=[t=>{let r=Oa.get(t)??{};Oa.add(t,{...r,description:e})}],t._zod.check=()=>{},t}function Dc(e){let t=new hr({check:"meta"});return t._zod.onattach=[t=>{let r=Oa.get(t)??{};Oa.add(t,{...r,...e})}],t._zod.check=()=>{},t}function Nc(e,t){let r=X(t),n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];"sensitive"!==r.case&&(n=n.map(e=>"string"==typeof e?e.toLowerCase():e),i=i.map(e=>"string"==typeof e?e.toLowerCase():e));let o=new Set(n),a=new Set(i),s=e.Codec??vi,c=e.Boolean??bn,u=new s({type:"pipe",in:new(e.String??Jr)({type:"string",error:r.error}),out:new c({type:"boolean",error:r.error}),transform:(e,t)=>{let n=e;return"sensitive"!==r.case&&(n=n.toLowerCase()),!!o.has(n)||!a.has(n)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:t.value,inst:u,continue:!1}),{})},reverseTransform:(e,t)=>!0===e?n[0]||"true":i[0]||"false",error:r.error});return u}function zc(e,t,r,n={}){let i=X(n),o={...X(n),check:"string_format",type:"string",format:t,fn:"function"==typeof r?r:e=>r.test(e),...i};return r instanceof RegExp&&(o.pattern=r),new e(o)}function Rc(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Oa,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Uc(e,t,r={path:[],schemaPath:[]}){var n;let i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,n);else{let r=a.schema,o=t.processors[i.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,r,n)}let o=e._zod.parent;o&&(a.ref||(a.ref=o),Uc(o,t,n),t.seen.get(o).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===t.io&&Jc(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Mc(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=n.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let n=t[1],{ref:i,defId:o}=(t=>{let n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(r)return{ref:i(r)};let o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${n}/${o}`}}if(t[1]===r)return{ref:"#"};let i=`#/${n}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+o}})(t);n.def={...n.schema},o&&(n.defId=o);let a=n.schema;for(let e in a)delete a[e];a.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let n=r[1];if(t!==r[0]){if(e.external){let n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){i(r);continue}}(e.metadataRegistry.get(r[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&i(r)}else i(r)}}function Kc(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,o={...i},a=r.ref;if(r.ref=null,a){n(a);let r=e.seen.get(a),s=r.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,s):(i.allOf=i.allOf??[],i.allOf.push(s)),Object.assign(i,o),t._zod.parent===a)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(s.$ref)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==a){n(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())n(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:Lc(t,"input",e.processors),output:Lc(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}function Jc(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if("transform"===n.type)return!0;if("array"===n.type)return Jc(n.element,r);if("set"===n.type)return Jc(n.valueType,r);if("lazy"===n.type)return Jc(n.getter(),r);if("promise"===n.type||"optional"===n.type||"nonoptional"===n.type||"nullable"===n.type||"readonly"===n.type||"default"===n.type||"prefault"===n.type)return Jc(n.innerType,r);if("intersection"===n.type)return Jc(n.left,r)||Jc(n.right,r);if("record"===n.type||"map"===n.type)return Jc(n.keyType,r)||Jc(n.valueType,r);if("pipe"===n.type)return Jc(n.in,r)||Jc(n.out,r);if("object"===n.type){for(let e in n.shape)if(Jc(n.shape[e],r))return!0;return!1}if("union"===n.type){for(let e of n.options)if(Jc(e,r))return!0;return!1}if("tuple"===n.type){for(let e of n.items)if(Jc(e,r))return!0;return!(!n.rest||!Jc(n.rest,r))}return!1}var Zc=(e,t={})=>r=>{let n=Rc({...r,processors:t});return Uc(e,n),Mc(n,e),Kc(n,e)},Lc=(e,t,r={})=>n=>{let{libraryOptions:i,target:o}=n??{},a=Rc({...i??{},target:o,io:t,processors:r});return Uc(e,a),Mc(a,e),Kc(a,e)},Wc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Fc=(e,t,r,n)=>{let i=r;i.type="string";let{minimum:o,maximum:a,format:s,patterns:c,contentEncoding:u}=e._zod.bag;if("number"==typeof o&&(i.minLength=o),"number"==typeof a&&(i.maxLength=a),s&&(i.format=Wc[s]??s,""===i.format&&delete i.format,"time"===s&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let e=[...c];1===e.length?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},Hc=(e,t,r,n)=>{let i=r,{minimum:o,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;"string"==typeof s&&s.includes("int")?i.type="integer":i.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(i.minimum=d,i.exclusiveMinimum=!0):i.exclusiveMinimum=d),"number"==typeof o&&(i.minimum=o,"number"==typeof d&&"draft-04"!==t.target&&(d>=o?delete i.minimum:delete i.exclusiveMinimum)),"number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),"number"==typeof a&&(i.maximum=a,"number"==typeof u&&"draft-04"!==t.target&&(u<=a?delete i.maximum:delete i.exclusiveMaximum)),"number"==typeof c&&(i.multipleOf=c)},Vc=(e,t,r,n)=>{r.type="boolean"},qc=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")},Bc=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema")},Gc=(e,t,r,n)=>{"openapi-3.0"===t.target?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Xc=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema")},Yc=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Void cannot be represented in JSON Schema")},Qc=(e,t,r,n)=>{r.not={}},eu=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")},tu=(e,t,r,n)=>{let i=$(e._zod.def.entries);i.every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},ru=(e,t,r,n)=>{let i=e._zod.def,o=[];for(let e of i.values)if(void 0===e){if("throw"===t.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(e))}else o.push(e);if(0===o.length);else if(1===o.length){let e=o[0];r.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?r.enum=[e]:r.const=e}else o.every(e=>"number"==typeof e)&&(r.type="number"),o.every(e=>"string"==typeof e)&&(r.type="string"),o.every(e=>"boolean"==typeof e)&&(r.type="boolean"),o.every(e=>null===e)&&(r.type="null"),r.enum=o},nu=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("NaN cannot be represented in JSON Schema")},iu=(e,t,r,n)=>{let i=r,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},ou=(e,t,r,n)=>{let i=r,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=e._zod.bag;void 0!==a&&(o.minLength=a),void 0!==s&&(o.maxLength=s),c?1===c.length?(o.contentMediaType=c[0],Object.assign(i,o)):(Object.assign(i,o),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,o)},au=(e,t,r,n)=>{r.type="boolean"},su=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")},cu=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Function types cannot be represented in JSON Schema")},uu=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")},du=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Map cannot be represented in JSON Schema")},lu=(e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Set cannot be represented in JSON Schema")},pu=(e,t,r,n)=>{let i=r,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(i.minItems=a),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=Uc(o.element,t,{...n,path:[...n.path,"items"]})},fu=(e,t,r,n)=>{let i=r,o=e._zod.def;i.type="object",i.properties={};let a=o.shape;for(let e in a)i.properties[e]=Uc(a[e],t,{...n,path:[...n.path,"properties",e]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(e=>{let r=o.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));c.size>0&&(i.required=Array.from(c)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Uc(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)},hu=(e,t,r,n)=>{let i=e._zod.def,o=!1===i.inclusive,a=i.options.map((e,r)=>Uc(e,t,{...n,path:[...n.path,o?"oneOf":"anyOf",r]}));o?r.oneOf=a:r.anyOf=a},mu=(e,t,r,n)=>{let i=e._zod.def,o=Uc(i.left,t,{...n,path:[...n.path,"allOf",0]}),a=Uc(i.right,t,{...n,path:[...n.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,c=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];r.allOf=c},gu=(e,t,r,n)=>{let i=r,o=e._zod.def;i.type="array";let a="draft-2020-12"===t.target?"prefixItems":"items",s="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=o.items.map((e,r)=>Uc(e,t,{...n,path:[...n.path,a,r]})),u=o.rest?Uc(o.rest,t,{...n,path:[...n.path,s,..."openapi-3.0"===t.target?[o.items.length]:[]]}):null;"draft-2020-12"===t.target?(i.prefixItems=c,u&&(i.items=u)):"openapi-3.0"===t.target?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:d,maximum:l}=e._zod.bag;"number"==typeof d&&(i.minItems=d),"number"==typeof l&&(i.maxItems=l)},vu=(e,t,r,n)=>{let i=r,o=e._zod.def;i.type="object";let a=o.keyType,s=a._zod.bag?.patterns;if("loose"===o.mode&&s&&s.size>0){let e=Uc(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Uc(o.keyType,t,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Uc(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let c=a._zod.values;if(c){let e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}},yu=(e,t,r,n)=>{let i=e._zod.def,o=Uc(i.innerType,t,n),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},_u=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType},bu=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},wu=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$u=(e,t,r,n)=>{let i,o=e._zod.def;Uc(o.innerType,t,n),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Su=(e,t,r,n)=>{let i=e._zod.def,o="input"===t.io?"transform"===i.in._zod.def.type?i.out:i.in:i.out;Uc(o,t,n),t.seen.get(e).ref=o},ku=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType,r.readOnly=!0},Iu=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType},Pu=(e,t,r,n)=>{let i=e._zod.def;Uc(i.innerType,t,n),t.seen.get(e).ref=i.innerType},Eu=(e,t,r,n)=>{let i=e._zod.innerType;Uc(i,t,n),t.seen.get(e).ref=i},xu={string:Fc,number:Hc,boolean:Vc,bigint:qc,symbol:Bc,null:Gc,undefined:Xc,void:Yc,never:Qc,any:(e,t,r,n)=>{},unknown:(e,t,r,n)=>{},date:eu,enum:tu,literal:ru,nan:nu,template_literal:iu,file:ou,success:au,custom:su,function:cu,transform:uu,map:du,set:lu,array:pu,object:fu,union:hu,intersection:mu,tuple:gu,record:vu,nullable:yu,nonoptional:_u,default:bu,prefault:wu,catch:$u,pipe:Su,readonly:ku,promise:Iu,optional:Pu,lazy:Eu};function Ou(e,t){if("_idmap"in e){let r=e,n=Rc({...t,processors:xu}),i={};for(let e of r._idmap.entries()){let[t,r]=e;Uc(r,n)}let o={},a={registry:r,uri:t?.uri,defs:i};n.external=a;for(let e of r._idmap.entries()){let[t,r]=e;Mc(n,r),o[t]=Kc(n,r)}if(Object.keys(i).length>0){let e="draft-2020-12"===n.target?"$defs":"definitions";o.__shared={[e]:i}}return{schemas:o}}let r=Rc({...t,processors:xu});return Uc(e,r),Mc(r,e),Kc(r,e)}class Tu{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),this.ctx=Rc({processors:xu,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return Uc(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),Mc(this.ctx,e);let r=Kc(this.ctx,e),{"~standard":n,...i}=r;return i}}var Cu={},Au={};a(Au,{xor:()=>Fl,xid:()=>Ad,void:()=>Al,uuidv7:()=>vd,uuidv6:()=>gd,uuidv4:()=>md,uuid:()=>hd,url:()=>_d,unknown:()=>xl,union:()=>Ll,undefined:()=>$l,ulid:()=>Td,uint64:()=>yl,uint32:()=>ll,tuple:()=>Xl,transform:()=>hp,templateLiteral:()=>Jp,symbol:()=>bl,superRefine:()=>Yp,success:()=>Op,stringbool:()=>rf,stringFormat:()=>el,string:()=>sd,strictObject:()=>Kl,set:()=>op,refine:()=>Xp,record:()=>Ql,readonly:()=>Mp,promise:()=>Fp,preprocess:()=>of,prefault:()=>Ip,pipe:()=>Np,partialRecord:()=>ep,optional:()=>gp,object:()=>Ml,number:()=>ol,nullish:()=>wp,nullable:()=>bp,null:()=>kl,nonoptional:()=>Ep,never:()=>Tl,nativeEnum:()=>cp,nanoid:()=>kd,nan:()=>jp,meta:()=>ef,map:()=>np,mac:()=>Ud,looseRecord:()=>tp,looseObject:()=>Jl,literal:()=>dp,lazy:()=>Lp,ksuid:()=>Dd,keyof:()=>Rl,jwt:()=>Yd,json:()=>nf,ipv6:()=>Kd,ipv4:()=>zd,intersection:()=>Bl,int64:()=>vl,int32:()=>dl,int:()=>sl,instanceof:()=>tf,httpUrl:()=>bd,hostname:()=>tl,hex:()=>rl,hash:()=>nl,guid:()=>pd,function:()=>Vp,float64:()=>ul,float32:()=>cl,file:()=>pp,exactOptional:()=>yp,enum:()=>sp,emoji:()=>$d,email:()=>dd,e164:()=>Gd,discriminatedUnion:()=>Vl,describe:()=>Qp,date:()=>Dl,custom:()=>Gp,cuid2:()=>xd,cuid:()=>Pd,codec:()=>Rp,cidrv6:()=>Wd,cidrv4:()=>Zd,check:()=>Bp,catch:()=>Cp,boolean:()=>fl,bigint:()=>ml,base64url:()=>qd,base64:()=>Hd,array:()=>zl,any:()=>Pl,_function:()=>Vp,_default:()=>Sp,_ZodString:()=>od,ZodXor:()=>Wl,ZodXID:()=>Cd,ZodVoid:()=>Cl,ZodUnknown:()=>El,ZodUnion:()=>Zl,ZodUndefined:()=>wl,ZodUUID:()=>fd,ZodURL:()=>yd,ZodULID:()=>Od,ZodType:()=>id,ZodTuple:()=>Gl,ZodTransform:()=>fp,ZodTemplateLiteral:()=>Kp,ZodSymbol:()=>_l,ZodSuccess:()=>xp,ZodStringFormat:()=>cd,ZodString:()=>ad,ZodSet:()=>ip,ZodRecord:()=>Yl,ZodReadonly:()=>Up,ZodPromise:()=>Wp,ZodPrefault:()=>kp,ZodPipe:()=>Dp,ZodOptional:()=>mp,ZodObject:()=>Ul,ZodNumberFormat:()=>al,ZodNumber:()=>il,ZodNullable:()=>_p,ZodNull:()=>Sl,ZodNonOptional:()=>Pp,ZodNever:()=>Ol,ZodNanoID:()=>Sd,ZodNaN:()=>Ap,ZodMap:()=>rp,ZodMAC:()=>Rd,ZodLiteral:()=>up,ZodLazy:()=>Zp,ZodKSUID:()=>jd,ZodJWT:()=>Xd,ZodIntersection:()=>ql,ZodIPv6:()=>Md,ZodIPv4:()=>Nd,ZodGUID:()=>ld,ZodFunction:()=>Hp,ZodFile:()=>lp,ZodExactOptional:()=>vp,ZodEnum:()=>ap,ZodEmoji:()=>wd,ZodEmail:()=>ud,ZodE164:()=>Bd,ZodDiscriminatedUnion:()=>Hl,ZodDefault:()=>$p,ZodDate:()=>jl,ZodCustomStringFormat:()=>Qd,ZodCustom:()=>qp,ZodCodec:()=>zp,ZodCatch:()=>Tp,ZodCUID2:()=>Ed,ZodCUID:()=>Id,ZodCIDRv6:()=>Ld,ZodCIDRv4:()=>Jd,ZodBoolean:()=>pl,ZodBigIntFormat:()=>gl,ZodBigInt:()=>hl,ZodBase64URL:()=>Vd,ZodBase64:()=>Fd,ZodArray:()=>Nl,ZodAny:()=>Il});var ju={};a(ju,{uppercase:()=>Hs,trim:()=>ec,toUpperCase:()=>rc,toLowerCase:()=>tc,startsWith:()=>qs,slugify:()=>nc,size:()=>Ks,regex:()=>Ws,property:()=>Gs,positive:()=>js,overwrite:()=>Ys,normalize:()=>Qs,nonpositive:()=>Ns,nonnegative:()=>zs,negative:()=>Ds,multipleOf:()=>Rs,minSize:()=>Ms,minLength:()=>Zs,mime:()=>Xs,maxSize:()=>Us,maxLength:()=>Js,lte:()=>Ts,lt:()=>Os,lowercase:()=>Fs,length:()=>Ls,includes:()=>Vs,gte:()=>As,gt:()=>Cs,endsWith:()=>Bs});var Du={};a(Du,{time:()=>Ku,duration:()=>Zu,datetime:()=>zu,date:()=>Uu,ZodISOTime:()=>Mu,ZodISODuration:()=>Ju,ZodISODateTime:()=>Nu,ZodISODate:()=>Ru});var Nu=d("ZodISODateTime",(e,t)=>{en.init(e,t),cd.init(e,t)});function zu(e){return rs(Nu,e)}var Ru=d("ZodISODate",(e,t)=>{tn.init(e,t),cd.init(e,t)});function Uu(e){return ns(Ru,e)}var Mu=d("ZodISOTime",(e,t)=>{rn.init(e,t),cd.init(e,t)});function Ku(e){return is(Mu,e)}var Ju=d("ZodISODuration",(e,t)=>{nn.init(e,t),cd.init(e,t)});function Zu(e){return os(Ju,e)}var Lu=(e,t)=>{Ee.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>Te(e,t)},flatten:{value:t=>Oe(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,k,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,k,2)}},isEmpty:{get:()=>0===e.issues.length}})},Wu=d("ZodError",Lu),Fu=d("ZodError",Lu,{Parent:Error}),Hu=De(Fu),Vu=ze(Fu),qu=Ue(Fu),Bu=Ke(Fu),Gu=Ze(Fu),Xu=We(Fu),Yu=He(Fu),Qu=qe(Fu),ed=Ge(Fu),td=Ye(Fu),rd=et(Fu),nd=rt(Fu),id=d("ZodType",(e,t)=>(Kr.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Lc(e,"input"),output:Lc(e,"output")}}),e.toJSONSchema=Zc(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(g.mergeDefs(t,{checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,r)=>G(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>Hu(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>qu(e,t,r),e.parseAsync=async(t,r)=>Vu(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>Bu(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>Gu(e,t,r),e.decode=(t,r)=>Xu(e,t,r),e.encodeAsync=async(t,r)=>Yu(e,t,r),e.decodeAsync=async(t,r)=>Qu(e,t,r),e.safeEncode=(t,r)=>ed(e,t,r),e.safeDecode=(t,r)=>td(e,t,r),e.safeEncodeAsync=async(t,r)=>rd(e,t,r),e.safeDecodeAsync=async(t,r)=>nd(e,t,r),e.refine=(t,r)=>e.check(Xp(t,r)),e.superRefine=t=>e.check(Yp(t)),e.overwrite=t=>e.check(Ys(t)),e.optional=()=>gp(e),e.exactOptional=()=>yp(e),e.nullable=()=>bp(e),e.nullish=()=>gp(bp(e)),e.nonoptional=t=>Ep(e,t),e.array=()=>zl(e),e.or=t=>Ll([e,t]),e.and=t=>Bl(e,t),e.transform=t=>Np(e,hp(t)),e.default=t=>Sp(e,t),e.prefault=t=>Ip(e,t),e.catch=t=>Cp(e,t),e.pipe=t=>Np(e,t),e.readonly=()=>Mp(e),e.describe=t=>{let r=e.clone();return Oa.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Oa.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Oa.get(e);let r=e.clone();return Oa.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),od=d("_ZodString",(e,t)=>{Jr.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Fc(e,t,r);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(Ws(...t)),e.includes=(...t)=>e.check(Vs(...t)),e.startsWith=(...t)=>e.check(qs(...t)),e.endsWith=(...t)=>e.check(Bs(...t)),e.min=(...t)=>e.check(Zs(...t)),e.max=(...t)=>e.check(Js(...t)),e.length=(...t)=>e.check(Ls(...t)),e.nonempty=(...t)=>e.check(Zs(1,...t)),e.lowercase=t=>e.check(Fs(t)),e.uppercase=t=>e.check(Hs(t)),e.trim=()=>e.check(ec()),e.normalize=(...t)=>e.check(Qs(...t)),e.toLowerCase=()=>e.check(tc()),e.toUpperCase=()=>e.check(rc()),e.slugify=()=>e.check(nc())}),ad=d("ZodString",(e,t)=>{Jr.init(e,t),od.init(e,t),e.email=t=>e.check(Aa(ud,t)),e.url=t=>e.check(Ua(yd,t)),e.jwt=t=>e.check(es(Xd,t)),e.emoji=t=>e.check(Ma(wd,t)),e.guid=t=>e.check(ja(ld,t)),e.uuid=t=>e.check(Da(fd,t)),e.uuidv4=t=>e.check(Na(fd,t)),e.uuidv6=t=>e.check(za(fd,t)),e.uuidv7=t=>e.check(Ra(fd,t)),e.nanoid=t=>e.check(Ka(Sd,t)),e.guid=t=>e.check(ja(ld,t)),e.cuid=t=>e.check(Ja(Id,t)),e.cuid2=t=>e.check(Za(Ed,t)),e.ulid=t=>e.check(La(Od,t)),e.base64=t=>e.check(Xa(Fd,t)),e.base64url=t=>e.check(Ya(Vd,t)),e.xid=t=>e.check(Wa(Cd,t)),e.ksuid=t=>e.check(Fa(jd,t)),e.ipv4=t=>e.check(Ha(Nd,t)),e.ipv6=t=>e.check(Va(Md,t)),e.cidrv4=t=>e.check(Ba(Jd,t)),e.cidrv6=t=>e.check(Ga(Ld,t)),e.e164=t=>e.check(Qa(Bd,t)),e.datetime=t=>e.check(zu(t)),e.date=t=>e.check(Uu(t)),e.time=t=>e.check(Ku(t)),e.duration=t=>e.check(Zu(t))});function sd(e){return Ta(ad,e)}var cd=d("ZodStringFormat",(e,t)=>{Zr.init(e,t),od.init(e,t)}),ud=d("ZodEmail",(e,t)=>{Fr.init(e,t),cd.init(e,t)});function dd(e){return Aa(ud,e)}var ld=d("ZodGUID",(e,t)=>{Lr.init(e,t),cd.init(e,t)});function pd(e){return ja(ld,e)}var fd=d("ZodUUID",(e,t)=>{Wr.init(e,t),cd.init(e,t)});function hd(e){return Da(fd,e)}function md(e){return Na(fd,e)}function gd(e){return za(fd,e)}function vd(e){return Ra(fd,e)}var yd=d("ZodURL",(e,t)=>{Hr.init(e,t),cd.init(e,t)});function _d(e){return Ua(yd,e)}function bd(e){return Ua(yd,{protocol:/^https?$/,hostname:it.domain,...g.normalizeParams(e)})}var wd=d("ZodEmoji",(e,t)=>{Vr.init(e,t),cd.init(e,t)});function $d(e){return Ma(wd,e)}var Sd=d("ZodNanoID",(e,t)=>{qr.init(e,t),cd.init(e,t)});function kd(e){return Ka(Sd,e)}var Id=d("ZodCUID",(e,t)=>{Br.init(e,t),cd.init(e,t)});function Pd(e){return Ja(Id,e)}var Ed=d("ZodCUID2",(e,t)=>{Gr.init(e,t),cd.init(e,t)});function xd(e){return Za(Ed,e)}var Od=d("ZodULID",(e,t)=>{Xr.init(e,t),cd.init(e,t)});function Td(e){return La(Od,e)}var Cd=d("ZodXID",(e,t)=>{Yr.init(e,t),cd.init(e,t)});function Ad(e){return Wa(Cd,e)}var jd=d("ZodKSUID",(e,t)=>{Qr.init(e,t),cd.init(e,t)});function Dd(e){return Fa(jd,e)}var Nd=d("ZodIPv4",(e,t)=>{on.init(e,t),cd.init(e,t)});function zd(e){return Ha(Nd,e)}var Rd=d("ZodMAC",(e,t)=>{sn.init(e,t),cd.init(e,t)});function Ud(e){return qa(Rd,e)}var Md=d("ZodIPv6",(e,t)=>{an.init(e,t),cd.init(e,t)});function Kd(e){return Va(Md,e)}var Jd=d("ZodCIDRv4",(e,t)=>{cn.init(e,t),cd.init(e,t)});function Zd(e){return Ba(Jd,e)}var Ld=d("ZodCIDRv6",(e,t)=>{un.init(e,t),cd.init(e,t)});function Wd(e){return Ga(Ld,e)}var Fd=d("ZodBase64",(e,t)=>{ln.init(e,t),cd.init(e,t)});function Hd(e){return Xa(Fd,e)}var Vd=d("ZodBase64URL",(e,t)=>{fn.init(e,t),cd.init(e,t)});function qd(e){return Ya(Vd,e)}var Bd=d("ZodE164",(e,t)=>{hn.init(e,t),cd.init(e,t)});function Gd(e){return Qa(Bd,e)}var Xd=d("ZodJWT",(e,t)=>{gn.init(e,t),cd.init(e,t)});function Yd(e){return es(Xd,e)}var Qd=d("ZodCustomStringFormat",(e,t)=>{vn.init(e,t),cd.init(e,t)});function el(e,t,r={}){return zc(Qd,e,t,r)}function tl(e){return zc(Qd,"hostname",it.hostname,e)}function rl(e){return zc(Qd,"hex",it.hex,e)}function nl(e,t){let r=`${e}_${t?.enc??"hex"}`,n=it[r];if(!n)throw Error(`Unrecognized hash format: ${r}`);return zc(Qd,r,n,t)}var il=d("ZodNumber",(e,t)=>{yn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Hc(e,t,r),e.gt=(t,r)=>e.check(Cs(t,r)),e.gte=(t,r)=>e.check(As(t,r)),e.min=(t,r)=>e.check(As(t,r)),e.lt=(t,r)=>e.check(Os(t,r)),e.lte=(t,r)=>e.check(Ts(t,r)),e.max=(t,r)=>e.check(Ts(t,r)),e.int=t=>e.check(sl(t)),e.safe=t=>e.check(sl(t)),e.positive=t=>e.check(Cs(0,t)),e.nonnegative=t=>e.check(As(0,t)),e.negative=t=>e.check(Os(0,t)),e.nonpositive=t=>e.check(Ts(0,t)),e.multipleOf=(t,r)=>e.check(Rs(t,r)),e.step=(t,r)=>e.check(Rs(t,r)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function ol(e){return as(il,e)}var al=d("ZodNumberFormat",(e,t)=>{_n.init(e,t),il.init(e,t)});function sl(e){return cs(al,e)}function cl(e){return us(al,e)}function ul(e){return ds(al,e)}function dl(e){return ls(al,e)}function ll(e){return ps(al,e)}var pl=d("ZodBoolean",(e,t)=>{bn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Vc(0,0,t)});function fl(e){return fs(pl,e)}var hl=d("ZodBigInt",(e,t)=>{wn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>qc(0,e),e.gte=(t,r)=>e.check(As(t,r)),e.min=(t,r)=>e.check(As(t,r)),e.gt=(t,r)=>e.check(Cs(t,r)),e.gte=(t,r)=>e.check(As(t,r)),e.min=(t,r)=>e.check(As(t,r)),e.lt=(t,r)=>e.check(Os(t,r)),e.lte=(t,r)=>e.check(Ts(t,r)),e.max=(t,r)=>e.check(Ts(t,r)),e.positive=t=>e.check(Cs(BigInt(0),t)),e.negative=t=>e.check(Os(BigInt(0),t)),e.nonpositive=t=>e.check(Ts(BigInt(0),t)),e.nonnegative=t=>e.check(As(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(Rs(t,r));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function ml(e){return ms(hl,e)}var gl=d("ZodBigIntFormat",(e,t)=>{$n.init(e,t),hl.init(e,t)});function vl(e){return vs(gl,e)}function yl(e){return ys(gl,e)}var _l=d("ZodSymbol",(e,t)=>{Sn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Bc(0,e)});function bl(e){return _s(_l,e)}var wl=d("ZodUndefined",(e,t)=>{kn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Xc(0,e)});function $l(e){return bs(wl,e)}var Sl=d("ZodNull",(e,t)=>{In.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Gc(0,e,t)});function kl(e){return ws(Sl,e)}var Il=d("ZodAny",(e,t)=>{Pn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function Pl(){return $s(Il)}var El=d("ZodUnknown",(e,t)=>{En.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function xl(){return Ss(El)}var Ol=d("ZodNever",(e,t)=>{xn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Qc(0,0,t)});function Tl(e){return ks(Ol,e)}var Cl=d("ZodVoid",(e,t)=>{On.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>Yc(0,e)});function Al(e){return Is(Cl,e)}var jl=d("ZodDate",(e,t)=>{Tn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>eu(0,e),e.min=(t,r)=>e.check(As(t,r)),e.max=(t,r)=>e.check(Ts(t,r));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function Dl(e){return Ps(jl,e)}var Nl=d("ZodArray",(e,t)=>{An.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>pu(e,t,r,n),e.element=t.element,e.min=(t,r)=>e.check(Zs(t,r)),e.nonempty=t=>e.check(Zs(1,t)),e.max=(t,r)=>e.check(Js(t,r)),e.length=(t,r)=>e.check(Ls(t,r)),e.unwrap=()=>e.element});function zl(e,t){return ic(Nl,e,t)}function Rl(e){let t=e._zod.def.shape;return sp(Object.keys(t))}var Ul=d("ZodObject",(e,t)=>{Rn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>fu(e,t,r,n),g.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>sp(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:xl()}),e.loose=()=>e.clone({...e._zod.def,catchall:xl()}),e.strict=()=>e.clone({...e._zod.def,catchall:Tl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>g.extend(e,t),e.safeExtend=t=>g.safeExtend(e,t),e.merge=t=>g.merge(e,t),e.pick=t=>g.pick(e,t),e.omit=t=>g.omit(e,t),e.partial=(...t)=>g.partial(mp,e,t[0]),e.required=(...t)=>g.required(Pp,e,t[0])});function Ml(e,t){let r={type:"object",shape:e??{},...g.normalizeParams(t)};return new Ul(r)}function Kl(e,t){return new Ul({type:"object",shape:e,catchall:Tl(),...g.normalizeParams(t)})}function Jl(e,t){return new Ul({type:"object",shape:e,catchall:xl(),...g.normalizeParams(t)})}var Zl=d("ZodUnion",(e,t)=>{Mn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>hu(e,t,r,n),e.options=t.options});function Ll(e,t){return new Zl({type:"union",options:e,...g.normalizeParams(t)})}var Wl=d("ZodXor",(e,t)=>{Zl.init(e,t),Jn.init(e,t),e._zod.processJSONSchema=(t,r,n)=>hu(e,t,r,n),e.options=t.options});function Fl(e,t){return new Wl({type:"union",options:e,inclusive:!1,...g.normalizeParams(t)})}var Hl=d("ZodDiscriminatedUnion",(e,t)=>{Zl.init(e,t),Zn.init(e,t)});function Vl(e,t,r){return new Hl({type:"union",options:t,discriminator:e,...g.normalizeParams(r)})}var ql=d("ZodIntersection",(e,t)=>{Ln.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>mu(e,t,r,n)});function Bl(e,t){return new ql({type:"intersection",left:e,right:t})}var Gl=d("ZodTuple",(e,t)=>{Hn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>gu(e,t,r,n),e.rest=t=>e.clone({...e._zod.def,rest:t})});function Xl(e,t,r){let n=t instanceof Kr,i=n?r:t;return new Gl({type:"tuple",items:e,rest:n?t:null,...g.normalizeParams(i)})}var Yl=d("ZodRecord",(e,t)=>{qn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>vu(e,t,r,n),e.keyType=t.keyType,e.valueType=t.valueType});function Ql(e,t,r){return new Yl({type:"record",keyType:e,valueType:t,...g.normalizeParams(r)})}function ep(e,t,r){let n=G(e);return n._zod.values=void 0,new Yl({type:"record",keyType:n,valueType:t,...g.normalizeParams(r)})}function tp(e,t,r){return new Yl({type:"record",keyType:e,valueType:t,mode:"loose",...g.normalizeParams(r)})}var rp=d("ZodMap",(e,t)=>{Bn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>du(0,e),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...t)=>e.check(Ms(...t)),e.nonempty=t=>e.check(Ms(1,t)),e.max=(...t)=>e.check(Us(...t)),e.size=(...t)=>e.check(Ks(...t))});function np(e,t,r){return new rp({type:"map",keyType:e,valueType:t,...g.normalizeParams(r)})}var ip=d("ZodSet",(e,t)=>{Xn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>lu(0,e),e.min=(...t)=>e.check(Ms(...t)),e.nonempty=t=>e.check(Ms(1,t)),e.max=(...t)=>e.check(Us(...t)),e.size=(...t)=>e.check(Ks(...t))});function op(e,t){return new ip({type:"set",valueType:e,...g.normalizeParams(t)})}var ap=d("ZodEnum",(e,t)=>{Qn.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>tu(e,0,r),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{let i={};for(let n of e){if(!r.has(n))throw Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new ap({...t,checks:[],...g.normalizeParams(n),entries:i})},e.exclude=(e,n)=>{let i={...t.entries};for(let t of e){if(!r.has(t))throw Error(`Key ${t} not found in enum`);delete i[t]}return new ap({...t,checks:[],...g.normalizeParams(n),entries:i})}});function sp(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ap({type:"enum",entries:r,...g.normalizeParams(t)})}function cp(e,t){return new ap({type:"enum",entries:e,...g.normalizeParams(t)})}var up=d("ZodLiteral",(e,t)=>{ei.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>ru(e,t,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function dp(e,t){return new up({type:"literal",values:Array.isArray(e)?e:[e],...g.normalizeParams(t)})}var lp=d("ZodFile",(e,t)=>{ti.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>ou(e,0,r),e.min=(t,r)=>e.check(Ms(t,r)),e.max=(t,r)=>e.check(Us(t,r)),e.mime=(t,r)=>e.check(Xs(Array.isArray(t)?t:[t],r))});function pp(e){return gc(lp,e)}var fp=d("ZodTransform",(e,t)=>{ri.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>uu(0,e),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new f(e.constructor.name);r.addIssue=n=>{if("string"==typeof n)r.issues.push(g.issue(n,r.value,t));else{let t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(g.issue(t))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r)):(r.value=i,r)}});function hp(e){return new fp({type:"transform",transform:e})}var mp=d("ZodOptional",(e,t)=>{ii.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Pu(e,t,0,n),e.unwrap=()=>e._zod.def.innerType});function gp(e){return new mp({type:"optional",innerType:e})}var vp=d("ZodExactOptional",(e,t)=>{oi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Pu(e,t,0,n),e.unwrap=()=>e._zod.def.innerType});function yp(e){return new vp({type:"optional",innerType:e})}var _p=d("ZodNullable",(e,t)=>{ai.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>yu(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function bp(e){return new _p({type:"nullable",innerType:e})}function wp(e){return gp(bp(e))}var $p=d("ZodDefault",(e,t)=>{si.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>bu(e,t,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Sp(e,t){return new $p({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():g.shallowClone(t)}})}var kp=d("ZodPrefault",(e,t)=>{ui.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>wu(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function Ip(e,t){return new kp({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():g.shallowClone(t)}})}var Pp=d("ZodNonOptional",(e,t)=>{di.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>_u(e,t,0,n),e.unwrap=()=>e._zod.def.innerType});function Ep(e,t){return new Pp({type:"nonoptional",innerType:e,...g.normalizeParams(t)})}var xp=d("ZodSuccess",(e,t)=>{pi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>au(0,0,t),e.unwrap=()=>e._zod.def.innerType});function Op(e){return new xp({type:"success",innerType:e})}var Tp=d("ZodCatch",(e,t)=>{fi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>$u(e,t,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Cp(e,t){return new Tp({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}var Ap=d("ZodNaN",(e,t)=>{hi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>nu(0,e)});function jp(e){return xs(Ap,e)}var Dp=d("ZodPipe",(e,t)=>{mi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Su(e,t,0,n),e.in=t.in,e.out=t.out});function Np(e,t){return new Dp({type:"pipe",in:e,out:t})}var zp=d("ZodCodec",(e,t)=>{Dp.init(e,t),vi.init(e,t)});function Rp(e,t,r){return new zp({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var Up=d("ZodReadonly",(e,t)=>{bi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>ku(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function Mp(e){return new Up({type:"readonly",innerType:e})}var Kp=d("ZodTemplateLiteral",(e,t)=>{$i.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>iu(e,0,r)});function Jp(e,t){return new Kp({type:"template_literal",parts:e,...g.normalizeParams(t)})}var Zp=d("ZodLazy",(e,t)=>{Ii.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Eu(e,t,0,n),e.unwrap=()=>e._zod.def.getter()});function Lp(e){return new Zp({type:"lazy",getter:e})}var Wp=d("ZodPromise",(e,t)=>{ki.init(e,t),id.init(e,t),e._zod.processJSONSchema=(t,r,n)=>Iu(e,t,0,n),e.unwrap=()=>e._zod.def.innerType});function Fp(e){return new Wp({type:"promise",innerType:e})}var Hp=d("ZodFunction",(e,t)=>{Si.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>cu(0,e)});function Vp(e){return new Hp({type:"function",input:Array.isArray(e?.input)?Xl(e?.input):e?.input??zl(xl()),output:e?.output??xl()})}var qp=d("ZodCustom",(e,t)=>{Pi.init(e,t),id.init(e,t),e._zod.processJSONSchema=(e,t,r)=>su(0,e)});function Bp(e){let t=new hr({check:"custom"});return t._zod.check=e,t}function Gp(e,t){return Oc(qp,e??(()=>!0),t)}function Xp(e,t={}){return Tc(qp,e,t)}function Yp(e){return Cc(e)}var Qp=jc,ef=Dc;function tf(e,t={}){let r=new qp({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...g.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=t=>{t.value instanceof e||t.issues.push({code:"invalid_type",expected:e.name,input:t.value,inst:r,path:[...r._zod.def.path??[]]})},r}var rf=(...e)=>Nc({Codec:zp,Boolean:pl,String:ad},...e);function nf(e){let t=Lp(()=>Ll([sd(e),ol(),fl(),kl(),zl(t),Ql(sd(),t)]));return t}function of(e,t){return Np(hp(e),t)}var af,sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function cf(e){m({customError:e})}function uf(){return m().customError}af||(af={});var df={...Au,...ju,iso:Du},lf=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function pf(e,t){if(void 0!==e.not){if("object"==typeof e.not&&0===Object.keys(e.not).length)return df.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(void 0!==e.unevaluatedItems)throw Error("unevaluatedItems is not supported");if(void 0!==e.unevaluatedProperties)throw Error("unevaluatedProperties is not supported");if(void 0!==e.if||void 0!==e.then||void 0!==e.else)throw Error("Conditional schemas (if/then/else) are not supported");if(void 0!==e.dependentSchemas||void 0!==e.dependentRequired)throw Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let r=e.$ref;if(t.refs.has(r))return t.refs.get(r);if(t.processing.has(r))return df.lazy(()=>{if(!t.refs.has(r))throw Error(`Circular reference not resolved: ${r}`);return t.refs.get(r)});t.processing.add(r);let n=function(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(0===r.length)return t.rootSchema;let n="draft-2020-12"===t.version?"$defs":"definitions";if(r[0]===n){let n=r[1];if(!n||!t.defs[n])throw Error(`Reference not found: ${e}`);return t.defs[n]}throw Error(`Reference not found: ${e}`)}(r,t),i=ff(n,t);return t.refs.set(r,i),t.processing.delete(r),i}if(void 0!==e.enum){let r=e.enum;if("openapi-3.0"===t.version&&!0===e.nullable&&1===r.length&&null===r[0])return df.null();if(0===r.length)return df.never();if(1===r.length)return df.literal(r[0]);if(r.every(e=>"string"==typeof e))return df.enum(r);let n=r.map(e=>df.literal(e));return n.length<2?n[0]:df.union([n[0],n[1],...n.slice(2)])}if(void 0!==e.const)return df.literal(e.const);let r,n=e.type;if(Array.isArray(n)){let r=n.map(r=>pf({...e,type:r},t));return 0===r.length?df.never():1===r.length?r[0]:df.union(r)}if(!n)return df.any();switch(n){case"string":{let t=df.string();if(e.format){let r=e.format;"email"===r?t=t.check(df.email()):"uri"===r||"uri-reference"===r?t=t.check(df.url()):"uuid"===r||"guid"===r?t=t.check(df.uuid()):"date-time"===r?t=t.check(df.iso.datetime()):"date"===r?t=t.check(df.iso.date()):"time"===r?t=t.check(df.iso.time()):"duration"===r?t=t.check(df.iso.duration()):"ipv4"===r?t=t.check(df.ipv4()):"ipv6"===r?t=t.check(df.ipv6()):"mac"===r?t=t.check(df.mac()):"cidr"===r?t=t.check(df.cidrv4()):"cidr-v6"===r?t=t.check(df.cidrv6()):"base64"===r?t=t.check(df.base64()):"base64url"===r?t=t.check(df.base64url()):"e164"===r?t=t.check(df.e164()):"jwt"===r?t=t.check(df.jwt()):"emoji"===r?t=t.check(df.emoji()):"nanoid"===r?t=t.check(df.nanoid()):"cuid"===r?t=t.check(df.cuid()):"cuid2"===r?t=t.check(df.cuid2()):"ulid"===r?t=t.check(df.ulid()):"xid"===r?t=t.check(df.xid()):"ksuid"===r&&(t=t.check(df.ksuid()))}"number"==typeof e.minLength&&(t=t.min(e.minLength)),"number"==typeof e.maxLength&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case"number":case"integer":{let t="integer"===n?df.number().int():df.number();"number"==typeof e.minimum&&(t=t.min(e.minimum)),"number"==typeof e.maximum&&(t=t.max(e.maximum)),"number"==typeof e.exclusiveMinimum?t=t.gt(e.exclusiveMinimum):!0===e.exclusiveMinimum&&"number"==typeof e.minimum&&(t=t.gt(e.minimum)),"number"==typeof e.exclusiveMaximum?t=t.lt(e.exclusiveMaximum):!0===e.exclusiveMaximum&&"number"==typeof e.maximum&&(t=t.lt(e.maximum)),"number"==typeof e.multipleOf&&(t=t.multipleOf(e.multipleOf)),r=t;break}case"boolean":r=df.boolean();break;case"null":r=df.null();break;case"object":{let n={},i=e.properties||{},o=new Set(e.required||[]);for(let[e,r]of Object.entries(i)){let i=ff(r,t);n[e]=o.has(e)?i:i.optional()}if(e.propertyNames){let i=ff(e.propertyNames,t),o=e.additionalProperties&&"object"==typeof e.additionalProperties?ff(e.additionalProperties,t):df.any();if(0===Object.keys(n).length){r=df.record(i,o);break}let a=df.object(n).passthrough(),s=df.looseRecord(i,o);r=df.intersection(a,s);break}if(e.patternProperties){let i=e.patternProperties,o=Object.keys(i),a=[];for(let e of o){let r=ff(i[e],t),n=df.string().regex(new RegExp(e));a.push(df.looseRecord(n,r))}let s=[];if(Object.keys(n).length>0&&s.push(df.object(n).passthrough()),s.push(...a),0===s.length)r=df.object({}).passthrough();else if(1===s.length)r=s[0];else{let e=df.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=df.intersection(e,s[t]);r=e}break}let a=df.object(n);r=!1===e.additionalProperties?a.strict():"object"==typeof e.additionalProperties?a.catchall(ff(e.additionalProperties,t)):a.passthrough();break}case"array":{let{prefixItems:n,items:i}=e;if(n&&Array.isArray(n)){let o=n.map(e=>ff(e,t)),a=i&&"object"==typeof i&&!Array.isArray(i)?ff(i,t):void 0;r=a?df.tuple(o).rest(a):df.tuple(o),"number"==typeof e.minItems&&(r=r.check(df.minLength(e.minItems))),"number"==typeof e.maxItems&&(r=r.check(df.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=i.map(e=>ff(e,t)),o=e.additionalItems&&"object"==typeof e.additionalItems?ff(e.additionalItems,t):void 0;r=o?df.tuple(n).rest(o):df.tuple(n),"number"==typeof e.minItems&&(r=r.check(df.minLength(e.minItems))),"number"==typeof e.maxItems&&(r=r.check(df.maxLength(e.maxItems)))}else if(void 0!==i){let n=ff(i,t),o=df.array(n);"number"==typeof e.minItems&&(o=o.min(e.minItems)),"number"==typeof e.maxItems&&(o=o.max(e.maxItems)),r=o}else r=df.array(df.any());break}default:throw Error(`Unsupported type: ${n}`)}return e.description&&(r=r.describe(e.description)),void 0!==e.default&&(r=r.default(e.default)),r}function ff(e,t){if("boolean"==typeof e)return e?df.any():df.never();let r=pf(e,t),n=e.type||void 0!==e.enum||void 0!==e.const;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>ff(e,t)),o=df.union(i);r=n?df.intersection(r,o):o}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>ff(e,t)),o=df.xor(i);r=n?df.intersection(r,o):o}if(e.allOf&&Array.isArray(e.allOf))if(0===e.allOf.length)r=n?r:df.any();else{let i=n?r:ff(e.allOf[0],t);for(let r=n?0:1;r<e.allOf.length;r++)i=df.intersection(i,ff(e.allOf[r],t));r=i}!0===e.nullable&&"openapi-3.0"===t.version&&(r=df.nullable(r)),!0===e.readOnly&&(r=df.readonly(r));let i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let t of o)t in e&&(i[t]=e[t]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let t of a)t in e&&(i[t]=e[t]);for(let t of Object.keys(e))lf.has(t)||(i[t]=e[t]);return Object.keys(i).length>0&&t.registry.add(r,i),r}function hf(e,t){if("boolean"==typeof e)return e?df.any():df.never();let r=function(e,t){let r=e.$schema;return"https://json-schema.org/draft/2020-12/schema"===r?"draft-2020-12":"http://json-schema.org/draft-07/schema#"===r?"draft-7":"http://json-schema.org/draft-04/schema#"===r?"draft-4":t??"draft-2020-12"}(e,t?.defaultTarget);return ff(e,{version:r,defs:e.$defs||e.definitions||{},refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??Oa})}var mf={};function gf(e){return Ca(ad,e)}function vf(e){return ss(il,e)}function yf(e){return hs(pl,e)}function _f(e){return gs(hl,e)}function bf(e){return Es(jl,e)}a(mf,{string:()=>gf,number:()=>vf,date:()=>bf,boolean:()=>yf,bigint:()=>_f}),m(Vi());var wf=s.union([s.literal("light"),s.literal("dark")]).describe("Color theme preference for the host environment."),$f=s.union([s.literal("inline"),s.literal("fullscreen"),s.literal("pip")]).describe("Display mode for UI presentation."),Sf=s.union([s.literal("--color-background-primary"),s.literal("--color-background-secondary"),s.literal("--color-background-tertiary"),s.literal("--color-background-inverse"),s.literal("--color-background-ghost"),s.literal("--color-background-info"),s.literal("--color-background-danger"),s.literal("--color-background-success"),s.literal("--color-background-warning"),s.literal("--color-background-disabled"),s.literal("--color-text-primary"),s.literal("--color-text-secondary"),s.literal("--color-text-tertiary"),s.literal("--color-text-inverse"),s.literal("--color-text-ghost"),s.literal("--color-text-info"),s.literal("--color-text-danger"),s.literal("--color-text-success"),s.literal("--color-text-warning"),s.literal("--color-text-disabled"),s.literal("--color-text-ghost"),s.literal("--color-border-primary"),s.literal("--color-border-secondary"),s.literal("--color-border-tertiary"),s.literal("--color-border-inverse"),s.literal("--color-border-ghost"),s.literal("--color-border-info"),s.literal("--color-border-danger"),s.literal("--color-border-success"),s.literal("--color-border-warning"),s.literal("--color-border-disabled"),s.literal("--color-ring-primary"),s.literal("--color-ring-secondary"),s.literal("--color-ring-inverse"),s.literal("--color-ring-info"),s.literal("--color-ring-danger"),s.literal("--color-ring-success"),s.literal("--color-ring-warning"),s.literal("--font-sans"),s.literal("--font-mono"),s.literal("--font-weight-normal"),s.literal("--font-weight-medium"),s.literal("--font-weight-semibold"),s.literal("--font-weight-bold"),s.literal("--font-text-xs-size"),s.literal("--font-text-sm-size"),s.literal("--font-text-md-size"),s.literal("--font-text-lg-size"),s.literal("--font-heading-xs-size"),s.literal("--font-heading-sm-size"),s.literal("--font-heading-md-size"),s.literal("--font-heading-lg-size"),s.literal("--font-heading-xl-size"),s.literal("--font-heading-2xl-size"),s.literal("--font-heading-3xl-size"),s.literal("--font-text-xs-line-height"),s.literal("--font-text-sm-line-height"),s.literal("--font-text-md-line-height"),s.literal("--font-text-lg-line-height"),s.literal("--font-heading-xs-line-height"),s.literal("--font-heading-sm-line-height"),s.literal("--font-heading-md-line-height"),s.literal("--font-heading-lg-line-height"),s.literal("--font-heading-xl-line-height"),s.literal("--font-heading-2xl-line-height"),s.literal("--font-heading-3xl-line-height"),s.literal("--border-radius-xs"),s.literal("--border-radius-sm"),s.literal("--border-radius-md"),s.literal("--border-radius-lg"),s.literal("--border-radius-xl"),s.literal("--border-radius-full"),s.literal("--border-width-regular"),s.literal("--shadow-hairline"),s.literal("--shadow-sm"),s.literal("--shadow-md"),s.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),kf=s.record(Sf.describe("Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses `Record<K, string | undefined>` rather than `Partial<Record<K, string>>`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation."),s.union([s.string(),s.undefined()]).describe("Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses `Record<K, string | undefined>` rather than `Partial<Record<K, string>>`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation.")).describe("Style variables for theming MCP apps.\n\nIndividual style keys are optional - hosts may provide any subset of these values.\nValues are strings containing CSS values (colors, sizes, font stacks, etc.).\n\nNote: This type uses `Record<K, string | undefined>` rather than `Partial<Record<K, string>>`\nfor compatibility with Zod schema generation. Both are functionally equivalent for validation."),If=(s.object({method:s.literal("ui/open-link"),params:s.object({url:s.string().describe("URL to open in the host's browser")})}),s.object({isError:s.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),s.object({isError:s.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),s.object({method:s.literal("ui/notifications/sandbox-proxy-ready"),params:s.object({})}),s.object({connectDomains:s.array(s.string()).optional().describe("Origins for network requests (fetch/XHR/WebSocket)."),resourceDomains:s.array(s.string()).optional().describe("Origins for static resources (scripts, images, styles, fonts)."),frameDomains:s.array(s.string()).optional().describe("Origins for nested iframes (frame-src directive)."),baseUriDomains:s.array(s.string()).optional().describe("Allowed base URIs for the document (base-uri directive).")})),Pf=s.object({camera:s.object({}).optional().describe("Request camera access (Permission Policy `camera` feature)."),microphone:s.object({}).optional().describe("Request microphone access (Permission Policy `microphone` feature)."),geolocation:s.object({}).optional().describe("Request geolocation access (Permission Policy `geolocation` feature)."),clipboardWrite:s.object({}).optional().describe("Request clipboard write access (Permission Policy `clipboard-write` feature).")}),Ef=(s.object({method:s.literal("ui/notifications/size-changed"),params:s.object({width:s.number().optional().describe("New width in pixels."),height:s.number().optional().describe("New height in pixels.")})}),s.object({method:s.literal("ui/notifications/tool-input"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),s.object({method:s.literal("ui/notifications/tool-input-partial"),params:s.object({arguments:s.record(s.string(),s.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),s.object({method:s.literal("ui/notifications/tool-cancelled"),params:s.object({reason:s.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),s.object({fonts:s.string().optional()})),xf=s.object({variables:kf.optional().describe("CSS variables for theming the app."),css:Ef.optional().describe("CSS blocks that apps can inject.")}),Of=(s.object({method:s.literal("ui/resource-teardown"),params:s.object({})}),s.record(s.string(),s.unknown()),s.object({text:s.object({}).optional().describe("Host supports text content blocks."),image:s.object({}).optional().describe("Host supports image content blocks."),audio:s.object({}).optional().describe("Host supports audio content blocks."),resource:s.object({}).optional().describe("Host supports resource content blocks."),resourceLink:s.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:s.object({}).optional().describe("Host supports structured content.")})),Tf=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),openLinks:s.object({}).optional().describe("Host supports opening external URLs."),serverTools:s.object({listChanged:s.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:s.object({listChanged:s.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:s.object({}).optional().describe("Host accepts log messages."),sandbox:s.object({permissions:Pf.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:If.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Of.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Of.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),Cf=s.object({experimental:s.object({}).optional().describe("Experimental features (structure TBD)."),tools:s.object({listChanged:s.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:s.array($f).optional().describe("Display modes the app supports.")}),Af=(s.object({method:s.literal("ui/notifications/initialized"),params:s.object({}).optional()}),s.object({csp:If.optional().describe("Content Security Policy configuration."),permissions:Pf.optional().describe("Sandbox permissions requested by the UI."),domain:s.string().optional().describe("Dedicated origin for view sandbox."),prefersBorder:s.boolean().optional().describe("Visual boundary preference - true if UI prefers a visible border.")}),s.object({method:s.literal("ui/request-display-mode"),params:s.object({mode:$f.describe("The display mode being requested.")})}),s.object({mode:$f.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),s.union([s.literal("model"),s.literal("app")]).describe("Tool visibility scope - who can access the tool.")),jf=(s.object({resourceUri:s.string().optional(),visibility:s.array(Af).optional().describe('Who can access this tool. Default: ["model", "app"]\n- "model": Tool visible to and callable by the agent\n- "app": Tool callable by the app from this server only')}),s.object({mimeTypes:s.array(s.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),s.object({method:s.literal("ui/message"),params:s.object({role:s.literal("user").describe('Message role, currently only "user" is supported.'),content:s.array(i.WK).describe("Message content blocks (text, image, etc.).")})}),s.object({method:s.literal("ui/notifications/sandbox-resource-ready"),params:s.object({html:s.string().describe("HTML content to load into the inner iframe."),sandbox:s.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:If.optional().describe("CSP configuration from resource metadata."),permissions:Pf.optional().describe("Sandbox permissions from resource metadata.")})}),s.object({method:s.literal("ui/notifications/tool-result"),params:i.TF.describe("Standard MCP tool execution result.")}),s.object({toolInfo:s.object({id:i.UJ.optional().describe("JSON-RPC id of the tools/call request."),tool:i.Dn.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:wf.optional().describe("Current color theme preference."),styles:xf.optional().describe("Style configuration for theming the app."),displayMode:$f.optional().describe("How the UI is currently displayed."),availableDisplayModes:s.array($f).optional().describe("Display modes the host supports."),containerDimensions:s.union([s.object({height:s.number().describe("Fixed container height in pixels.")}),s.object({maxHeight:s.union([s.number(),s.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(s.union([s.object({width:s.number().describe("Fixed container width in pixels.")}),s.object({maxWidth:s.union([s.number(),s.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe("Container dimensions. Represents the dimensions of the iframe or other\ncontainer holding the app. Specify either width or maxWidth, and either height or maxHeight."),locale:s.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s.string().optional().describe("User's timezone in IANA format."),userAgent:s.string().optional().describe("Host application identifier."),platform:s.union([s.literal("web"),s.literal("desktop"),s.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:s.object({touch:s.boolean().optional().describe("Whether the device supports touch input."),hover:s.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:s.object({top:s.number().describe("Top safe area inset in pixels."),right:s.number().describe("Right safe area inset in pixels."),bottom:s.number().describe("Bottom safe area inset in pixels."),left:s.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough()),Df=(s.object({method:s.literal("ui/notifications/host-context-changed"),params:jf.describe("Partial context update containing only changed fields.")}),s.object({method:s.literal("ui/update-model-context"),params:s.object({content:s.array(i.WK).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:s.record(s.string(),s.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),s.object({method:s.literal("ui/initialize"),params:s.object({appInfo:i.a8.describe("App identification (name and version)."),appCapabilities:Cf.describe("Features and capabilities this app provides."),protocolVersion:s.string().describe("Protocol version this app supports.")})}),s.object({protocolVersion:s.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:i.a8.describe("Host application identification and version."),hostCapabilities:Tf.describe("Features and capabilities provided by the host."),hostContext:jf.describe("Rich context about the host environment.")}).passthrough(),"ui/resourceUri"),Nf="text/html;profile=mcp-app";function zf(e,t,r,n){let i=r._meta,o=i.ui,a=i[Df],s=i;return o?.resourceUri&&!a?s={...i,[Df]:o.resourceUri}:a&&!o?.resourceUri&&(s={...i,ui:{...o,resourceUri:a}}),e.registerTool(t,{...r,_meta:s},n)}function Rf(e,t,r,n,i){e.registerResource(t,r,{mimeType:Nf,...n},i)}n.Zs;var Uf="io.modelcontextprotocol/ui";function Mf(e){if(e)return e.extensions?.[Uf]}},42275:(e,t,r)=>{"use strict";r.r(t),r.d(t,{canonicalize:()=>o,canonicalizeEx:()=>a});var n="$";function i(e,t){var r="",i=t&&t.include,o=t&&t.exclude;o&&"string"==typeof o&&(o=[o]),i&&i.sort();var a=new WeakMap,s=t&&t.allowCircular,c=t&&t.filterUndefined,u=t&&t.undefinedInArrayToNull;return function e(t,d){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(p=a.get(t))&&d.startsWith(p)){if(!s)throw new Error("Circular reference detected");return void(r+='"[Circular:'+p+']"')}a.set(t,d),r+="[";var l=!1;t.forEach(function(t,n){l&&(r+=","),l=!0,u&&void 0===t&&(t=null),e(t,d+"["+n+"]")}),r+="]"}else{var p;if(void 0!==(p=a.get(t))&&d.startsWith(p)){if(!s)throw new Error("Circular reference detected");return void(r+='"[Circular:'+p+']"')}a.set(t,d),r+="{";var f=!1,h=function(n){o&&o.includes(n)||(f&&(r+=","),f=!0,r+=JSON.stringify(n),r+=":",e(t[n],d+"."+n))};if(d===n&&i)i.forEach(function(e){t.hasOwnProperty(e)&&h(e)});else{var m=Object.keys(t);c&&(m=m.filter(function(e){return void 0!==t[e]})),m.sort(),m.forEach(function(e){h(e)})}r+="}"}}(e,n),r}function o(e,t){return i(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}function a(e,t){return i(e,t)}},42399:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=42399,e.exports=t},42769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthTokenRetrievalService=void 0,t.OAuthTokenRetrievalService=class{config;constructor(e){this.config={...e,logger:e.logger||(()=>{}),retryConfig:{maxRetries:3,retryDelay:1e3,retryBackoff:2,...e.retryConfig}}}async retrieveTokens(e,t){const r=`${this.config.baseUrl}/api/v1/bouncer/delegations/${e}/tokens`;this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens",{delegationId:e,endpoint:r});let n=null,i=0;for(;i<=this.config.retryConfig.maxRetries;)try{const n=await this.config.fetchProvider(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok){const t=await n.json().catch(()=>({}));if(404===n.status||401===n.status)return this.config.logger("[OAuthTokenRetrievalService] Tokens unavailable",{status:n.status,delegationId:e,error:t}),null;const r=t.error?.message||t.error||t.message||`HTTP ${n.status}`;throw new Error(`Token retrieval failed: ${r}`)}const i=await n.json();if(!i.success)return this.config.logger("[OAuthTokenRetrievalService] Token retrieval error response",{delegationId:e,error:i.error}),null;const o=this.mapToIdpTokens(i.data);return this.config.logger("[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",{delegationId:e,expiresAt:new Date(o.expires_at).toISOString(),hasRefreshToken:!!o.refresh_token}),o}catch(t){if(n=t instanceof Error?t:new Error(String(t)),!(i<this.config.retryConfig.maxRetries))return this.config.logger("[OAuthTokenRetrievalService] Max retries exceeded",{delegationId:e,error:n.message,attempts:i+1}),null;{const e=this.config.retryConfig.retryDelay*Math.pow(this.config.retryConfig.retryBackoff,i);this.config.logger("[OAuthTokenRetrievalService] Retry attempt failed, retrying",{attempt:i+1,maxRetries:this.config.retryConfig.maxRetries,delay:e,error:n.message}),await new Promise(t=>setTimeout(t,e)),i++}}return null}mapToIdpTokens(e){let t;return t=e.oauth_expires_at?new Date(e.oauth_expires_at).getTime():e.oauth_expires_in?Date.now()+1e3*e.oauth_expires_in:Date.now()+36e5,{access_token:e.oauth_access_token,refresh_token:e.oauth_refresh_token||void 0,expires_in:e.oauth_expires_in||void 0,expires_at:t,token_type:e.oauth_token_type||"Bearer",scope:e.oauth_scope||void 0}}}},44089:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598),i=r(80384),o=r(90489),a=r(45935),s=r(39069),c=r(73553),u=r(81593),d=r(99135),l=r(60322),p=r(29994),f=r(71759),h=r(4268),m=r(58242);t.default=(e,t,r,g,v,y)=>{let _;if((0,d.isCryptoKey)(t))(0,l.checkEncCryptoKey)(t,e,"decrypt"),_=n.KeyObject.from(t);else{if(!(t instanceof Uint8Array||(0,p.default)(t)))throw new TypeError((0,f.default)(t,...m.types,"Uint8Array"));_=t}if(!g)throw new s.JWEInvalid("JWE Initialization Vector missing");if(!v)throw new s.JWEInvalid("JWE Authentication Tag missing");switch((0,o.default)(e,_),(0,i.default)(e,g),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return function(e,t,r,i,o,d){const l=parseInt(e.slice(1,4),10);(0,p.default)(t)&&(t=t.export());const f=t.subarray(l>>3),m=t.subarray(0,l>>3),g=parseInt(e.slice(-3),10),v=`aes-${l}-cbc`;if(!(0,h.default)(v))throw new s.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);const y=(0,u.default)(d,i,r,g,m,l);let _,b;try{_=(0,c.default)(o,y)}catch{}if(!_)throw new s.JWEDecryptionFailed;try{const e=(0,n.createDecipheriv)(v,f,i);b=(0,a.concat)(e.update(r),e.final())}catch{}if(!b)throw new s.JWEDecryptionFailed;return b}(e,_,r,g,v,y);case"A128GCM":case"A192GCM":case"A256GCM":return function(e,t,r,i,o,a){const c=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,h.default)(c))throw new s.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);try{const e=(0,n.createDecipheriv)(c,t,i,{authTagLength:16});e.setAuthTag(o),a.byteLength&&e.setAAD(a,{plaintextLength:r.length});const s=e.update(r);return e.final(),s}catch{throw new s.JWEDecryptionFailed}}(e,_,r,g,v,y);default:throw new s.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}}},44490:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const n=r(28261);class i extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var o;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(o||(t.UsedValueState=o={})),t.varKinds={const:new n.Name("const"),let:new n.Name("let"),var:new n.Name("var")};class a{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof n.Name?e:this.name(e)}name(e){return new n.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}t.Scope=a;class s extends n.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=n._`.${new n.Name(t)}[${r}]`}}t.ValueScopeName=s;const c=n._`\n`;t.ValueScope=class extends a{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:n.nil}}get(){return this._scope}name(e){return new s(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:i}=n,o=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[i];if(a){const e=a.get(o);if(e)return e}else a=this._values[i]=new Map;a.set(o,n);const s=this._scope[i]||(this._scope[i]=[]),c=s.length;return s[c]=t.ref,n.setValue(t,{property:i,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw new Error(`CodeGen: name "${t}" has no value`);return n._`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,r,a={},s){let c=n.nil;for(const u in e){const d=e[u];if(!d)continue;const l=a[u]=a[u]||new Map;d.forEach(e=>{if(l.has(e))return;l.set(e,o.Started);let a=r(e);if(a){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;c=n._`${c}${r} ${e} = ${a};${this.opts._n}`}else{if(!(a=null==s?void 0:s(e)))throw new i(e);c=n._`${c}${a}${this.opts._n}`}l.set(e,o.Completed)})}return c}}},44558:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryDelegationGraphStorage=void 0,t.MemoryDelegationGraphStorage=class{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],n=new Set;for(;r.length>0;){const e=r.shift();if(n.has(e))continue;n.add(e);const i=this.nodes.get(e);if(i)for(const e of i.children)if(!n.has(e)){r.push(e);const n=this.nodes.get(e);n&&t.push(n)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let n=0;for(const t of e){const e=this.getChainSync(t.id);n=Math.max(n,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:n}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}},44618:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},44708:e=>{"use strict";e.exports=require("node:https")},45380:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isJWK=i,t.isPrivateJWK=function(e){return"oct"!==e.kty&&"string"==typeof e.d},t.isPublicJWK=function(e){return"oct"!==e.kty&&void 0===e.d},t.isSecretJWK=function(e){return i(e)&&"oct"===e.kty&&"string"==typeof e.k};const n=r(71661);function i(e){return(0,n.default)(e)&&"string"==typeof e.kty}},45395:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerifier=void 0;const n=r(81296),i=r(28717),o=r(42275),a=r(53683);t.ProofVerifier=class{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;constructor(e){this.cryptoService=new n.CryptoService(e.cryptoProvider),this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??300,this.nonceTtlSeconds=e.nonceTtlSeconds??300}async verifyProof(e,t){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const n=r.proof,i=await this.validateNonce(n.meta.nonce,n.meta.did);if(!i.valid)return i;const o=await this.validateTimestamp(n.meta.ts);if(!o.valid)return o;const a=this.buildCanonicalPayload(n.meta),s=(new TextEncoder).encode(a),c=await this.verifySignature(n.jws,t,s,n.meta.kid);return c.valid?(await this.addNonceToCache(n.meta.nonce,n.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:a.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async verifyProofDetached(e,t,r){try{const n=await this.validateProofStructure(e);if(!n.valid)return n;const i=n.proof,o=await this.validateNonce(i.meta.nonce,i.meta.did);if(!o.valid)return o;const a=await this.validateTimestamp(i.meta.ts);if(!a.valid)return a;const s=t instanceof Uint8Array?t:(new TextEncoder).encode(t),c=await this.verifySignature(i.jws,r,s,i.meta.kid);return c.valid?(await this.addNonceToCache(i.meta.nonce,i.meta.did),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:a.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async validateProofStructure(e){const t=i.DetachedProofSchema.safeParse(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:a.PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error.message}`),details:{zodErrors:t.error.errors}}}async validateNonce(e,t){return await this.nonceCache.has(e,t)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:a.PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,details:{nonce:e,agentDid:t}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:a.PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,n){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:n,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:a.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:n,actualKid:t.kid}}}async addNonceToCache(e,t){await this.nonceCache.add(e,this.nonceTtlSeconds,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});if(!r.verificationMethod||0===r.verificationMethod.length)throw new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let n;if(t){const i=t.startsWith("#")?t:`#${t}`;if(n=r.verificationMethod.find(t=>t.id===i||t.id===`${e}${i}`),!n)throw new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else n=r.verificationMethod[0];if(!n?.publicKeyJwk)throw new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:n?.id});const i=n.publicKeyJwk;if("OKP"!==i.kty||"Ed25519"!==i.crv||!i.x)throw new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${i.kty}, crv=${i.crv}`,{did:e,kid:t,jwk:{kty:i.kty,crv:i.crv}});return i}catch(r){if(r instanceof a.ProofVerificationError)throw r;throw console.error("[ProofVerifier] Failed to fetch public key from DID:",r),new a.ProofVerificationError(a.PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return(0,o.canonicalize)(t)}}},45935:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decoder=t.encoder=void 0,t.concat=o,t.p2s=function(e,r){return o(t.encoder.encode(e),new Uint8Array([0]),r)},t.uint64be=function(e){const t=Math.floor(e/i),r=e%i,n=new Uint8Array(8);return a(n,t,0),a(n,r,4),n},t.uint32be=s,t.lengthAndInput=function(e){return o(s(e.length),e)},t.concatKdf=async function(e,t,r){const i=Math.ceil((t>>3)/32),o=new Uint8Array(32*i);for(let t=0;t<i;t++){const i=new Uint8Array(4+e.length+r.length);i.set(s(t+1)),i.set(e,4),i.set(r,4+e.length),o.set(await(0,n.default)("sha256",i),32*t)}return o.slice(0,t>>3)};const n=r(17306);t.encoder=new TextEncoder,t.decoder=new TextDecoder;const i=2**32;function o(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function a(e,t,r){if(t<0||t>=i)throw new RangeError(`value must be >= 0 and <= ${i-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function s(e){const t=new Uint8Array(4);return a(t,e),t}},46171:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDefaultConsoleLogger=t.logger=void 0;var n=r(86587);Object.defineProperty(t,"logger",{enumerable:!0,get:function(){return n.logger}}),Object.defineProperty(t,"createDefaultConsoleLogger",{enumerable:!0,get:function(){return n.createDefaultConsoleLogger}})},46398:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(24954),i=r(38994),o=r(67218),a=r(67218),s={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:s,parentSchema:c,it:u}=e,{opts:d}=u,l=(0,n.allSchemaProperties)(r),p=l.filter(e=>(0,o.alwaysValidSchema)(u,r[e]));if(0===l.length||p.length===l.length&&(!u.opts.unevaluated||!0===u.props))return;const f=d.strictSchema&&!d.allowMatchingProperties&&c.properties,h=t.name("valid");!0===u.props||u.props instanceof i.Name||(u.props=(0,a.evaluatedPropsToName)(t,u.props));const{props:m}=u;function g(e){for(const t in f)new RegExp(e).test(t)&&(0,o.checkStrictMode)(u,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){t.forIn("key",s,o=>{t.if(i._`${(0,n.usePattern)(e,r)}.test(${o})`,()=>{const n=p.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:a.Type.Str},h),u.opts.unevaluated&&!0!==m?t.assign(i._`${m}[${o}]`,!0):n||u.allErrors||t.if((0,i.not)(h),()=>t.break())})})}!function(){for(const e of l)f&&g(e),u.allErrors?v(e):(t.var(h,!0),v(e),t.if(h))}()}};t.default=s},46610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitstringManager=void 0,t.isIndexSet=async function(e,t,n){const i=r.base64urlDecode(e),o=await n.decompress(i),a=Math.floor(t/8),s=t%8;return!(a>=o.length)&&!!(o[a]&1<<s)};class r{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const n=Math.ceil(e/8);this.bits=new Uint8Array(n)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),n=e%8;t?this.bits[r]|=1<<n:this.bits[r]&=~(1<<n)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,n){const i=r.base64urlDecode(e),o=await n.decompress(i),a=8*o.length,s=new r(a,t,n);return s.bits=o,s}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return r.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;t+="=".repeat(r);const n=atob(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);return i}static fromSetBits(e,t,n,i){const o=new r(e,n,i);for(const e of t)o.setBit(e,!0);return o}}t.BitstringManager=r},47532:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,a.default)(t,...s.types));return(0,n.createSecretKey)(t)}if(t instanceof n.KeyObject)return t;if((0,i.isCryptoKey)(t))return(0,o.checkSigCryptoKey)(t,e,r),n.KeyObject.from(t);if(c.isJWK(t))return e.startsWith("HS")?(0,n.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError((0,a.default)(t,...s.types,"Uint8Array","JSON Web Key"))};const n=r(77598),i=r(99135),o=r(60322),a=r(71759),s=r(58242),c=r(45380)},47919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionRegistrationService=void 0,t.createSessionRegistrationService=function(e){return e.apiUrl&&e.apiKey?new i({baseUrl:e.apiUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,logger:e.logger}):(e.logger?.("[SessionRegistration] Missing required config - session registration disabled",{hasApiUrl:!!e.apiUrl,hasApiKey:!!e.apiKey}),null)};const n=r(82906);class i{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,logger:e.logger||(()=>{}),timeoutMs:e.timeoutMs??5e3}}async registerSession(e){const t=e.session_id;try{const r=n.registerSessionRequestSchema.safeParse(e);if(!r.success){const e=`Invalid session registration request: ${r.error.message}`;return this.config.logger("[SessionRegistration] Validation failed",{sessionId:t,error:e}),{success:!1,sessionId:t,error:e}}const i=`${this.config.baseUrl}${n.AGENTSHIELD_ENDPOINTS.SESSIONS}`;this.config.logger("[SessionRegistration] Registering session for dashboard visibility",{sessionId:t,agentDid:e.agent_did,clientName:e.client_info.name,url:i});const o=new AbortController,a=setTimeout(()=>o.abort(),this.config.timeoutMs);try{const r=await this.config.fetchProvider.fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(e),signal:o.signal});if(clearTimeout(a),!r.ok){const e=await r.text().catch(()=>"Unknown error");return this.config.logger("[SessionRegistration] Registration failed",{sessionId:t,status:r.status,error:e}),{success:!1,sessionId:t,error:`HTTP ${r.status}: ${e}`}}const s=await r.json(),c=n.registerSessionResponseSchema.safeParse(s.data||s);return c.success?(this.config.logger("[SessionRegistration] Session now visible in AgentShield dashboard",{sessionId:t,registered:c.data.registered}),{success:!0,sessionId:t}):(this.config.logger("[SessionRegistration] Invalid response format",{sessionId:t,response:s}),{success:!0,sessionId:t})}finally{clearTimeout(a)}}catch(e){if(e instanceof Error&&"AbortError"===e.name)return this.config.logger("[SessionRegistration] Request timed out",{sessionId:t,timeoutMs:this.config.timeoutMs}),{success:!1,sessionId:t,error:"Request timed out"};const r=e instanceof Error?e.message:"Unknown error";return this.config.logger("[SessionRegistration] Unexpected error",{sessionId:t,error:r}),{success:!1,sessionId:t,error:r}}}registerSessionAsync(e){this.registerSession(e).catch(t=>{this.config.logger("[SessionRegistration] Background registration failed",{sessionId:e.session_id,error:t instanceof Error?t.message:"Unknown error"})})}}t.SessionRegistrationService=i},48021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=void 0,t.InMemoryOAuthConfigCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const n=Date.now()+r;this.cache.set(e,{value:t,expiresAt:n})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}},t.NoOpOAuthConfigCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},48505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=void 0;const n=r(27087);class i extends n.StorageProvider{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}t.MemoryStorageProvider=i;class o extends n.NonceCacheProvider{nonces=new Map;async has(e,t){const r=t?`nonce:${t}:${e}`:`nonce:${e}`,n=this.nonces.get(r);return!(!n||Date.now()>n&&(this.nonces.delete(r),1))}async add(e,t,r){const n=r?`nonce:${r}:${e}`:`nonce:${e}`,i=Date.now()+1e3*t;this.nonces.set(n,i)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}t.MemoryNonceCacheProvider=o;class a extends n.IdentityProvider{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#key-1`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return`did:key:z${Buffer.from(e,"base64").toString("base64url").substring(0,32)}`}}t.MemoryIdentityProvider=a},48870:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:i}=e,o="maxItems"===t?n.operators.GT:n.operators.LT;e.fail$data(n._`${r}.length ${o} ${i}`)}};t.default=i},50205:e=>{"use strict";var t=e.exports=function(e,t,n){"function"==typeof t&&(n=t,t={}),r(t,"function"==typeof(n=t.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function r(e,i,o,a,s,c,u,d,l,p){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var f in i(a,s,c,u,d,l,p),a){var h=a[f];if(Array.isArray(h)){if(f in t.arrayKeywords)for(var m=0;m<h.length;m++)r(e,i,o,h[m],s+"/"+f+"/"+m,c,s,f,a,m)}else if(f in t.propsKeywords){if(h&&"object"==typeof h)for(var g in h)r(e,i,o,h[g],s+"/"+f+"/"+n(g),c,s,f,a,g)}else(f in t.keywords||e.allKeys&&!(f in t.skipKeywords))&&r(e,i,o,h,s+"/"+f,c,s,f,a)}o(a,s,c,u,d,l,p)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},50399:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthProviderRegistry=void 0,t.OAuthProviderRegistry=class{configService;validator;providers=new Map;_configuredProvider=null;constructor(e,t){this.configService=e,this.validator=t}async loadFromAgentShield(e){const t=await this.configService.getOAuthConfig(e);this.providers.clear(),this._configuredProvider=t.configuredProvider||null;for(const[e,r]of Object.entries(t.providers))this.providers.set(e,r)}getConfiguredProvider(){return this._configuredProvider}getProvider(e){return this.providers.get(e)||null}getAllProviders(){return Array.from(this.providers.values())}hasProvider(e){return this.providers.has(e)}getProviderNames(){return Array.from(this.providers.keys())}registerCustomProvider(e,t){this.validator&&this.validator.validate(t,e),this.providers.set(e,t)}getProviderWithParams(e){return this.getProvider(e)||null}}},50550:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ecdhAllowed=void 0,t.deriveKey=async function(e,t,r,i,o=new Uint8Array(0),s=new Uint8Array(0)){let f,h;if((0,c.isCryptoKey)(e))(0,u.checkEncCryptoKey)(e,"ECDH"),f=n.KeyObject.from(e);else{if(!(0,d.default)(e))throw new TypeError((0,l.default)(e,...p.types));f=e}if((0,c.isCryptoKey)(t))(0,u.checkEncCryptoKey)(t,"ECDH","deriveBits"),h=n.KeyObject.from(t);else{if(!(0,d.default)(t))throw new TypeError((0,l.default)(t,...p.types));h=t}const m=(0,a.concat)((0,a.lengthAndInput)(a.encoder.encode(r)),(0,a.lengthAndInput)(o),(0,a.lengthAndInput)(s),(0,a.uint32be)(i)),g=(0,n.diffieHellman)({privateKey:h,publicKey:f});return(0,a.concatKdf)(g,i,m)},t.generateEpk=async function(e){let t;if((0,c.isCryptoKey)(e))t=n.KeyObject.from(e);else{if(!(0,d.default)(e))throw new TypeError((0,l.default)(e,...p.types));t=e}switch(t.asymmetricKeyType){case"x25519":return f("x25519");case"x448":return f("x448");case"ec":{const e=(0,o.default)(t);return f("ec",{namedCurve:e})}default:throw new s.JOSENotSupported("Invalid or unsupported EPK")}};const n=r(77598),i=r(57975),o=r(90862),a=r(45935),s=r(39069),c=r(99135),u=r(60322),d=r(29994),l=r(71759),p=r(58242),f=(0,i.promisify)(n.generateKeyPair);t.ecdhAllowed=e=>["P-256","P-384","P-521","X25519","X448"].includes((0,o.default)(e))},51967:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var n=r(36023);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return n.KeywordCxt}});var i=r(38994);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return i.CodeGen}});const o=r(74383),a=r(4220),s=r(6247),c=r(91688),u=r(38994),d=r(89008),l=r(26419),p=r(67218),f=r(10114),h=r(18951),m=(e,t)=>new RegExp(e,t);m.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function b(e){var t,r,n,i,o,a,s,c,u,d,l,p,f,g,v,y,_,b,w,$,S,k,I,P,E;const x=e.strict,O=null===(t=e.code)||void 0===t?void 0:t.optimize,T=!0===O||void 0===O?1:O||0,C=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:m,A=null!==(i=e.uriResolver)&&void 0!==i?i:h.default;return{strictSchema:null===(a=null!==(o=e.strictSchema)&&void 0!==o?o:x)||void 0===a||a,strictNumbers:null===(c=null!==(s=e.strictNumbers)&&void 0!==s?s:x)||void 0===c||c,strictTypes:null!==(d=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==d?d:"log",strictTuples:null!==(p=null!==(l=e.strictTuples)&&void 0!==l?l:x)&&void 0!==p?p:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:x)&&void 0!==g&&g,code:e.code?{...e.code,optimize:T,regExp:C}:{optimize:T,regExp:C},loopRequired:null!==(v=e.loopRequired)&&void 0!==v?v:200,loopEnum:null!==(y=e.loopEnum)&&void 0!==y?y:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(b=e.messages)||void 0===b||b,inlineRefs:null===(w=e.inlineRefs)||void 0===w||w,schemaId:null!==($=e.schemaId)&&void 0!==$?$:"$id",addUsedSchema:null===(S=e.addUsedSchema)||void 0===S||S,validateSchema:null===(k=e.validateSchema)||void 0===k||k,validateFormats:null===(I=e.validateFormats)||void 0===I||I,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(E=e.int32range)||void 0===E||E,uriResolver:A}}class w{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...b(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new u.ValueScope({scope:{},prefixes:v,es5:t,lines:r}),this.logger=function(e){if(!1===e)return x;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),$.call(this,y,e,"NOT SUPPORTED"),$.call(this,_,e,"DEPRECATED","warn"),this._metaOpts=E.call(this),e.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&P.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=f;"id"===r&&(n={...f},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await i.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||o.call(this,r)}async function i(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof a.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await u.call(this,e);this.refs[e]||await i.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let i;if("object"==typeof e){const{schemaId:t}=this.opts;if(i=e[t],void 0!==i&&"string"!=typeof i)throw new Error(`schema ${t} must be string`)}return t=(0,d.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=S.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new c.SchemaEnv({schema:{},schemaId:r});if(t=c.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=S.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,d.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(T.call(this,r,t),!t)return(0,p.eachItem)(r,e=>C.call(this,e)),this;j.call(this,t);const n={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,p.eachItem)(r,0===n.type.length?e=>C.call(this,e,n):e=>n.type.forEach(t=>C.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let i=e;for(const e of t)i=i[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,o=i[e];n&&o&&(i[e]=N(o))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,i=this.opts.addUsedSchema){let o;const{schemaId:a}=this.opts;if("object"==typeof e)o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let s=this._cache.get(e);if(void 0!==s)return s;r=(0,d.normalizeId)(o||r);const u=d.getSchemaRefs.call(this,e,r);return s=new c.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:r,localRefs:u}),this._cache.set(s.schema,s),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=s),n&&this.validateSchema(e,!0),s}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):c.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{c.compileSchema.call(this,e)}finally{this.opts=t}}}function $(e,t,r,n="error"){for(const i in e){const o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function S(e){return e=(0,d.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function I(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function P(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function E(){const e={...this.opts};for(const t of g)delete e[t];return e}w.ValidationError=o.default,w.MissingRefError=a.default,t.default=w;const x={log(){},warn(){},error(){}},O=/^[a-z_$][a-z0-9_$:-]*$/i;function T(e,t){const{RULES:r}=this;if((0,p.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!O.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function C(e,t,r){var n;const i=null==t?void 0:t.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:o}=this;let a=i?o.post:o.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;const s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?A.call(this,a,s,t.before):a.rules.push(s),o.all[e]=s,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function A(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function j(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=N(t)),e.validateSchema=this.compile(t,!0))}const D={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function N(e){return{anyOf:[e,D]}}},51997:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(23665),i={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,n.validateTuple)(e,"items")};t.default=i},52643:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=52643,e.exports=t},52691:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(39069),i=r(45935),o=r(24726),a=r(87925),s=r(71661),c=e=>e.toLowerCase().replace(/^application\//,"");t.default=(e,t,r={})=>{let u;try{u=JSON.parse(i.decoder.decode(t))}catch{}if(!(0,s.default)(u))throw new n.JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:d}=r;if(d&&("string"!=typeof e.typ||c(e.typ)!==c(d)))throw new n.JWTClaimValidationFailed('unexpected "typ" JWT header value',u,"typ","check_failed");const{requiredClaims:l=[],issuer:p,subject:f,audience:h,maxTokenAge:m}=r,g=[...l];void 0!==m&&g.push("iat"),void 0!==h&&g.push("aud"),void 0!==f&&g.push("sub"),void 0!==p&&g.push("iss");for(const e of new Set(g.reverse()))if(!(e in u))throw new n.JWTClaimValidationFailed(`missing required "${e}" claim`,u,e,"missing");if(p&&!(Array.isArray(p)?p:[p]).includes(u.iss))throw new n.JWTClaimValidationFailed('unexpected "iss" claim value',u,"iss","check_failed");if(f&&u.sub!==f)throw new n.JWTClaimValidationFailed('unexpected "sub" claim value',u,"sub","check_failed");if(h&&(y="string"==typeof h?[h]:h,!("string"==typeof(v=u.aud)?y.includes(v):Array.isArray(v)&&y.some(Set.prototype.has.bind(new Set(v))))))throw new n.JWTClaimValidationFailed('unexpected "aud" claim value',u,"aud","check_failed");var v,y;let _;switch(typeof r.clockTolerance){case"string":_=(0,a.default)(r.clockTolerance);break;case"number":_=r.clockTolerance;break;case"undefined":_=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:b}=r,w=(0,o.default)(b||new Date);if((void 0!==u.iat||m)&&"number"!=typeof u.iat)throw new n.JWTClaimValidationFailed('"iat" claim must be a number',u,"iat","invalid");if(void 0!==u.nbf){if("number"!=typeof u.nbf)throw new n.JWTClaimValidationFailed('"nbf" claim must be a number',u,"nbf","invalid");if(u.nbf>w+_)throw new n.JWTClaimValidationFailed('"nbf" claim timestamp check failed',u,"nbf","check_failed")}if(void 0!==u.exp){if("number"!=typeof u.exp)throw new n.JWTClaimValidationFailed('"exp" claim must be a number',u,"exp","invalid");if(u.exp<=w-_)throw new n.JWTExpired('"exp" claim timestamp check failed',u,"exp","check_failed")}if(m){const e=w-u.iat;if(e-_>("number"==typeof m?m:(0,a.default)(m)))throw new n.JWTExpired('"iat" claim timestamp check failed (too far in the past)',u,"iat","check_failed");if(e<0-_)throw new n.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',u,"iat","check_failed")}return u}},53683:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=void 0,t.createProofVerificationError=function(e,t,n){return new r(e,t,n)},t.PROOF_VERIFICATION_ERROR_CODES={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class r extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}t.ProofVerificationError=r},53871:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(17214),t),i(r(98448),t),i(r(32299),t),i(r(75306),t)},54992:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generalDecrypt=async function(e,t,r){if(!(0,o.default)(e))throw new i.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(o.default))throw new i.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new i.JWEInvalid("JWE Recipients has no members");for(const i of e.recipients)try{return await(0,n.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:i.encrypted_key,header:i.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new i.JWEDecryptionFailed};const n=r(70331),i=r(39069),o=r(71661)},55116:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(8956);t.default=n.default},55403:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenedVerify=async function(e,t,r){if(!(0,c.default)(e))throw new o.JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new o.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new o.JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new o.JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new o.JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!(0,c.default)(e.header))throw new o.JWSInvalid("JWS Unprotected Header incorrect type");let h={};if(e.protected)try{const t=(0,n.decode)(e.protected);h=JSON.parse(a.decoder.decode(t))}catch{throw new o.JWSInvalid("JWS Protected Header is invalid")}if(!(0,s.default)(h,e.header))throw new o.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const m={...h,...e.header};let g=!0;if((0,d.default)(o.JWSInvalid,new Map([["b64",!0]]),r?.crit,h,m).has("b64")&&(g=h.b64,"boolean"!=typeof g))throw new o.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:v}=m;if("string"!=typeof v||!v)throw new o.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const y=r&&(0,l.default)("algorithms",r.algorithms);if(y&&!y.has(v))throw new o.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(g){if("string"!=typeof e.payload)throw new o.JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new o.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let _=!1;"function"==typeof t?(t=await t(h,e),_=!0,(0,u.checkKeyTypeWithJwk)(v,t,"verify"),(0,p.isJWK)(t)&&(t=await(0,f.importJWK)(t,v))):(0,u.checkKeyTypeWithJwk)(v,t,"verify");const b=(0,a.concat)(a.encoder.encode(e.protected??""),a.encoder.encode("."),"string"==typeof e.payload?a.encoder.encode(e.payload):e.payload);let w,$;try{w=(0,n.decode)(e.signature)}catch{throw new o.JWSInvalid("Failed to base64url decode the signature")}if(!await(0,i.default)(v,t,w,b))throw new o.JWSSignatureVerificationFailed;if(g)try{$=(0,n.decode)(e.payload)}catch{throw new o.JWSInvalid("Failed to base64url decode the payload")}else $="string"==typeof e.payload?a.encoder.encode(e.payload):e.payload;const S={payload:$};return void 0!==e.protected&&(S.protectedHeader=h),void 0!==e.header&&(S.unprotectedHeader=e.header),_?{...S,key:t}:S};const n=r(3508),i=r(34119),o=r(39069),a=r(45935),s=r(91146),c=r(71661),u=r(89666),d=r(82880),l=r(18610),p=r(45380),f=r(68846)},55921:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationGraphManager=void 0,t.createDelegationGraph=function(e){return new r(e)};class r{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],n=t[e];if(n.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${n.id} issued by ${n.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(n.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${n.id} parentId=${n.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}t.DelegationGraphManager=r},56058:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CONSENT_UI_RESOURCE_URI=void 0,t.CONSENT_UI_RESOURCE_URI="ui://mcpi-consent/authorize"},56853:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofGenerator=void 0,t.createProofResponse=async function(e,t,r,n,i,o={}){const s={data:t},c=new a(r,i),u=await c.generateProof(e,s,n,o);return s.meta={proof:u},s},t.extractCanonicalData=function(e,t){return{request:{method:e.method,...e.params?{params:e.params}:{}},response:t.data}};const n=r(4283),i=r(42275),o=r(81296);class a{identity;cryptoProvider;constructor(e,t){this.identity=e,this.cryptoProvider=t}async generateProof(e,t,r,n={}){const i=await this.generateCanonicalHashes(e,t),o={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:i.requestHash,responseHash:i.responseHash,...n};return{jws:await this.generateJWS(o),meta:o}}async generateCanonicalHashes(e,t){const r={method:e.method,...e.params?{params:e.params}:{}},n=t.data;return{requestHash:await this.generateSHA256Hash(r),responseHash:await this.generateSHA256Hash(n)}}async generateSHA256Hash(e){const t=this.canonicalizeJSON(e),r=(new TextEncoder).encode(t);return this.cryptoProvider.hash(r)}canonicalizeJSON(e){return(0,i.canonicalize)(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await(0,n.importPKCS8)(t,"EdDSA"),i={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new n.SignJWT(i).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);const n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=r.subarray(0,32),o=new Uint8Array(n.length+i.length);o.set(n),o.set(i,n.length);let a="";for(let e=0;e<o.length;e++)a+=String.fromCharCode(o[e]);const s=btoa(a);return"-----BEGIN PRIVATE KEY-----\n"+(s.match(/.{1,64}/g)?.join("\n")??s)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const n=await this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==n.requestHash||e.meta.responseHash!==n.responseHash)return!1;const i=this.base64PublicKeyToJWK(this.identity.publicKey);return new o.CryptoService(this.cryptoProvider).verifyJWS(e.jws,i,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch{return!1}}base64PublicKeyToJWK(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);if(32!==r.length)throw new Error(`Invalid Ed25519 public key length: ${r.length}`);let n="";for(let e=0;e<r.length;e++)n+=String.fromCharCode(r[e]);return{kty:"OKP",crv:"Ed25519",x:btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),kid:this.identity.kid}}}t.ProofGenerator=a},57975:e=>{"use strict";e.exports=require("node:util")},58242:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.types=void 0;const n=r(99135),i=r(29994);t.default=e=>(0,i.default)(e)||(0,n.isCryptoKey)(e);const o=["KeyObject"];t.types=o,(globalThis.CryptoKey||n.default?.CryptoKey)&&o.push("CryptoKey")},58421:(e,t,r)=>{"use strict";r.d(t,{Zs:()=>s,hG:()=>u});var n=r(83307),i=r(38296);function o(e){return"completed"===e||"failed"===e||"cancelled"===e}var a=r(35638);class s{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(i.Sq,e=>{this._oncancel(e)}),this.setNotificationHandler(i._r,e=>{this._onprogress(e)}),this.setRequestHandler(i.tC,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(i.Ql,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new i.Nh(i.O4.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(i.oQ,async(e,t)=>{const r=async()=>{const n=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,n=this._requestResolvers.get(r);if(n)if(this._requestResolvers.delete(r),"response"===e.type)n(t);else{const e=t;n(new i.Nh(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const a=await this._taskStore.getTask(n,t.sessionId);if(!a)throw new i.Nh(i.O4.InvalidParams,`Task not found: ${n}`);if(!o(a.status))return await this._waitForTaskUpdate(n,t.signal),await r();if(o(a.status)){const e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n),{...e,_meta:{...e._meta,[i.EV]:{taskId:n}}}}return await r()};return await r()}),this.setRequestHandler(i.zR,async(e,t)=>{try{const{tasks:r,nextCursor:n}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:n,_meta:{}}}catch(e){throw new i.Nh(i.O4.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(i.gd,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new i.Nh(i.O4.InvalidParams,`Task not found: ${e.params.taskId}`);if(o(r.status))throw new i.Nh(i.O4.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new i.Nh(i.O4.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...n}}catch(e){if(e instanceof i.Nh)throw e;throw new i.Nh(i.O4.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),i.Nh.fromError(i.O4.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const n=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{n?.(e,t),(0,i.ig)(e)||(0,i.LW)(e)?this._onresponse(e):(0,i.vo)(e)?this._onrequest(e,t):(0,i.lg)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=i.Nh.fromError(i.O4.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[i.EV]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:i.O4.MethodNotFound,message:"Method not found"}};return void(o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:t,timestamp:Date.now()},n?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):n?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const s=(0,i.bZ)(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;const r={relatedRequestId:e.id};o&&(r.relatedTask={taskId:o}),await this.notification(t,r)},sendRequest:async(t,r,n)=>{if(a.signal.aborted)throw new i.Nh(i.O4.ConnectionClosed,"Request was cancelled");const s={...n,relatedRequestId:e.id};o&&!s.relatedTask&&(s.relatedTask={taskId:o});const u=s.relatedTask?.taskId??o;return u&&c&&await c.updateTaskStatus(u,"input_required"),await this.request(t,r,s)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async t=>{if(a.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))},async t=>{if(a.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:i.O4.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),void o(e)}i(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void((0,i.ig)(e)?r(e):r(new i.Nh(e.error.code,e.error.message,e.error.data)));const n=this._responseHandlers.get(t);if(void 0===n)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if((0,i.ig)(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(o=!0,this._taskProgressTokens.set(e.taskId,t))}}o||this._progressHandlers.delete(t),(0,i.ig)(e)?n(e):n(i.Nh.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{const n=await this.request(e,t,r);yield{type:"result",result:n}}catch(e){yield{type:"error",error:e instanceof i.Nh?e:new i.Nh(i.O4.InternalError,String(e))}}return}let a;try{const n=await this.request(e,i.Mg,r);if(!n.task)throw new i.Nh(i.O4.InternalError,"Task creation did not return a task");for(a=n.task.taskId,yield{type:"taskCreated",task:n.task};;){const e=await this.getTask({taskId:a},r);if(yield{type:"taskStatus",task:e},o(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:a},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new i.Nh(i.O4.InternalError,`Task ${a} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new i.Nh(i.O4.InternalError,`Task ${a} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:a},t,r);return void(yield{type:"result",result:e})}const n=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,n)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof i.Nh?e:new i.Nh(i.O4.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s,task:c,relatedTask:u}=r??{};return new Promise((d,l)=>{const p=e=>{l(e)};if(!this._transport)return void p(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(e){return void p(e)}r?.signal?.throwIfAborted();const f=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),c&&(h.params={...h.params,task:c}),u&&(h.params={...h.params,_meta:{...h.params?._meta||{},[i.EV]:u}});const m=e=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof i.Nh?e:new i.Nh(i.O4.RequestTimeout,String(e));l(t)};this._responseHandlers.set(f,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return l(e);try{const r=(0,n.xL)(t,e.result);r.success?d(r.data):l(r.error)}catch(e){l(e)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});const g=r?.timeout??6e4;this._setupTimeout(f,g,r?.maxTotalTimeout,()=>m(i.Nh.fromError(i.O4.RequestTimeout,"Request timed out",{timeout:g})),r?.resetTimeoutOnProgress??!1);const v=u?.taskId;if(v){const e=e=>{const t=this._responseHandlers.get(f);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,e),this._enqueueTaskMessage(v,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(f),l(e)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:s}).catch(e=>{this._cleanupTimeout(f),l(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},i.Sc,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},i.a5,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},i.gH,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const n={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[i.EV]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:n,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[i.EV]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[i.EV]:t.relatedTask}}}),await this._transport.send(n,t)}setRequestHandler(e,t){const r=(0,a.v$)(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,n)=>{const i=(0,a.EQ)(e,r);return Promise.resolve(t(i,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=(0,a.v$)(e);this._notificationHandlers.set(r,r=>{const n=(0,a.EQ)(e,r);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&(0,i.vo)(t.message)){const r=t.message.id,n=this._requestResolvers.get(r);n?(n(new i.Nh(i.O4.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted)return void n(new i.Nh(i.O4.InvalidRequest,"Request cancelled"));const o=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(o),n(new i.Nh(i.O4.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const n=await r.getTask(e,t);if(!n)throw new i.Nh(i.O4.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(e,n,a)=>{await r.storeTaskResult(e,n,a,t);const s=await r.getTask(e,t);if(s){const t=i.ki.parse({method:"notifications/tasks/status",params:s});await this.notification(t),o(s.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,n,a)=>{const s=await r.getTask(e,t);if(!s)throw new i.Nh(i.O4.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(o(s.status))throw new i.Nh(i.O4.InvalidParams,`Cannot update task "${e}" from terminal status "${s.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,n,a,t);const c=await r.getTask(e,t);if(c){const t=i.ki.parse({method:"notifications/tasks/status",params:c});await this.notification(t),o(c.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function c(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function u(e,t){const r={...e};for(const e in t){const n=e,i=t[n];if(void 0===i)continue;const o=r[n];c(o)&&c(i)?r[n]={...o,...i}:r[n]=i}return r}},58459:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnsecuredJWT=void 0;const n=r(3508),i=r(45935),o=r(39069),a=r(52691),s=r(59333);class c extends s.ProduceJWT{encode(){return`${n.encode(JSON.stringify({alg:"none"}))}.${n.encode(JSON.stringify(this._payload))}.`}static decode(e,t){if("string"!=typeof e)throw new o.JWTInvalid("Unsecured JWT must be a string");const{0:r,1:s,2:c,length:u}=e.split(".");if(3!==u||""!==c)throw new o.JWTInvalid("Invalid Unsecured JWT");let d;try{if(d=JSON.parse(i.decoder.decode(n.decode(r))),"none"!==d.alg)throw new Error}catch{throw new o.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,a.default)(d,n.decode(s),t),header:d}}}t.UnsecuredJWT=c},58621:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.compactDecrypt=async function(e,t,r){if(e instanceof Uint8Array&&(e=o.decoder.decode(e)),"string"!=typeof e)throw new i.JWEInvalid("Compact JWE must be a string or Uint8Array");const{0:a,1:s,2:c,3:u,4:d,length:l}=e.split(".");if(5!==l)throw new i.JWEInvalid("Invalid Compact JWE");const p=await(0,n.flattenedDecrypt)({ciphertext:u,iv:c||void 0,protected:a,tag:d||void 0,encrypted_key:s||void 0},t,r),f={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return"function"==typeof t?{...f,key:p.key}:f};const n=r(70331),i=r(39069),o=r(45935)},59035:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const n=r(28825),i=r(38994),o=i.operators,a={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>i.str`should be ${a[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>i._`{comparison: ${a[e].okStr}, limit: ${t}}`};t.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:t,data:r,schemaCode:o,keyword:s,it:c}=e,{opts:u,self:d}=c;if(!u.validateFormats)return;const l=new n.KeywordCxt(c,d.RULES.all.format.definition,"format");function p(e){return i._`${e}.compare(${r}, ${o}) ${a[s].fail} 0`}l.$data?function(){const r=t.scopeValue("formats",{ref:d.formats,code:u.code.formats}),n=t.const("fmt",i._`${r}[${l.schemaCode}]`);e.fail$data((0,i.or)(i._`typeof ${n} != "object"`,i._`${n} instanceof RegExp`,i._`typeof ${n}.compare != "function"`,p(n)))}():function(){const r=l.schema,n=d.formats[r];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${s}": format "${r}" does not define "compare" function`);const o=t.scopeValue("formats",{key:r,ref:n,code:u.code.formats?i._`${u.code.formats}${(0,i.getProperty)(r)}`:void 0});e.fail$data(p(o))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.formatLimitDefinition),e)},59333:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProduceJWT=void 0;const n=r(24726),i=r(71661),o=r(87925);function a(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}t.ProduceJWT=class{_payload;constructor(e={}){if(!(0,i.default)(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:a("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:a("setNotBefore",(0,n.default)(e))}:this._payload={...this._payload,nbf:(0,n.default)(new Date)+(0,o.default)(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:a("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:a("setExpirationTime",(0,n.default)(e))}:this._payload={...this._payload,exp:(0,n.default)(new Date)+(0,o.default)(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:(0,n.default)(new Date)}:e instanceof Date?this._payload={...this._payload,iat:a("setIssuedAt",(0,n.default)(e))}:this._payload="string"==typeof e?{...this._payload,iat:a("setIssuedAt",(0,n.default)(new Date)+(0,o.default)(e))}:{...this._payload,iat:a("setIssuedAt",e)},this}}},59768:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new n.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};const n=r(39069)},60322:(e,t)=>{"use strict";function r(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function n(e,t){return e.name===t}function i(e){return parseInt(e.name.slice(4),10)}function o(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}Object.defineProperty(t,"__esModule",{value:!0}),t.checkSigCryptoKey=function(e,t,...a){switch(t){case"HS256":case"HS384":case"HS512":{if(!n(e.algorithm,"HMAC"))throw r("HMAC");const o=parseInt(t.slice(2),10);if(i(e.algorithm.hash)!==o)throw r(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!n(e.algorithm,"RSASSA-PKCS1-v1_5"))throw r("RSASSA-PKCS1-v1_5");const o=parseInt(t.slice(2),10);if(i(e.algorithm.hash)!==o)throw r(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!n(e.algorithm,"RSA-PSS"))throw r("RSA-PSS");const o=parseInt(t.slice(2),10);if(i(e.algorithm.hash)!==o)throw r(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw r("Ed25519 or Ed448");break;case"Ed25519":if(!n(e.algorithm,"Ed25519"))throw r("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!n(e.algorithm,"ECDSA"))throw r("ECDSA");const i=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==i)throw r(i,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}o(e,a)},t.checkEncCryptoKey=function(e,t,...a){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!n(e.algorithm,"AES-GCM"))throw r("AES-GCM");const i=parseInt(t.slice(1,4),10);if(e.algorithm.length!==i)throw r(i,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!n(e.algorithm,"AES-KW"))throw r("AES-KW");const i=parseInt(t.slice(1,4),10);if(e.algorithm.length!==i)throw r(i,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw r("ECDH, X25519, or X448")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!n(e.algorithm,"PBKDF2"))throw r("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!n(e.algorithm,"RSA-OAEP"))throw r("RSA-OAEP");const o=parseInt(t.slice(9),10)||1;if(i(e.algorithm.hash)!==o)throw r(`SHA-${o}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}o(e,a)}},60808:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.jwtDecrypt=async function(e,t,r){const a=await(0,n.compactDecrypt)(e,t,r),s=(0,i.default)(a.protectedHeader,a.plaintext,r),{protectedHeader:c}=a;if(void 0!==c.iss&&c.iss!==s.iss)throw new o.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch',s,"iss","mismatch");if(void 0!==c.sub&&c.sub!==s.sub)throw new o.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch',s,"sub","mismatch");if(void 0!==c.aud&&JSON.stringify(c.aud)!==JSON.stringify(s.aud))throw new o.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch',s,"aud","mismatch");const u={payload:s,protectedHeader:c};return"function"==typeof t?{...u,key:a.key}:u};const n=r(58621),i=r(52691),o=r(39069)},61494:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GeneralSign=void 0;const n=r(30131),i=r(39069);class o{parent;protectedHeader;unprotectedHeader;options;key;constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setProtectedHeader(e){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=e,this}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addSignature(...e){return this.parent.addSignature(...e)}sign(...e){return this.parent.sign(...e)}done(){return this.parent}}t.GeneralSign=class{_payload;_signatures=[];constructor(e){this._payload=e}addSignature(e,t){const r=new o(this,e,t);return this._signatures.push(r),r}async sign(){if(!this._signatures.length)throw new i.JWSInvalid("at least one signature must be added");const e={signatures:[],payload:""};for(let t=0;t<this._signatures.length;t++){const r=this._signatures[t],o=new n.FlattenedSign(this._payload);o.setProtectedHeader(r.protectedHeader),o.setUnprotectedHeader(r.unprotectedHeader);const{payload:a,...s}=await o.sign(r.key,r.options);if(0===t)e.payload=a;else if(e.payload!==a)throw new i.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");e.signatures.push(s)}return e}}},62175:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthService=t.defaultSecretResolver=void 0,t.defaultSecretResolver={async resolveSecret(e){if("undefined"!=typeof process&&process.env)return process.env[e]}},t.OAuthService=class{config;constructor(e){this.config={configService:e.configService,fetchProvider:e.fetchProvider,agentShieldApiUrl:e.agentShieldApiUrl,agentShieldApiKey:e.agentShieldApiKey,projectId:e.projectId,logger:e.logger||(()=>{}),secretResolver:e.secretResolver||t.defaultSecretResolver}}async resolveClientSecret(e){if(e.metadata?.clientSecretName){const t=e.metadata.clientSecretName;this.config.logger("[OAuthService] Resolving client secret by name",{secretName:t,version:e.metadata.clientSecretVersion});const r=await this.config.secretResolver.resolveSecret(t);if(r)return this.config.logger("[OAuthService] Client secret resolved successfully",{secretName:t}),r;this.config.logger("[OAuthService] Client secret not found in secure storage",{secretName:t})}if(e.clientSecret)return this.config.logger("[OAuthService] DEPRECATED: Using legacy clientSecret field - migrate to metadata.clientSecretName for better security",{telemetry:{event:"oauth.deprecated_client_secret_used",hasMetadata:!!e.metadata,hasSecretName:!!e.metadata?.clientSecretName}}),e.clientSecret}async exchangeToken(e,t,r,n){const i=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];if(!i)throw new Error(`Provider "${e}" not configured for project "${this.config.projectId}"`);if(i.supportsPKCE&&!i.proxyMode){if(!r)throw new Error(`Provider "${e}" requires PKCE code_verifier for token exchange`);return this.exchangeTokenPKCE(i,t,r,n||"")}if(i.proxyMode)return this.exchangeTokenProxy(i,t,r,n||"");throw new Error(`Provider "${e}" configuration is invalid: must support PKCE or use proxy mode`)}async exchangeTokenPKCE(e,t,r,n){const i=await this.resolveClientSecret(e);this.config.logger("[OAuthService] Exchanging token with PKCE",{provider:e.authorizationUrl,tokenUrl:e.tokenUrl,hasClientSecret:!!i,resolvedViaSecretName:!!e.metadata?.clientSecretName});const o={grant_type:"authorization_code",code:t,redirect_uri:n,client_id:e.clientId,code_verifier:r};i&&(o.client_secret=i);const a=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(o).toString()});if(!a.ok){const t=await a.text().catch(()=>"Unknown error");let r;try{r=JSON.parse(t)}catch{r={error:t}}const n=r.error_description||r.error||t;throw this.config.logger("[OAuthService] Token exchange failed",{status:a.status,error:n,provider:e.tokenUrl}),new Error(`Token exchange failed: ${n} (${a.status})`)}const s=await a.json();if(s.error)throw this.config.logger("[OAuthService] Token exchange returned error (200 status)",{error:s.error,errorDescription:s.error_description,errorUri:s.error_uri,provider:e.tokenUrl,responseKeys:Object.keys(s)}),new Error(`Token exchange failed: ${s.error_description||s.error}`);if(!s.access_token)throw this.config.logger("[OAuthService] Token response missing access_token",{responseKeys:Object.keys(s),provider:e.tokenUrl}),new Error("Token response missing access_token");const c=s.expires_in||3600,u=Date.now()+1e3*c,d={access_token:s.access_token,refresh_token:s.refresh_token,expires_in:c,expires_at:u,token_type:s.token_type||"Bearer",scope:s.scope};return this.config.logger("[OAuthService] Token exchange successful",{provider:e.tokenUrl,expiresAt:new Date(u).toISOString(),hasRefreshToken:!!d.refresh_token}),d}async exchangeTokenProxy(e,t,r,n){const i=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Exchanging token via proxy",{proxyUrl:i,provider:e.authorizationUrl,hasCodeVerifier:!!r,supportsPKCE:e.supportsPKCE});const o={grant_type:"authorization_code",code:t,redirect_uri:n||"",provider:e.authorizationUrl,project_id:this.config.projectId};e.supportsPKCE&&r&&(o.code_verifier=r);const a=await this.config.fetchProvider.fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify(o)});if(!a.ok){const e=await a.text().catch(()=>"Unknown error");let t;try{t=JSON.parse(e)}catch{t={error:e}}const r=t.error_description||t.error||e;throw this.config.logger("[OAuthService] Proxy token exchange failed",{status:a.status,error:r,proxyUrl:i}),new Error(`Proxy token exchange failed: ${r} (${a.status})`)}const s=await a.json(),c=s.data||s;if(!c.access_token)throw new Error("Proxy token response missing access_token");const u=c.expires_in||3600,d=Date.now()+1e3*u,l={access_token:c.access_token,refresh_token:c.refresh_token,expires_in:u,expires_at:d,token_type:c.token_type||"Bearer",scope:c.scope};return this.config.logger("[OAuthService] Proxy token exchange successful",{proxyUrl:i,expiresAt:new Date(d).toISOString(),hasRefreshToken:!!l.refresh_token}),l}async refreshToken(e,t){const r=(await this.config.configService.getOAuthConfig(this.config.projectId)).providers[e];return r?r.supportsPKCE&&!r.proxyMode?this.refreshTokenPKCE(r,t):r.proxyMode?this.refreshTokenProxy(r,t):null:(this.config.logger("[OAuthService] Provider not found for refresh",{provider:e}),null)}async refreshTokenPKCE(e,t){this.config.logger("[OAuthService] Refreshing token with PKCE",{provider:e.tokenUrl});try{const r=await this.config.fetchProvider.fetch(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId}).toString()});if(!r.ok)return this.config.logger("[OAuthService] Token refresh failed",{status:r.status,provider:e.tokenUrl}),null;const n=await r.json();if(!n.access_token)return this.config.logger("[OAuthService] Token refresh response missing access_token"),null;const i=n.expires_in||3600,o=Date.now()+1e3*i,a={access_token:n.access_token,refresh_token:n.refresh_token||t,expires_in:i,expires_at:o,token_type:n.token_type||"Bearer",scope:n.scope};return this.config.logger("[OAuthService] Token refresh successful",{provider:e.tokenUrl,expiresAt:new Date(o).toISOString()}),a}catch(t){return this.config.logger("[OAuthService] Token refresh error",{error:t instanceof Error?t.message:String(t),provider:e.tokenUrl}),null}}async refreshTokenProxy(e,t){const r=`${this.config.agentShieldApiUrl}/api/v1/oauth/token`;this.config.logger("[OAuthService] Refreshing token via proxy",{proxyUrl:r,provider:e.authorizationUrl});try{const n=await this.config.fetchProvider.fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.agentShieldApiKey}`},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,provider:e.authorizationUrl,project_id:this.config.projectId})});if(!n.ok)return this.config.logger("[OAuthService] Proxy token refresh failed",{status:n.status,proxyUrl:r}),null;const i=await n.json(),o=i.data||i;if(!o.access_token)return this.config.logger("[OAuthService] Proxy token refresh response missing access_token"),null;const a=o.expires_in||3600,s=Date.now()+1e3*a,c={access_token:o.access_token,refresh_token:o.refresh_token||t,expires_in:a,expires_at:s,token_type:o.token_type||"Bearer",scope:o.scope};return this.config.logger("[OAuthService] Proxy token refresh successful",{proxyUrl:r,expiresAt:new Date(s).toISOString()}),c}catch(e){return this.config.logger("[OAuthService] Proxy token refresh error",{error:e instanceof Error?e.message:String(e),proxyUrl:r}),null}}}},62408:e=>{"use strict";e.exports=require("@kya-os/contracts")},63146:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEd25519DidKey=c,t.extractPublicKeyFromDidKey=u,t.publicKeyToJwk=d,t.createDidKeyResolver=function(){return{resolve:async e=>{if(!c(e))return null;const t=u(e);if(!t)return null;const r=d(t),n=e.replace("did:key:",""),o=(0,i.didKeyFragment)(e);return{id:e,verificationMethod:[{id:`${e}#${o}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${o}`],assertionMethod:[`${e}#${o}`]}}}},t.resolveDidKeySync=function(e){if(!c(e))return null;const t=u(e);if(!t)return null;const r=d(t),n=e.replace("did:key:",""),o=(0,i.didKeyFragment)(e);return{id:e,verificationMethod:[{id:`${e}#${o}`,type:"Ed25519VerificationKey2020",controller:e,publicKeyJwk:r,publicKeyMultibase:n}],authentication:[`${e}#${o}`],assertionMethod:[`${e}#${o}`]}};const n=r(69459),i=r(75306),o=r(98448),a=new Uint8Array([237,1]),s=32;function c(e){return e.startsWith("did:key:z6Mk")}function u(e){if(!e.startsWith("did:key:z"))return null;try{const t=e.replace("did:key:","").slice(1),r=(0,n.base58Decode)(t);return r.length<a.length+s||r[0]!==a[0]||r[1]!==a[1]?null:r.slice(a.length)}catch{return null}}function d(e){return{kty:"OKP",crv:"Ed25519",x:(0,o.base64urlEncodeFromBytes)(e)}}},63969:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=function e(t){if(null===t)return"null";if("boolean"==typeof t)return t.toString();if("number"==typeof t){if(!isFinite(t))throw new Error("Cannot canonicalize non-finite number");return JSON.stringify(t)}if("string"==typeof t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(t=>e(t)).join(",")+"]";if("object"==typeof t)return"{"+Object.keys(t).sort().map(r=>{const n=e(t[r]);return JSON.stringify(r)+":"+n}).join(",")+"}";throw new Error("Cannot canonicalize type: "+typeof t)},t.createUnsignedVCJWT=function(e,t={}){const r={alg:"EdDSA",typ:"JWT"};t.keyId&&(r.kid=t.keyId);const i="string"==typeof e.issuer?e.issuer:e.issuer?.id,o=e.credentialSubject?.id;let a,s;e.expirationDate&&"string"==typeof e.expirationDate&&(a=Math.floor(new Date(e.expirationDate).getTime()/1e3)),e.issuanceDate&&"string"==typeof e.issuanceDate&&(s=Math.floor(new Date(e.issuanceDate).getTime()/1e3));const c={...e};delete c.proof;const u={iss:i,vc:c};o&&(u.sub=o),a&&(u.exp=a),s&&(u.iat=s),e.id&&"string"==typeof e.id&&(u.jti=e.id);const d=(0,n.base64urlEncodeFromString)(JSON.stringify(r)),l=(0,n.base64urlEncodeFromString)(JSON.stringify(u));return{header:r,payload:u,encodedHeader:d,encodedPayload:l,signingInput:`${d}.${l}`}},t.completeVCJWT=function(e,t){return`${e}.${t}`},t.parseVCJWT=function(e){const t=e.split(".");if(3!==t.length)return null;try{const e=i(t[0]),r=i(t[1]);return{header:JSON.parse(e),payload:JSON.parse(r),signature:t[2],signingInput:`${t[0]}.${t[1]}`}}catch{return null}};const n=r(98448);function i(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return"undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("utf-8")}},65067:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserDidManager=void 0;const n=r(75306);t.UserDidManager=class{config;sessionDidCache=new Map;sessionKeyPairCache=new Map;constructor(e){this.config=e}async getKeyPairForSession(e,t){if(this.sessionKeyPairCache.has(e))return this.sessionKeyPairCache.get(e);if(t?.provider&&t?.subject&&this.config.storage?.getKeyPairByOAuth)try{const r=await this.config.storage.getKeyPairByOAuth(t.provider,t.subject);if(r)return this.sessionKeyPairCache.set(e,r),r}catch(e){console.warn("[UserDidManager] OAuth key pair lookup failed:",e)}if(this.config.storage?.getKeyPair)try{const t=await this.config.storage.getKeyPair(e);if(t)return this.sessionKeyPairCache.set(e,t),t}catch(e){console.warn("[UserDidManager] Session key pair lookup failed:",e)}return null}async getOrCreateUserDid(e,t){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(t&&t.provider&&t.subject&&this.config.storage?.getByOAuth)try{const r=await this.config.storage.getByOAuth(t.provider,t.subject);if(r){if(console.error("[UserDidManager] Found persistent user DID from OAuth mapping:",{provider:t.provider,userDid:r.substring(0,20)+"..."}),this.sessionDidCache.set(e,r),this.config.storage)try{await this.config.storage.set(e,r,1800)}catch(e){console.warn("[UserDidManager] Failed to cache persistent DID in session storage:",e)}return r}}catch(e){console.warn("[UserDidManager] OAuth lookup failed, falling back to session storage:",e)}if(this.config.storage)try{const r=await this.config.storage.get(e);if(r){if(this.sessionDidCache.set(e,r),t&&t.provider&&t.subject&&this.config.storage.setByOAuth)try{await this.config.storage.setByOAuth(t.provider,t.subject,r,7776e3),console.error("[UserDidManager] Created persistent OAuth mapping for existing user DID:",{provider:t.provider,userDid:r.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}return r}}catch(e){console.warn("[UserDidManager] Storage.get failed:",e)}return null}async setUserDidForSession(e,t,r){if(this.sessionDidCache.set(e,t),this.config.storage)try{await this.config.storage.set(e,t,1800)}catch(e){console.warn("[UserDidManager] Failed to store user DID in session storage:",e)}if(r?.provider&&r?.subject&&this.config.storage?.setByOAuth)try{await this.config.storage.setByOAuth(r.provider,r.subject,t,7776e3),console.error("[UserDidManager] Created OAuth → DID mapping:",{provider:r.provider,userDid:t.substring(0,20)+"..."})}catch(e){console.warn("[UserDidManager] Failed to create OAuth mapping:",e)}}async generateUserDid(){return(await this.generateUserDidWithKeyPair()).did}async generateUserDidWithKeyPair(){this.config.useDidWeb&&this.config.didWebBaseUrl&&console.warn("[UserDidManager] did:web not yet implemented, using did:key");const e=await this.config.crypto.generateKeyPair(),t=this.base64ToBytes(e.publicKey),r=this.generateDidKeyFromPublicKey(t),i=`${r}#${(0,n.didKeyFragment)(r)}`;return{did:r,publicKey:e.publicKey,privateKey:e.privateKey,keyId:i}}generateDidKeyFromPublicKey(e){const t=new Uint8Array([237,1]),r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),`did:key:z${this.base58Encode(r)}`}base58Encode(e){let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let r="";for(;t>0;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}base64ToBytes(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(t,"base64"));{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}}async getUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage){const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}return null}async clearUserDid(e){if(this.sessionDidCache.delete(e),this.config.storage)try{await this.config.storage.delete(e)}catch(e){console.warn("[UserDidManager] Storage.delete failed, continuing:",e)}}clearCache(){this.sessionDidCache.clear()}}},65358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o=r(6013),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>n._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:s,schemaCode:c,it:u}=e;if(!a&&0===s.length)throw new Error("enum must have non-empty array");const d=s.length>=u.opts.loopEnum;let l;const p=()=>null!=l?l:l=(0,i.useFunc)(t,o.default);let f;if(d||a)f=t.let("valid"),e.block$data(f,function(){t.assign(f,!1),t.forOf("v",c,e=>t.if(n._`${p()}(${r}, ${e})`,()=>t.assign(f,!0).break()))});else{if(!Array.isArray(s))throw new Error("ajv implementation error");const e=t.const("vSchema",c);f=(0,n.or)(...s.map((t,i)=>function(e,t){const i=s[t];return"object"==typeof i&&null!==i?n._`${p()}(${r}, ${e}[${t}])`:n._`${r} === ${i}`}(e,i)))}e.pass(f)}};t.default=a},66766:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598);t.default=e=>e.d?(0,n.createPrivateKey)({format:"jwk",key:e}):(0,n.createPublicKey)({format:"jwk",key:e})},67218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const n=r(38994),i=r(28261);function o(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const i=n.RULES.keywords;for(const r in t)i[r]||h(e,`unknown keyword: "${r}"`)}function a(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function s(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function c(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function u({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(o,a,s,c)=>{const u=void 0===s?a:s instanceof n.Name?(a instanceof n.Name?e(o,a,s):t(o,a,s),s):a instanceof n.Name?(t(o,s,a),a):r(a,s);return c!==n.Name||u instanceof n.Name?u:i(o,u)}}function d(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",n._`{}`);return void 0!==t&&l(e,r,t),r}function l(e,t,r){Object.keys(r).forEach(r=>e.assign(n._`${t}${(0,n.getProperty)(r)}`,!0))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(o(e,t),!a(t,e.self.RULES.all))},t.checkUnknownRules=o,t.schemaHasRules=a,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,i,o){if(!o){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return n._`${r}`}return n._`${e}${t}${(0,n.getProperty)(i)}`},t.unescapeFragment=function(e){return c(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(s(e))},t.escapeJsonPointer=s,t.unescapeJsonPointer=c,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:u({mergeNames:(e,t,r)=>e.if(n._`${r} !== true && ${t} !== undefined`,()=>{e.if(n._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,n._`${r} || {}`).code(n._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(n._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,n._`${r} || {}`),l(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:d}),items:u({mergeNames:(e,t,r)=>e.if(n._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,n._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(n._`${r} !== true`,()=>e.assign(r,!0===t||n._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=d,t.setEvaluated=l;const p={};var f;function h(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:p[t.code]||(p[t.code]=new i._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(f||(t.Type=f={})),t.getErrorPath=function(e,t,r){if(e instanceof n.Name){const i=t===f.Num;return r?i?n._`"[" + ${e} + "]"`:n._`"['" + ${e} + "']"`:i?n._`"/" + ${e}`:n._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,n.getProperty)(e).toString():"/"+s(e)},t.checkStrictMode=h},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;0!==i--;){var a=o[i];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r}},68252:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderResolver=t.CredentialAuthModeError=t.ConsentOnlyModeError=void 0;class r extends Error{toolProtection;constructor(e){super("Tool is configured for consent-only mode (no OAuth provider required)"),this.toolProtection=e,this.name="ConsentOnlyModeError"}}t.ConsentOnlyModeError=r;class n extends Error{toolProtection;provider;constructor(e,t){super(`Tool requires credential authentication with provider "${t}"`),this.toolProtection=e,this.name="CredentialAuthModeError",this.provider=t}}t.CredentialAuthModeError=n,t.ProviderResolver=class{registry;configService;constructor(e,t){this.registry=e,this.configService=t}isConsentOnlyMode(e){return"none"===e.authorization?.type}isCredentialAuthMode(e){return"password"===e.authorization?.type?{isCredential:!0,provider:e.authorization.provider||"credentials"}:{isCredential:!1}}async resolveProvider(e,t){if(this.isConsentOnlyMode(e))throw console.error("[ProviderResolver] Tool is consent-only mode (authorization.type=none), skipping OAuth resolution"),new r(e);const i=this.isCredentialAuthMode(e);if(i.isCredential)throw console.error(`[ProviderResolver] Tool requires credential auth (authorization.type=password), provider="${i.provider}"`),new n(e,i.provider);if(e.oauthProvider){if(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),!this.registry.hasProvider(e.oauthProvider))throw new Error(`Provider "${e.oauthProvider}" not configured for project "${t}". Add provider in project settings.`);return e.oauthProvider}const o=this.inferProviderFromScopes(e.requiredScopes||[]);if(o&&(0===this.registry.getProviderNames().length&&await this.registry.loadFromAgentShield(t),this.registry.hasProvider(o)))return console.error(`[ProviderResolver] Inferred provider "${o}" from scopes`),o;await this.registry.loadFromAgentShield(t);const a=this.registry.getConfiguredProvider();if(a&&this.registry.hasProvider(a))return console.warn(`[ProviderResolver] Tool does not specify oauthProvider. Using project-configured provider "${a}" as fallback. Consider explicitly setting oauthProvider in tool protection config.`),a;throw new Error(`Tool requires OAuth but no provider is configured for project "${t}". Configure an OAuth provider in AgentShield dashboard.`)}inferProviderFromScopes(e){if(!e||0===e.length)return null;const t=e.map(e=>e.split(":")[0].toLowerCase()),r={github:"github",google:"google",gmail:"google",calendar:"google",microsoft:"microsoft",outlook:"microsoft",slack:"slack",auth0:"auth0",okta:"okta"},n=new Set(t.map(e=>r[e]).filter(Boolean));return 1===n.size?Array.from(n)[0]:null}}},68423:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598);t.default=(e,t)=>{let r;try{r=e instanceof n.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}},68681:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildDelegationProofJWT=async function(e){const{agentDid:t,userDid:r,delegationId:i,delegationChain:o,scopes:a,privateKeyJwk:s,kid:c,targetHostname:u}=e,d=await(0,n.importJWK)(s,"EdDSA"),l=Math.floor(Date.now()/1e3),p=l+60;return await new n.SignJWT({delegation_id:i,delegation_chain:o,scope:a.join(",")}).setProtectedHeader({alg:"EdDSA",kid:c}).setIssuer(t).setSubject(r).setJti(crypto.randomUUID()).setAudience(u).setIssuedAt(l).setExpirationTime(p).sign(d)},t.buildChainString=function(e){return e.id||e.vcId?e.vcId?`${e.vcId}>${e.id}`:e.id:""};const n=r(4283)},68846:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.importSPKI=async function(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw new TypeError('"spki" must be SPKI formatted string');return(0,i.fromSPKI)(e,t,r)},t.importX509=async function(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw new TypeError('"x509" must be X.509 formatted string');return(0,i.fromX509)(e,t,r)},t.importPKCS8=async function(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,i.fromPKCS8)(e,t,r)},t.importJWK=async function(e,t){if(!(0,s.default)(e))throw new TypeError("JWK must be an object");switch(t||=e.alg,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return(0,n.decode)(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new a.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(0,o.default)({...e,alg:t});default:throw new a.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}};const n=r(3508),i=r(85251),o=r(66766),a=r(39069),s=r(71661)},68997:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=n.operators,o={maximum:{okStr:"<=",ok:i.LTE,fail:i.GT},minimum:{okStr:">=",ok:i.GTE,fail:i.LT},exclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},exclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},a={message:({keyword:e,schemaCode:t})=>n.str`must be ${o[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${o[e].okStr}, limit: ${t}}`},s={keyword:Object.keys(o),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:r,schemaCode:i}=e;e.fail$data(n._`${r} ${o[t].fail} ${i} || isNaN(${r})`)}};t.default=s},69459:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.base58Encode=function(e){if(0===e.length)return"";let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let n="";for(;t>0;)n=r[Number(t%BigInt(58))]+n,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)n="1"+n;return n},t.base58Decode=function(e){if(0===e.length)return new Uint8Array(0);let t=BigInt(0);for(const r of e){const e=n.get(r);if(void 0===e)throw new Error(`Invalid base58 character: ${r}`);t=t*BigInt(58)+BigInt(e)}const r=[];for(;t>0;)r.unshift(Number(t%BigInt(256))),t/=BigInt(256);let i=0;for(const t of e){if("1"!==t)break;i++}const o=new Uint8Array(i+r.length);return o.set(r,i),o},t.isValidBase58=function(e){if(0===e.length)return!0;for(const t of e)if(!n.has(t))return!1;return!0};const r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",n=new Map;for(let e=0;e<r.length;e++)n.set(r[e],e)},70331:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flattenedDecrypt=async function(e,t,r){if(!(0,s.default)(e))throw new o.JWEInvalid("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new o.JWEInvalid("JOSE Header missing");if(void 0!==e.iv&&"string"!=typeof e.iv)throw new o.JWEInvalid("JWE Initialization Vector incorrect type");if("string"!=typeof e.ciphertext)throw new o.JWEInvalid("JWE Ciphertext missing or incorrect type");if(void 0!==e.tag&&"string"!=typeof e.tag)throw new o.JWEInvalid("JWE Authentication Tag incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new o.JWEInvalid("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new o.JWEInvalid("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new o.JWEInvalid("JWE AAD incorrect type");if(void 0!==e.header&&!(0,s.default)(e.header))throw new o.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!(0,s.default)(e.unprotected))throw new o.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let f;if(e.protected)try{const t=(0,n.decode)(e.protected);f=JSON.parse(u.decoder.decode(t))}catch{throw new o.JWEInvalid("JWE Protected Header is invalid")}if(!(0,a.default)(f,e.header,e.unprotected))throw new o.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");const h={...f,...e.header,...e.unprotected};if((0,l.default)(o.JWEInvalid,new Map,r?.crit,f,h),void 0!==h.zip)throw new o.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');const{alg:m,enc:g}=h;if("string"!=typeof m||!m)throw new o.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof g||!g)throw new o.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");const v=r&&(0,p.default)("keyManagementAlgorithms",r.keyManagementAlgorithms),y=r&&(0,p.default)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(v&&!v.has(m)||!v&&m.startsWith("PBES2"))throw new o.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(y&&!y.has(g))throw new o.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');let _;if(void 0!==e.encrypted_key)try{_=(0,n.decode)(e.encrypted_key)}catch{throw new o.JWEInvalid("Failed to base64url decode the encrypted_key")}let b,w,$,S=!1;"function"==typeof t&&(t=await t(f,e),S=!0);try{b=await(0,c.default)(m,t,_,h,r)}catch(e){if(e instanceof TypeError||e instanceof o.JWEInvalid||e instanceof o.JOSENotSupported)throw e;b=(0,d.default)(g)}if(void 0!==e.iv)try{w=(0,n.decode)(e.iv)}catch{throw new o.JWEInvalid("Failed to base64url decode the iv")}if(void 0!==e.tag)try{$=(0,n.decode)(e.tag)}catch{throw new o.JWEInvalid("Failed to base64url decode the tag")}const k=u.encoder.encode(e.protected??"");let I,P;I=void 0!==e.aad?(0,u.concat)(k,u.encoder.encode("."),u.encoder.encode(e.aad)):k;try{P=(0,n.decode)(e.ciphertext)}catch{throw new o.JWEInvalid("Failed to base64url decode the ciphertext")}const E={plaintext:await(0,i.default)(g,b,P,w,$,I)};if(void 0!==e.protected&&(E.protectedHeader=f),void 0!==e.aad)try{E.additionalAuthenticatedData=(0,n.decode)(e.aad)}catch{throw new o.JWEInvalid("Failed to base64url decode the aad")}return void 0!==e.unprotected&&(E.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(E.unprotectedHeader=e.header),S?{...E,key:t}:E};const n=r(3508),i=r(44089),o=r(39069),a=r(91146),s=r(71661),c=r(95538),u=r(45935),d=r(94726),l=r(82880),p=r(18610)},71016:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignJWT=void 0;const n=r(15497),i=r(39069),o=r(45935),a=r(59333);class s extends a.ProduceJWT{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new n.CompactSign(o.encoder.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new i.JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}t.SignJWT=s},71458:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unprotected=void 0,t.unprotected=Symbol()},71661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}},71759:(e,t)=>{"use strict";function r(e,t,...r){if((r=r.filter(Boolean)).length>2){const 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}Object.defineProperty(t,"__esModule",{value:!0}),t.withAlg=function(e,t,...n){return r(`Key for the ${e} algorithm must be `,t,...n)},t.default=(e,...t)=>r("Key must be ",e,...t)},71871:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(67218),i={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,n.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};t.default=i},72114:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolContextBuilder=void 0;const n=r(27399),i=r(68252);t.ToolContextBuilder=class{config;constructor(e){this.config={tokenResolver:e.tokenResolver,configService:e.configService,providerResolver:e.providerResolver,projectId:e.projectId,logger:e.logger||(()=>{})}}async buildContext(e,t,r,o,a){if(!a?.requiredScopes?.length||!t)return;let s;try{s=await this.resolveProvider(a)}catch(r){if(r instanceof i.ConsentOnlyModeError||r instanceof i.CredentialAuthModeError)throw this.config.logger("[ToolContextBuilder] Special auth mode detected, re-throwing",{toolName:e,errorType:r.name,message:r.message}),r;return void this.config.logger("[ToolContextBuilder] Provider not resolved",{toolName:e,userDid:t.substring(0,20)+"...",error:r instanceof Error?r.message:String(r)})}const c=await this.config.tokenResolver.resolveTokenDataFromDid(t,s,a.requiredScopes);if(!c){if(o)return this.config.logger("[ToolContextBuilder] IDP token not found, but delegation exists - returning minimal context",{toolName:e,userDid:t.substring(0,20)+"...",provider:s,scopes:a.requiredScopes,note:"Tool can execute with delegation-only authorization"}),{provider:s,scopes:a.requiredScopes,userDid:t,sessionId:r,delegationToken:o};throw this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError",{toolName:e,userDid:t.substring(0,20)+"...",provider:s,scopes:a.requiredScopes}),new n.OAuthRequiredError({toolName:e,requiredScopes:a.requiredScopes,provider:s,oauthUrl:"",userDid:t,sessionId:r})}const u=this.buildAuthHeaders(c),d={idpToken:c.access_token,idpHeaders:u,provider:s,scopes:a.requiredScopes,userDid:t,sessionId:r,delegationToken:o,userId:c.userId};return this.config.logger("[ToolContextBuilder] Context built successfully",{toolName:e,userDid:t.substring(0,20)+"...",provider:s,hasToken:!!c.access_token,hasUserId:!!c.userId,tokenUsage:c.tokenUsage,headerKeys:Object.keys(u)}),d}buildAuthHeaders(e){const t={},r=e.tokenUsage||"bearer",n=e.access_token;switch(r){case"cookie":e.cookieFormat?t.Cookie=e.cookieFormat.replace(/\{\{token\}\}/g,n):t.Cookie=n;break;case"bearer":default:t.Authorization=`Bearer ${n}`;break;case"header":t[e.tokenHeader||"X-Session-Token"]=n}return e.apiHeaders&&Object.assign(t,e.apiHeaders),t}async resolveProvider(e){try{const t=await this.config.providerResolver.resolveProvider(e,this.config.projectId);return this.config.logger("[ToolContextBuilder] Provider resolved",{provider:t}),t}catch(e){throw this.config.logger("[ToolContextBuilder] Provider resolution failed",{error:e instanceof Error?e.message:String(e),projectId:this.config.projectId}),e}}}},72425:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unwrap=t.wrap=void 0;const n=r(4573),i=r(77598),o=r(39069),a=r(45935),s=r(99135),c=r(60322),u=r(29994),d=r(71759),l=r(4268),p=r(58242);function f(e,t){if(e.symmetricKeySize<<3!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function h(e,t,r){if((0,u.default)(e))return e;if(e instanceof Uint8Array)return(0,i.createSecretKey)(e);if((0,s.isCryptoKey)(e))return(0,c.checkEncCryptoKey)(e,t,r),i.KeyObject.from(e);throw new TypeError((0,d.default)(e,...p.types,"Uint8Array"))}t.wrap=(e,t,r)=>{const s=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,l.default)(s))throw new o.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);const c=h(t,e,"wrapKey");f(c,e);const u=(0,i.createCipheriv)(s,c,n.Buffer.alloc(8,166));return(0,a.concat)(u.update(r),u.final())},t.unwrap=(e,t,r)=>{const s=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,l.default)(s))throw new o.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);const c=h(t,e,"unwrapKey");f(c,e);const u=(0,i.createDecipheriv)(s,c,n.Buffer.alloc(8,166));return(0,a.concat)(u.update(r),u.final())}},72545:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exportSPKI=async function(e){return(0,n.toSPKI)(e)},t.exportPKCS8=async function(e){return(0,i.toPKCS8)(e)},t.exportJWK=async function(e){return(0,o.default)(e)};const n=r(85251),i=r(85251),o=r(27464)},73553:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598).timingSafeEqual;t.default=n},74218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodeJwt=function(e){if("string"!=typeof e)throw new a.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new a.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new a.JWTInvalid("Invalid JWT");if(!t)throw new a.JWTInvalid("JWTs must contain a payload");let s,c;try{s=(0,n.decode)(t)}catch{throw new a.JWTInvalid("Failed to base64url decode the payload")}try{c=JSON.parse(i.decoder.decode(s))}catch{throw new a.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,o.default)(c))throw new a.JWTInvalid("Invalid JWT Claims Set");return c};const n=r(7300),i=r(45935),o=r(71661),a=r(39069)},74372:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GeneralEncrypt=void 0;const n=r(92599),i=r(71458),o=r(39069),a=r(94726),s=r(91146),c=r(40554),u=r(3508),d=r(82880);class l{parent;unprotectedHeader;key;options;constructor(e,t,r){this.parent=e,this.key=t,this.options=r}setUnprotectedHeader(e){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=e,this}addRecipient(...e){return this.parent.addRecipient(...e)}encrypt(...e){return this.parent.encrypt(...e)}done(){return this.parent}}t.GeneralEncrypt=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(e){this._plaintext=e}addRecipient(e,t){const r=new l(this,e,{crit:t?.crit});return this._recipients.push(r),r}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}async encrypt(){if(!this._recipients.length)throw new o.JWEInvalid("at least one recipient must be added");if(1===this._recipients.length){const[e]=this._recipients,t=await new n.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),r={ciphertext:t.ciphertext,iv:t.iv,recipients:[{}],tag:t.tag};return t.aad&&(r.aad=t.aad),t.protected&&(r.protected=t.protected),t.unprotected&&(r.unprotected=t.unprotected),t.encrypted_key&&(r.recipients[0].encrypted_key=t.encrypted_key),t.header&&(r.recipients[0].header=t.header),r}let e;for(let t=0;t<this._recipients.length;t++){const r=this._recipients[t];if(!(0,s.default)(this._protectedHeader,this._unprotectedHeader,r.unprotectedHeader))throw new o.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader,...r.unprotectedHeader},{alg:i}=n;if("string"!=typeof i||!i)throw new o.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("dir"===i||"ECDH-ES"===i)throw new o.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if("string"!=typeof n.enc||!n.enc)throw new o.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(e){if(e!==n.enc)throw new o.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}else e=n.enc;if((0,d.default)(o.JWEInvalid,new Map,r.options.crit,this._protectedHeader,n),void 0!==n.zip)throw new o.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}const t=(0,a.default)(e),r={ciphertext:"",iv:"",recipients:[],tag:""};for(let o=0;o<this._recipients.length;o++){const a=this._recipients[o],s={};r.recipients.push(s);const d={...this._protectedHeader,...this._unprotectedHeader,...a.unprotectedHeader}.alg.startsWith("PBES2")?2048+o:void 0;if(0===o){const e=await new n.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(t).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(a.unprotectedHeader).setKeyManagementParameters({p2c:d}).encrypt(a.key,{...a.options,[i.unprotected]:!0});r.ciphertext=e.ciphertext,r.iv=e.iv,r.tag=e.tag,e.aad&&(r.aad=e.aad),e.protected&&(r.protected=e.protected),e.unprotected&&(r.unprotected=e.unprotected),s.encrypted_key=e.encrypted_key,e.header&&(s.header=e.header);continue}const{encryptedKey:l,parameters:p}=await(0,c.default)(a.unprotectedHeader?.alg||this._protectedHeader?.alg||this._unprotectedHeader?.alg,e,a.key,t,{p2c:d});s.encrypted_key=(0,u.encode)(l),(a.unprotectedHeader||p)&&(s.header={...a.unprotectedHeader,...p})}return r}}},74383:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},75306:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isValidDid=i,t.getDidMethod=function(e){if(!i(e))return null;const t=e.match(/^did:([^:]+):/);return t?t[1]:null},t.normalizeDid=o,t.compareDids=function(e,t){return o(e)===o(t)},t.getServerDid=function(e){const t=e.identity.serverDid||e.identity.agentDid;if(!t)throw new Error("Server DID not configured");return t},t.extractAgentId=a,t.extractAgentSlug=function(e){return a(e)},t.generateDidKeyFromBytes=c,t.generateDidKeyFromBase64=function(e){return c(Uint8Array.from(atob(e),e=>e.charCodeAt(0)))},t.didKeyFragment=function(e){return e.startsWith("did:key:")?e.slice(8):"keys-1"};const n=r(69459);function i(e){return"string"==typeof e&&e.startsWith("did:")}function o(e){return e.trim()}function a(e){const t=e.split(":");return t[t.length-1]}const s=new Uint8Array([237,1]);function c(e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),`did:key:z${(0,n.base58Encode)(t)}`}},76593:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const n=r(38994),i=r(67218);function o(e,t,r){const{gen:o,compositeRule:a,data:s,opts:c}=e;if(void 0===r)return;const u=n._`${s}${(0,n.getProperty)(t)}`;if(a)return void(0,i.checkStrictMode)(e,`default is ignored for: ${u}`);let d=n._`${u} === undefined`;"empty"===c.useDefaults&&(d=n._`${d} || ${u} === null || ${u} === ""`),o.if(d,n._`${u} = ${(0,n.stringify)(r)}`)}t.assignDefaults=function(e,t){const{properties:r,items:n}=e.schema;if("object"===t&&r)for(const t in r)o(e,t,r[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,r)=>o(e,r,t.default))}},77311:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasMergedToolProtections=t.extractToolProtections=t.getToolProtection=t.fetchRemoteConfig=t.ProviderRuntimeConfigBuilder=void 0,t.createProviderRuntimeConfig=function(e,t){return(new n).withProviders(e).withEnvironment(t?.environment||"development").withSession(t?.session||{}).withIdentity(t?.identity||{enabled:!1,environment:"development"}).withProofing(t?.proofing||{enabled:!1}).withDelegation(t?.delegation||{enabled:!1,verifier:{type:"memory"}}).withAudit(t?.audit||{enabled:!1}).withWellKnown(t?.wellKnown||{enabled:!0}).build()};class n{config={environment:"development"};withProviders(e){return Object.assign(this.config,e),this}withEnvironment(e){return this.config.environment=e,this}withSession(e){return this.config.session=e,this}withIdentity(e){return this.config.identity=e,this}withProofing(e){return this.config.proofing=e,this}withDelegation(e){return this.config.delegation=e,this}withToolProtectionService(e){return this.config.toolProtectionService=e,this}withToolProtection(e){return this.config.toolProtection=e,this}withAudit(e){return this.config.audit=e,this}withWellKnown(e){return this.config.wellKnown=e,this}build(){const e=["cryptoProvider","clockProvider","fetchProvider","storageProvider","nonceCacheProvider","identityProvider"];for(const t of e)if(!(t in this.config))throw new Error(`Missing required provider: ${t}`);return{environment:"development",session:{timestampSkewSeconds:120,ttlMinutes:30},...this.config}}}t.ProviderRuntimeConfigBuilder=n;var i=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return i.fetchRemoteConfig}}),Object.defineProperty(t,"getToolProtection",{enumerable:!0,get:function(){return i.getToolProtection}}),Object.defineProperty(t,"extractToolProtections",{enumerable:!0,get:function(){return i.extractToolProtections}}),Object.defineProperty(t,"hasMergedToolProtections",{enumerable:!0,get:function(){return i.hasMergedToolProtections}})},77460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialVerifier=void 0,t.createDelegationVerifier=function(e){return new i(e)};const n=r(62408);class i{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheTtl;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const n=Date.now(),i=this.validateBasicProperties(e),o=Date.now()-n;if(!i.valid)return{valid:!1,reason:i.reason,stage:"basic",metrics:{basicCheckMs:o,totalMs:Date.now()-r},checks:{basicValid:!1}};const a=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),s=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,u]=await Promise.all([a,s]),d=c.durationMs||0,l=u.durationMs||0,p=i.valid&&c.valid&&u.valid,f={valid:p,reason:p?void 0:c.reason||u.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:o,signatureCheckMs:d,statusCheckMs:l,totalMs:Date.now()-r},checks:{basicValid:i.valid,signatureValid:c.valid,statusValid:u.valid}};return f.valid&&e.id&&this.setInCache(e.id,f),f}validateBasicProperties(e){const t=(0,n.validateDelegationCredential)(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error.message}`};if((0,n.isDelegationCredentialExpired)(e))return{valid:!1,reason:"Delegation credential expired"};if((0,n.isDelegationCredentialNotYetValid)(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;return"revoked"===r.status?{valid:!1,reason:"Delegation status is revoked"}:"expired"===r.status?{valid:!1,reason:"Delegation status is expired"}:r.issuerDid&&r.subjectDid?e.proof?{valid:!0}:{valid:!1,reason:"Missing proof"}:{valid:!1,reason:"Missing issuer or subject DID"}}async verifySignature(e,t){const r=Date.now();try{const n="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!0,reason:"No DID resolver or signature verifier available, skipping signature verification",durationMs:Date.now()-r};const i=await t.resolve(n);if(!i)return{valid:!1,reason:`Could not resolve issuer DID: ${n}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const o=e.proof.verificationMethod;if(!o)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const a=this.findVerificationMethod(i,o);if(!a)return{valid:!1,reason:`Verification method ${o} not found`,durationMs:Date.now()-r};const s=a.publicKeyJwk;if(!s)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,s);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!0,reason:"No status list resolver available, skipping status check",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl})}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}t.DelegationCredentialVerifier=i},77598:e=>{"use strict";e.exports=require("node:crypto")},78195:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(!(e instanceof Uint8Array)||e.length<8)throw new n.JWEInvalid("PBES2 Salt Input must be 8 or more octets")};const n=r(39069)},78322:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationErrorFormatter=void 0,t.createDelegationErrorFormatter=function(e){return new n(e)};const r={message:'Authorization required for "{toolName}".\n\nAuthorization URL: {consentUrl}\n\nShare this URL with the user so they can authorize in their browser, then retry.',noUrlMessage:'Authorization required for "{toolName}" but no consent URL is available.\n\nPlease contact the administrator to configure delegation for this tool.',oauthMessage:'Authorization required for "{toolName}".\n\nSign in with {provider}: {oauthUrl}\n\nShare this URL with the user so they can sign in with {provider}, then retry.',noOAuthUrlMessage:'Authorization required for "{toolName}" but no {provider} URL is available.\n\nPlease contact the administrator to configure OAuth for this tool.',supportsMarkdown:!0};class n{config;constructor(e){this.config=e}setConfig(e){this.config=e}format(e){const{toolName:t,consentUrl:n,scopes:i,clientId:o}=e,a=this.getTemplate(o),s=this.buildUrl(n,a);let c;if(s){const e=a.message??r.message;c=this.interpolate(e,{toolName:t,consentUrl:s,scopes:i?.join(", ")??""}),!1===a.supportsMarkdown&&(c=this.stripMarkdownLinks(c))}else{const e=a.noUrlMessage??r.noUrlMessage;c=this.interpolate(e,{toolName:t,consentUrl:"",scopes:i?.join(", ")??""})}return{message:c,consentUrl:s}}formatOAuth(e){const{toolName:t,oauthUrl:n,provider:i="OAuth",scopes:o,clientId:a}=e,s=this.getTemplate(a),c=this.buildUrl(n,s);let u;if(c){const e=s.oauthMessage??r.oauthMessage;u=this.interpolate(e,{toolName:t,oauthUrl:c,provider:i,scopes:o?.join(", ")??""}),!1===s.supportsMarkdown&&(u=this.stripMarkdownLinks(u))}else{const e=s.noOAuthUrlMessage??r.noOAuthUrlMessage;u=this.interpolate(e,{toolName:t,oauthUrl:"",provider:i,scopes:o?.join(", ")??""})}return{message:u,oauthUrl:c}}getTemplate(e){const t=this.config?.default??{};return e&&this.config?.clients?.[e]?{...r,...t,...this.config.clients[e]}:{...r,...t}}buildUrl(e,t){if(e){if(!t.extraParams||0===Object.keys(t.extraParams).length)return e;try{const r=new URL(e);for(const[e,n]of Object.entries(t.extraParams))r.searchParams.set(e,n);return r.toString()}catch{return e}}}interpolate(e,t){let r=e;for(const[e,n]of Object.entries(t))r=r.replace(new RegExp(`\\{${e}\\}`,"g"),()=>n);return r}stripMarkdownLinks(e){return e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1: $2")}}t.DelegationErrorFormatter=n},78474:e=>{"use strict";e.exports=require("node:events")},78805:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(24954),i=r(67218),o=r(38994),a={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>o.str`must match pattern "${e}"`,params:({schemaCode:e})=>o._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:s,schemaCode:c,it:u}=e,d=u.opts.unicodeRegExp?"u":"";if(a){const{regExp:n}=u.opts.code,a="new RegExp"===n.code?o._`new RegExp`:(0,i.useFunc)(t,n),s=t.let("valid");t.try(()=>t.assign(s,o._`${a}(${c}, ${d}).test(${r})`),()=>t.assign(s,!1)),e.fail$data(o._`!${s}`)}else{const t=(0,n.usePattern)(e,s);e.fail$data(o._`!${t}.test(${r})`)}}};t.default=a},80338:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decrypt=t.encrypt=void 0;const n=r(77598),i=r(57975),o=r(68423),a=r(99135),s=r(60322),c=r(29994),u=r(71759),d=r(58242),l=(e,t)=>{if("rsa"!==e.asymmetricKeyType)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,o.default)(e,t)},p=(0,i.deprecate)(()=>n.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'),f=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return n.constants.RSA_PKCS1_OAEP_PADDING;case"RSA1_5":return p();default:return}},h=e=>{switch(e){case"RSA-OAEP":return"sha1";case"RSA-OAEP-256":return"sha256";case"RSA-OAEP-384":return"sha384";case"RSA-OAEP-512":return"sha512";default:return}};function m(e,t,...r){if((0,c.default)(e))return e;if((0,a.isCryptoKey)(e))return(0,s.checkEncCryptoKey)(e,t,...r),n.KeyObject.from(e);throw new TypeError((0,u.default)(e,...d.types))}t.encrypt=(e,t,r)=>{const i=f(e),o=h(e),a=m(t,e,"wrapKey","encrypt");return l(a,e),(0,n.publicEncrypt)({key:a,oaepHash:o,padding:i},r)},t.decrypt=(e,t,r)=>{const i=f(e),o=h(e),a=m(t,e,"unwrapKey","decrypt");return l(a,e),(0,n.privateDecrypt)({key:a,oaepHash:o,padding:i},r)}},80374:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>n._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:r,data:o,it:a}=e;if((0,i.alwaysValidSchema)(a,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,n.not)(s),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(s)}};t.default=o},80384:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(39069),i=r(21444);t.default=(e,t)=>{if(t.length<<3!==(0,i.bitLength)(e))throw new n.JWEInvalid("Invalid Initialization Vector length")}},80903:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(77598),i=r(57975),o=r(17759),a=r(59768),s=r(9066),c=r(47532),u=(0,i.promisify)(n.sign);t.default=async(e,t,r)=>{const i=(0,c.default)(e,t,"sign");if(e.startsWith("HS")){const t=n.createHmac((0,a.default)(e),i);return t.update(r),t.digest()}return u((0,o.default)(e),r,(0,s.default)(e,i))}},81296:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoService=void 0;const n=r(98448);t.CryptoService=class{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return console.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,i,o]=t;let a,s,c;try{a=JSON.parse((0,n.base64urlDecodeToString)(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(i)try{s=JSON.parse((0,n.base64urlDecodeToString)(i))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{c=(0,n.base64urlDecodeToBytes)(o)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:a,payload:s,signatureBytes:c,signingInput:`${r}.${i}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return console.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return console.error("[CryptoService] Key ID mismatch"),!1;let i;try{i=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return console.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return console.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];i={header:JSON.parse((0,n.base64urlDecodeToString)(e)),payload:void 0,signatureBytes:(0,n.base64urlDecodeToBytes)(t),signingInput:""}}catch{return console.error("[CryptoService] Invalid detached JWS format"),!1}}}const o=r?.alg||"EdDSA";if(i.header.alg!==o)return console.error(`[CryptoService] Unsupported algorithm: ${i.header.alg}, expected ${o}`),!1;let a,s,c;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let i;i=r.detachedPayload instanceof Uint8Array?(0,n.base64urlEncodeFromBytes)(r.detachedPayload):(0,n.base64urlEncodeFromBytes)((new TextEncoder).encode(r.detachedPayload)),a=`${t}.${i}`,s=(new TextEncoder).encode(a)}else{if(!i.signingInput)return console.error("[CryptoService] Missing signing input for compact JWS"),!1;a=i.signingInput,s=(new TextEncoder).encode(a)}try{c=this.jwkToBase64PublicKey(t)}catch(e){return console.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(s,i.signatureBytes,c)}catch(e){return console.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=(0,n.base64urlDecodeToBytes)(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return(0,n.bytesToBase64)(t)}}},81593:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,o,a,s){const c=(0,i.concat)(e,t,r,(0,i.uint64be)(e.length<<3)),u=(0,n.createHmac)(`sha${o}`,a);return u.update(c),u.digest().slice(0,s>>3)};const n=r(77598),i=r(45935)},82811:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=async function(e,t){const{apiUrl:r,apiKey:i,projectId:o,agentDid:a,cacheTtl:s=3e5,fetchProvider:c}=e,u=o?`config:project:${o}`:a?`config:agent:${a}`:null;if(t&&u)try{const e=await t.get(u);if(e)try{const t=JSON.parse(e);if(t.expiresAt>Date.now())return t.config}catch{}}catch(e){console.warn("[RemoteConfig] Cache read failed:",e)}try{if(!o)return console.error("[RemoteConfig] projectId is required for user-scoped delegation. Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). Please configure AGENTSHIELD_PROJECT_ID environment variable."),null;const e=`${r}${n.AGENTSHIELD_ENDPOINTS.CONFIG(o)}`,a=await c(e,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(!a.ok)return console.warn(`[RemoteConfig] API returned ${a.status}: ${a.statusText}`),null;const d=await a.json(),l=d.config||d.data?.config||(d.success?d.data:null);if(!l)return console.warn("[RemoteConfig] No config found in API response"),null;if(t&&u)try{await t.set(u,JSON.stringify({config:l,expiresAt:Date.now()+s}),s)}catch(e){console.warn("[RemoteConfig] Cache write failed:",e)}return l}catch(e){return console.warn("[RemoteConfig] Failed to fetch config:",e),null}},t.getToolProtection=function(e,t){const r=e?.toolProtection?.tools;if(!r)return null;let n=r[t];return!n&&r["*"]&&(n=r["*"]),n&&n.requiresDelegation?n:null},t.extractToolProtections=function(e){return e?.toolProtection?.tools?e.toolProtection.tools:{}},t.hasMergedToolProtections=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return void 0!==t.toolProtection&&"object"==typeof t.toolProtection&&null!==t.toolProtection&&"tools"in t.toolProtection&&"object"==typeof t.toolProtection.tools&&null!==t.toolProtection.tools},t.getPolicy=o,t.extractPolicy=function(e){return e?.policy?e.policy:structuredClone(i.DEFAULT_POLICY_CONFIG)},t.hasMergedPolicy=function(e){if(!e||"object"!=typeof e)return!1;const t=e;return void 0!==t.policy&&"object"==typeof t.policy&&null!==t.policy},t.isPolicyEnabled=function(e){const t=o(e);return t?.enabled??!0};const n=r(82906),i=r(62408);function o(e){return e?.policy?e.policy:null}},82880:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(39069);t.default=function(e,t,r,i,o){if(void 0!==o.crit&&void 0===i?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||void 0===i.crit)return new Set;if(!Array.isArray(i.crit)||0===i.crit.length||i.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 a;a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of i.crit){if(!a.has(t))throw new n.JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&void 0===i[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(i.crit)}},82906:e=>{"use strict";e.exports=require("@kya-os/contracts/agentshield-api")},83307:(e,t,r)=>{"use strict";r.d(t,{BW:()=>a,KW:()=>i,Lm:()=>s,xL:()=>o}),r(92540);var n=r(98085);function i(e){return!!e._zod}function o(e,t){return i(e)?n.xLC(e,t):e.safeParse(t)}function a(e){if(!e)return;let t;if(i(e)){const r=e;t=r._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function s(e){if(i(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}},83959:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(98119),i=r(30659),o=r(88313),a=r(38563),s=r(44618),c=[n.default,i.default,(0,o.default)(),a.default,s.metadataVocabulary,s.contentVocabulary];t.default=c},84559:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.experimental_jwksCache=t.jwksCache=void 0,t.createRemoteJWKSet=function(e,t){const r=new c(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n};const n=r(12930),i=r(39069),o=r(22562),a=r(71661);let s;"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(s="jose/v5.10.0"),t.jwksCache=Symbol();class c{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,i;this._url=new URL(e.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration="number"==typeof r?.timeoutDuration?r?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof r?.cooldownDuration?r?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof r?.cacheMaxAge?r?.cacheMaxAge:6e5,void 0!==r?.[t.jwksCache]&&(this._cache=r?.[t.jwksCache],n=r?.[t.jwksCache],i=this._cacheMaxAge,"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=i)&&"jwks"in n&&(0,a.default)(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,a.default)&&(this._jwksTimestamp=this._cache.uat,this._local=(0,o.createLocalJWKSet)(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof i.JWKSNoMatchingKey&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);s&&!e.has("User-Agent")&&(e.set("User-Agent",s),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||=(0,n.default)(this._url,this._timeoutDuration,this._options).then(e=>{this._local=(0,o.createLocalJWKSet)(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e}),await this._pendingFetch}}t.experimental_jwksCache=t.jwksCache},84641:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(77598);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.randomFillSync}})},84948:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(67218),i={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:i}=e;if((0,n.alwaysValidSchema)(i,r))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=i},85251:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fromX509=t.fromSPKI=t.fromPKCS8=t.toPKCS8=t.toSPKI=void 0;const n=r(77598),i=r(4573),o=r(99135),a=r(29994),s=r(71759),c=r(58242),u=(e,t,r)=>{let i;if((0,o.isCryptoKey)(r)){if(!r.extractable)throw new TypeError("CryptoKey is not extractable");i=n.KeyObject.from(r)}else{if(!(0,a.default)(r))throw new TypeError((0,s.default)(r,...c.types));i=r}if(i.type!==e)throw new TypeError(`key is not a ${e} key`);return i.export({format:"pem",type:t})};t.toSPKI=e=>u("public","spki",e),t.toPKCS8=e=>u("private","pkcs8",e),t.fromPKCS8=e=>(0,n.createPrivateKey)({key:i.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"}),t.fromSPKI=e=>(0,n.createPublicKey)({key:i.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,""),"base64"),type:"spki",format:"der"}),t.fromX509=e=>(0,n.createPublicKey)({key:e,type:"spki",format:"pem"})},85601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=void 0,t.InMemoryToolProtectionCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const n=Date.now()+r;this.cache.set(e,{value:t,expiresAt:n})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expiresAt&&this.cache.delete(t)}getStale(e){const t=this.cache.get(e);return t?t.value:null}getExpiresAt(e){const t=this.cache.get(e);return t?t.expiresAt:null}},t.NoOpToolProtectionCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},86587:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.createDefaultConsoleLogger=n;const r={debug:10,info:20,warn:30,error:40};function n(){let e="info",t=!1;function n(n,...i){if(function(t){return r[t]>=r[e]}(n))if(t)console.error(...i);else switch(n){case"debug":"function"==typeof console.debug?console.debug(...i):console.log(...i);break;case"info":"function"==typeof console.info?console.info(...i):console.log(...i);break;case"warn":"function"==typeof console.warn?console.warn(...i):console.error(...i);break;case"error":console.error(...i)}}return{configure(r={}){r.level&&(e=r.level),!0===r.forceStderr?t=!0:!1===r.forceStderr?t=!1:"stdio"===r.transport?t=!0:"sse"!==r.transport&&"http"!==r.transport||(t=!1)},debug:(...e)=>n("debug",...e),info:(...e)=>n("info",...e),warn:(...e)=>n("warn",...e),error:(...e)=>n("error",...e)}}t.logger=n()},86660:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i={data:new n.Name("data"),valCxt:new n.Name("valCxt"),instancePath:new n.Name("instancePath"),parentData:new n.Name("parentData"),parentDataProperty:new n.Name("parentDataProperty"),rootData:new n.Name("rootData"),dynamicAnchors:new n.Name("dynamicAnchors"),vErrors:new n.Name("vErrors"),errors:new n.Name("errors"),this:new n.Name("this"),self:new n.Name("self"),scope:new n.Name("scope"),json:new n.Name("json"),jsonPos:new n.Name("jsonPos"),jsonLen:new n.Name("jsonLen"),jsonPart:new n.Name("jsonPart")};t.default=i},87925:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;t.default=e=>{const t=r.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let i;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(3600*n);break;case"day":case"days":case"d":i=Math.round(86400*n);break;case"week":case"weeks":case"w":i=Math.round(604800*n);break;default:i=Math.round(31557600*n)}return"-"===t[1]||"ago"===t[4]?-i:i}},88313:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(30714),i=r(51997),o=r(23665),a=r(5153),s=r(32692),c=r(15860),u=r(80374),d=r(88401),l=r(23252),p=r(46398),f=r(84948),h=r(21070),m=r(5368),g=r(12003),v=r(8102),y=r(71871);t.default=function(e=!1){const t=[f.default,h.default,m.default,g.default,v.default,y.default,u.default,d.default,c.default,l.default,p.default];return e?t.push(i.default,a.default):t.push(n.default,o.default),t.push(s.default),t}},88401:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(24954),i=r(38994),o=r(86660),a=r(67218),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>i._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:r,parentSchema:s,data:c,errsCount:u,it:d}=e;if(!u)throw new Error("ajv implementation error");const{allErrors:l,opts:p}=d;if(d.props=!0,"all"!==p.removeAdditional&&(0,a.alwaysValidSchema)(d,r))return;const f=(0,n.allSchemaProperties)(s.properties),h=(0,n.allSchemaProperties)(s.patternProperties);function m(e){t.code(i._`delete ${c}[${e}]`)}function g(n){if("all"===p.removeAdditional||p.removeAdditional&&!1===r)m(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(l||t.break());if("object"==typeof r&&!(0,a.alwaysValidSchema)(d,r)){const r=t.name("valid");"failing"===p.removeAdditional?(v(n,r,!1),t.if((0,i.not)(r),()=>{e.reset(),m(n)})):(v(n,r),l||t.if((0,i.not)(r),()=>t.break()))}}}function v(t,r,n){const i={keyword:"additionalProperties",dataProp:t,dataPropType:a.Type.Str};!1===n&&Object.assign(i,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(i,r)}t.forIn("key",c,r=>{f.length||h.length?t.if(function(r){let o;if(f.length>8){const e=(0,a.schemaRefOrVal)(d,s.properties,"properties");o=(0,n.isOwnProperty)(t,e,r)}else o=f.length?(0,i.or)(...f.map(e=>i._`${r} === ${e}`)):i.nil;return h.length&&(o=(0,i.or)(o,...h.map(t=>i._`${(0,n.usePattern)(e,t)}.test(${r})`))),(0,i.not)(o)}(r),()=>g(r)):g(r)}),e.ok(i._`${u} === ${o.default.errors}`)}};t.default=s},88660:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EmbeddedJWK=async function(e,t){const r={...e,...t?.header};if(!(0,i.default)(r.jwk))throw new o.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');const a=await(0,n.importJWK)({...r.jwk,ext:!0},r.alg);if(a instanceof Uint8Array||"public"!==a.type)throw new o.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return a};const n=r(68846),i=r(71661),o=r(39069)},88915:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.generateSecret=async function(e,t){return(0,n.generateSecret)(e,t)};const n=r(37329)},89008:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const n=r(67218),i=r(67371),o=r(50205),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&u(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(s.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(c))return!0;if("object"==typeof r&&c(r))return!0}return!1}function u(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!a.has(r)&&("object"==typeof e[r]&&(0,n.eachItem)(e[r],e=>t+=u(e)),t===1/0))return 1/0}return t}function d(e,t="",r){!1!==r&&(t=f(t));const n=e.parse(t);return l(e,n)}function l(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=d,t._getFullPath=l;const p=/#\/?$/;function f(e){return e?e.replace(p,""):""}t.normalizeId=f,t.resolveUrl=function(e,t,r){return r=f(r),e.resolve(t,r)};const h=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,a=f(e[r]||t),s={"":a},c=d(n,a,!1),u={},l=new Set;return o(e,{allKeys:!0},(e,t,n,i)=>{if(void 0===i)return;const o=c+t;let a=s[i];function d(t){const r=this.opts.uriResolver.resolve;if(t=f(a?r(a,t):t),l.has(t))throw m(t);l.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?p(e,n.schema,t):t!==f(o)&&("#"===t[0]?(p(e,u[t],t),u[t]=e):this.refs[t]=o),t}function g(e){if("string"==typeof e){if(!h.test(e))throw new Error(`invalid anchor "${e}"`);d.call(this,`#${e}`)}}"string"==typeof e[r]&&(a=d.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=a}),u;function p(e,t,r){if(void 0!==t&&!i(e,t))throw m(r)}function m(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},89190:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>n.str`must be multiple of ${e}`,params:({schemaCode:e})=>n._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:i,it:o}=e,a=o.opts.multipleOfPrecision,s=t.let("res"),c=a?n._`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:n._`${s} !== parseInt(${s})`;e.fail$data(n._`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}};t.default=i},89666:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkKeyTypeWithJwk=void 0;const n=r(71759),i=r(58242),o=r(45380),a=e=>e?.[Symbol.toStringTag],s=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function c(e,t,r,c){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,c)=>{if(!(t instanceof Uint8Array)){if(c&&o.isJWK(t)){if(o.isSecretJWK(t)&&s(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!(0,i.default)(t))throw new TypeError((0,n.withAlg)(e,t,...i.types,"Uint8Array",c?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${a(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,c,e):((e,t,r,c)=>{if(c&&o.isJWK(t))switch(r){case"sign":if(o.isPrivateJWK(t)&&s(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(o.isPublicJWK(t)&&s(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!(0,i.default)(t))throw new TypeError((0,n.withAlg)(e,t,...i.types,c?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${a(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${a(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${a(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${a(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${a(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,c,e)}t.default=c.bind(void 0,!1),t.checkKeyTypeWithJwk=c.bind(void 0,!0)},90489:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(39069),i=r(29994);t.default=(e,t)=>{let r;switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new n.JOSENotSupported(`Content Encryption Algorithm ${e} is not supported either by JOSE or your javascript runtime`)}if(t instanceof Uint8Array){const e=t.byteLength<<3;if(e!==r)throw new n.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${e} bits`);return}if((0,i.default)(t)&&"secret"===t.type){const e=t.symmetricKeySize<<3;if(e!==r)throw new n.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${e} bits`);return}throw new TypeError("Invalid Content Encryption Key type")}},90862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.weakMap=void 0;const n=r(77598),i=r(39069),o=r(99135),a=r(29994),s=r(71759),c=r(58242),u=r(45380);t.weakMap=new WeakMap,t.default=(e,t)=>{let r;if((0,o.isCryptoKey)(e))r=n.KeyObject.from(e);else{if(!(0,a.default)(e)){if((0,u.isJWK)(e))return e.crv;throw new TypeError((0,s.default)(e,...c.types))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new i.JOSENotSupported("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}}},91146:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0}},91688:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const n=r(38994),i=r(74383),o=r(86660),a=r(89008),s=r(67218),c=r(36023);class u{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,a.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function d(e){const t=p.call(this,e);if(t)return t;const r=(0,a.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:s,lines:u}=this.opts.code,{ownProperties:d}=this.opts,l=new n.CodeGen(this.scope,{es5:s,lines:u,ownProperties:d});let f;e.$async&&(f=l.scopeValue("Error",{ref:i.default,code:n._`require("ajv/dist/runtime/validation_error").default`}));const h=l.scopeName("validate");e.validateName=h;const m={gen:l,allErrors:this.opts.allErrors,data:o.default.data,parentData:o.default.parentData,parentDataProperty:o.default.parentDataProperty,dataNames:[o.default.data],dataPathArr:[n.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:l.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,n.stringify)(e.schema)}:{ref:e.schema}),validateName:h,ValidationError:f,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:n.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:n._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(e),(0,c.validateFunctionCode)(m),l.optimize(this.opts.code.optimize);const t=l.toString();g=`${l.scopeRefs(o.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,e));const r=new Function(`${o.default.self}`,`${o.default.scope}`,g)(this,this.scope.get());if(this.scope.value(h,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:h,validateCode:t,scopeValues:l._values}),this.opts.unevaluated){const{props:e,items:t}=m;r.evaluated={props:e instanceof n.Name?void 0:e,items:t instanceof n.Name?void 0:t,dynamicProps:e instanceof n.Name,dynamicItems:t instanceof n.Name},r.source&&(r.source.evaluated=(0,n.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error("Error compiling schema, function code:",g),t}finally{this._compilations.delete(e)}}function l(e){return(0,a.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:d.call(this,e)}function p(e){for(const t of this._compilations)if(f(t,e))return t}function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function h(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||m.call(this,e,t)}function m(e,t){const r=this.opts.uriResolver.parse(t),n=(0,a._getFullPath)(this.opts.uriResolver,r);let i=(0,a.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return v.call(this,r,e);const o=(0,a.normalizeId)(n),s=this.refs[o]||this.schemas[o];if("string"==typeof s){const t=m.call(this,e,s);if("object"!=typeof(null==t?void 0:t.schema))return;return v.call(this,r,t)}if("object"==typeof(null==s?void 0:s.schema)){if(s.validate||d.call(this,s),o===(0,a.normalizeId)(t)){const{schema:t}=s,{schemaId:r}=this.opts,n=t[r];return n&&(i=(0,a.resolveUrl)(this.opts.uriResolver,i,n)),new u({schema:t,schemaId:r,root:e,baseId:i})}return v.call(this,r,s)}}t.SchemaEnv=u,t.compileSchema=d,t.resolveRef=function(e,t,r){var n;r=(0,a.resolveUrl)(this.opts.uriResolver,t,r);const i=e.refs[r];if(i)return i;let o=h.call(this,e,r);if(void 0===o){const i=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new u({schema:i,schemaId:a,root:e,baseId:t}))}return void 0!==o?e.refs[r]=l.call(this,o):void 0},t.getCompilingSchema=p,t.resolveSchema=m;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(e,{baseId:t,schema:r,root:n}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(const n of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,s.unescapeFragment)(n)];if(void 0===e)return;const i="object"==typeof(r=e)&&r[this.opts.schemaId];!g.has(n)&&i&&(t=(0,a.resolveUrl)(this.opts.uriResolver,t,i))}let o;if("boolean"!=typeof r&&r.$ref&&!(0,s.schemaHasRulesButRef)(r,this.RULES)){const e=(0,a.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=m.call(this,n,e)}const{schemaId:c}=this.opts;return o=o||new u({schema:r,schemaId:c,root:n,baseId:t}),o.schema!==o.root.schema?o:void 0}},91712:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5888),i=r(59035),o=r(38994),a=new o.Name("fullFormats"),s=new o.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return u(e,t,n.fullFormats,a),e;const[r,o]="fast"===t.mode?[n.fastFormats,s]:[n.fullFormats,a];return u(e,t.formats||n.formatNames,r,o),t.keywords&&(0,i.default)(e),e};function u(e,t,r,n){var i,a;null!==(i=(a=e.opts.code).formats)&&void 0!==i||(a.formats=o._`require("ajv-formats/dist/formats").${n}`);for(const n of t)e.addFormat(n,r[n])}c.get=(e,t="full")=>{const r=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},92182:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StorageKeyHelpers=void 0,t.createStorageProviders=async function(e){const t=!1!==e.fallbackToMemory;if(e.redisUrl)try{const t="redis",n=await r(52643)(t).catch(()=>null);if(!n)throw new Error("Redis package not available");const{createClient:i}=n,o=i({url:e.redisUrl,socket:{connectTimeout:5e3}});await o.connect(),await o.ping();return{storageProvider:new c(o),nonceCacheProvider:new u(o)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to connect to Redis, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.kvNamespace)try{const t=await async function(e){try{const t="@kya-os/mcp-i-cloudflare/providers/storage",{KVStorageProvider:n,KVNonceCacheProvider:i}=await r(42399)(t);return{storage:new n(e),nonceCache:new i(e)}}catch(e){throw new Error(`Failed to import Cloudflare storage providers: ${e instanceof Error?e.message:String(e)}`)}}(e.kvNamespace);return{storageProvider:t.storage,nonceCacheProvider:t.nonceCache}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize KV, falling back to memory:",e instanceof Error?e.message:String(e))}if(e.durableObjectState)try{return{storageProvider:new a(e.durableObjectState),nonceCacheProvider:new s(e.durableObjectState)}}catch(e){if(!t)throw e;console.warn("[StorageService] Failed to initialize Durable Objects, falling back to memory:",e instanceof Error?e.message:String(e))}if(t)return{storageProvider:new i.MemoryStorageProvider,nonceCacheProvider:new i.MemoryNonceCacheProvider};throw new Error("No storage provider configured and fallbackToMemory is false")},t.migrateLegacyKeys=async function(e,t,r,n=100){let i=0;try{const o=await r.list(e);for(const e of o){const o=t(e);if(!o)continue;if(await r.exists(o))continue;const a=await r.get(e);a&&(await r.set(o,a),i++,i%n===0&&await new Promise(e=>setTimeout(e,0)))}}catch(e){throw console.error("[StorageService] Migration error:",e),e}return i};const n=r(27087),i=r(48505);class o{static buildDelegationKey(e,t,r){return`delegation:${e}:${t}:${r}`}static buildSessionKey(e){return`session:${e}`}static buildNonceKey(e,t){return`nonce:${e}:${t}`}static parseDelegationKey(e){if(!e.startsWith("delegation:"))return null;const t=e.slice(11),r=t.lastIndexOf(":");if(-1===r)return null;const n=t.slice(r+1);if(!n)return null;const i=t.slice(0,r),o=i.indexOf("did:");if(0!==o)return null;const a=i.indexOf(":",o+4);if(-1===a)return null;const s=i.indexOf("did:",a+1);if(-1===s)return null;const c=i.slice(0,s),u=i.slice(s),d=c.endsWith(":")?c.slice(0,-1):c;return d&&u?{userDid:d,agentDid:u,projectId:n}:null}}t.StorageKeyHelpers=o;class a extends n.StorageProvider{state;constructor(e){super(),this.state=e}async get(e){return await this.state.storage.get(e)??null}async set(e,t){await this.state.storage.put(e,t)}async delete(e){await this.state.storage.delete(e)}async exists(e){return void 0!==await this.state.storage.get(e)}async list(e){const t=await this.state.storage.list(e?{prefix:e}:void 0);return Array.from(t.keys())}}class s extends n.NonceCacheProvider{state;constructor(e){super(),this.state=e}async has(e,t){const r=t?o.buildNonceKey(t,e):`nonce:${e}`,n=await this.state.storage.get(r);if(!n)return!1;const i=parseInt(n,10);return Date.now()<i}async add(e,t,r){const n=r?o.buildNonceKey(r,e):`nonce:${e}`,i=Date.now()+1e3*t;await this.state.storage.put(n,i.toString())}async cleanup(){}async destroy(){}}class c extends n.StorageProvider{redis;constructor(e){super(),this.redis=e}async get(e){return await this.redis.get(e)}async set(e,t){await this.redis.set(e,t)}async delete(e){await this.redis.del(e)}async exists(e){return 1===await this.redis.exists(e)}async list(e){const t=e?`${e}*`:"*";return await this.redis.keys(t)}}class u extends n.NonceCacheProvider{redis;keyPrefix;constructor(e,t="nonce:"){super(),this.redis=e,this.keyPrefix=t}async has(e,t){const r=t?o.buildNonceKey(t,e):`${this.keyPrefix}${e}`;return 1===await this.redis.exists(r)}async add(e,t,r){const n=r?o.buildNonceKey(r,e):`${this.keyPrefix}${e}`;await this.redis.setEx(n,t,"1")}async cleanup(){}async destroy(){}}},92540:()=>{"use strict";var e,t;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const r=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),n=e=>{switch(typeof e){case"undefined":return r.undefined;case"string":return r.string;case"number":return Number.isNaN(e)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":return Array.isArray(e)?r.array:null===e?r.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?r.promise:"undefined"!=typeof Map&&e instanceof Map?r.map:"undefined"!=typeof Set&&e instanceof Set?r.set:"undefined"!=typeof Date&&e instanceof Date?r.date:r.object;default:return r.unknown}},i=e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class o extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof o))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,e.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}o.create=e=>new o(e);const a=(t,n)=>{let o;switch(t.code){case i.invalid_type:o=t.received===r.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case i.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case i.unrecognized_keys:o=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case i.invalid_union:o="Invalid input";break;case i.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case i.invalid_enum_value:o=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case i.invalid_arguments:o="Invalid function arguments";break;case i.invalid_return_type:o="Invalid function return type";break;case i.invalid_date:o="Invalid date";break;case i.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(o=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(o=`${o} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?o=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?o=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):o="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case i.too_small:o="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case i.too_big:o="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case i.custom:o="Invalid input";break;case i.invalid_intersection_types:o="Intersection results could not be merged";break;case i.not_multiple_of:o=`Number must be a multiple of ${t.multipleOf}`;break;case i.not_finite:o="Number must be finite";break;default:o=n.defaultError,e.assertNever(t)}return{message:o}};let s=a;function c(e,t){const r=s,n=(e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(void 0!==i.message)return{...i,path:o,message:i.message};let s="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)s=e(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===a?void 0:a].filter(e=>!!e)});e.common.issues.push(n)}class u{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return d;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return u.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:i}=n;if("aborted"===t.status)return d;if("aborted"===i.status)return d;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const d=Object.freeze({status:"aborted"}),l=e=>({status:"dirty",value:e}),p=e=>({status:"valid",value:e}),f=e=>"aborted"===e.status,h=e=>"dirty"===e.status,m=e=>"valid"===e.status,g=e=>"undefined"!=typeof Promise&&e instanceof Promise;var v;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(v||(v={}));class y{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _=(e,t)=>{if(m(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new o(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??i.defaultError}:void 0===i.data?{message:o??n??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:o??r??i.defaultError}},description:i}}class w{get description(){return this._def.description}_getType(e){return n(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:n(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new u,ctx:{common:e.parent.common,data:e.data,parsedType:n(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(g(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n(e)},i=this._parseSync({data:e,path:r.path,parent:r});return _(r,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return m(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>m(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:n(e)},i=this._parse({data:e,path:r.path,parent:r}),o=await(g(i)?i:Promise.resolve(i));return _(r,o)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const o=e(t),a=()=>n.addIssue({code:i.custom,...r(t)});return"undefined"!=typeof Promise&&o instanceof Promise?o.then(e=>!!e||(a(),!1)):!!o||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new _e({schema:this,typeName:xe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return be.create(this,this._def)}nullable(){return we.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ie.create(this)}promise(){return ye.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new _e({...b(this._def),schema:this,typeName:xe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new $e({...b(this._def),innerType:this,defaultValue:t,typeName:xe.ZodDefault})}brand(){return new Ie({typeName:xe.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Se({...b(this._def),innerType:this,catchValue:t,typeName:xe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Pe.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $=/^c[^\s-]{8,}$/i,S=/^[0-9a-z]+$/,k=/^[0-9A-HJKMNP-TV-Z]{26}$/i,I=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,P=/^[a-z0-9_-]{21}$/i,E=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,x=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,O=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let T;const C=/^(?:(?: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])$/,A=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,j=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,D=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,N=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,R="((\\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])))",U=new RegExp(`^${R}$`);function M(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function K(e){return new RegExp(`^${M(e)}$`)}function J(e){let t=`${R}T${M(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){return!("v4"!==t&&t||!C.test(e))||!("v6"!==t&&t||!j.test(e))}function L(e,t){if(!E.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!("object"!=typeof i||null===i||"typ"in i&&"JWT"!==i?.typ||!i.alg||t&&i.alg!==t)}catch{return!1}}function W(e,t){return!("v4"!==t&&t||!A.test(e))||!("v6"!==t&&t||!D.test(e))}class F extends w{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==r.string){const e=this._getOrReturnCtx(t);return c(e,{code:i.invalid_type,expected:r.string,received:e.parsedType}),d}const n=new u;let o;for(const r of this._def.checks)if("min"===r.kind)t.data.length<r.value&&(o=this._getOrReturnCtx(t,o),c(o,{code:i.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty());else if("max"===r.kind)t.data.length>r.value&&(o=this._getOrReturnCtx(t,o),c(o,{code:i.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty());else if("length"===r.kind){const e=t.data.length>r.value,a=t.data.length<r.value;(e||a)&&(o=this._getOrReturnCtx(t,o),e?c(o,{code:i.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&c(o,{code:i.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),n.dirty())}else if("email"===r.kind)O.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"email",code:i.invalid_string,message:r.message}),n.dirty());else if("emoji"===r.kind)T||(T=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),T.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"emoji",code:i.invalid_string,message:r.message}),n.dirty());else if("uuid"===r.kind)I.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"uuid",code:i.invalid_string,message:r.message}),n.dirty());else if("nanoid"===r.kind)P.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"nanoid",code:i.invalid_string,message:r.message}),n.dirty());else if("cuid"===r.kind)$.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"cuid",code:i.invalid_string,message:r.message}),n.dirty());else if("cuid2"===r.kind)S.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"cuid2",code:i.invalid_string,message:r.message}),n.dirty());else if("ulid"===r.kind)k.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"ulid",code:i.invalid_string,message:r.message}),n.dirty());else if("url"===r.kind)try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),c(o,{validation:"url",code:i.invalid_string,message:r.message}),n.dirty()}else"regex"===r.kind?(r.regex.lastIndex=0,r.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"regex",code:i.invalid_string,message:r.message}),n.dirty())):"trim"===r.kind?t.data=t.data.trim():"includes"===r.kind?t.data.includes(r.value,r.position)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),n.dirty()):"toLowerCase"===r.kind?t.data=t.data.toLowerCase():"toUpperCase"===r.kind?t.data=t.data.toUpperCase():"startsWith"===r.kind?t.data.startsWith(r.value)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:{startsWith:r.value},message:r.message}),n.dirty()):"endsWith"===r.kind?t.data.endsWith(r.value)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:{endsWith:r.value},message:r.message}),n.dirty()):"datetime"===r.kind?J(r).test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:"datetime",message:r.message}),n.dirty()):"date"===r.kind?U.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:"date",message:r.message}),n.dirty()):"time"===r.kind?K(r).test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{code:i.invalid_string,validation:"time",message:r.message}),n.dirty()):"duration"===r.kind?x.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"duration",code:i.invalid_string,message:r.message}),n.dirty()):"ip"===r.kind?Z(t.data,r.version)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"ip",code:i.invalid_string,message:r.message}),n.dirty()):"jwt"===r.kind?L(t.data,r.alg)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"jwt",code:i.invalid_string,message:r.message}),n.dirty()):"cidr"===r.kind?W(t.data,r.version)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"cidr",code:i.invalid_string,message:r.message}),n.dirty()):"base64"===r.kind?N.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"base64",code:i.invalid_string,message:r.message}),n.dirty()):"base64url"===r.kind?z.test(t.data)||(o=this._getOrReturnCtx(t,o),c(o,{validation:"base64url",code:i.invalid_string,message:r.message}),n.dirty()):e.assertNever(r);return{status:n.value,value:t.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:i.invalid_string,...v.errToObj(r)})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new F({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function H(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}F.create=e=>new F({checks:[],typeName:xe.ZodString,coerce:e?.coerce??!1,...b(e)});class V extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==r.number){const e=this._getOrReturnCtx(t);return c(e,{code:i.invalid_type,expected:r.number,received:e.parsedType}),d}let n;const o=new u;for(const r of this._def.checks)"int"===r.kind?e.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),c(n,{code:i.invalid_type,expected:"integer",received:"float",message:r.message}),o.dirty()):"min"===r.kind?(r.inclusive?t.data<r.value:t.data<=r.value)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):"max"===r.kind?(r.inclusive?t.data>r.value:t.data>=r.value)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()):"multipleOf"===r.kind?0!==H(t.data,r.value)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):"finite"===r.kind?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),c(n,{code:i.not_finite,message:r.message}),o.dirty()):e.assertNever(r);return{status:o.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,r,n){return new V({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:v.toString(n)}]})}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&e.isInteger(t.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}V.create=e=>new V({checks:[],typeName:xe.ZodNumber,coerce:e?.coerce||!1,...b(e)});class q extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==r.bigint)return this._getInvalidInput(t);let n;const o=new u;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?t.data<r.value:t.data<=r.value)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):"max"===r.kind?(r.inclusive?t.data>r.value:t.data>=r.value)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()):"multipleOf"===r.kind?t.data%r.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),c(n,{code:i.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()):e.assertNever(r);return{status:o.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.bigint,received:t.parsedType}),d}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,r,n){return new q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:v.toString(n)}]})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}q.create=e=>new q({checks:[],typeName:xe.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class B extends w{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==r.boolean){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.boolean,received:t.parsedType}),d}return p(e.data)}}B.create=e=>new B({typeName:xe.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class G extends w{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==r.date){const e=this._getOrReturnCtx(t);return c(e,{code:i.invalid_type,expected:r.date,received:e.parsedType}),d}if(Number.isNaN(t.data.getTime()))return c(this._getOrReturnCtx(t),{code:i.invalid_date}),d;const n=new u;let o;for(const r of this._def.checks)"min"===r.kind?t.data.getTime()<r.value&&(o=this._getOrReturnCtx(t,o),c(o,{code:i.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),n.dirty()):"max"===r.kind?t.data.getTime()>r.value&&(o=this._getOrReturnCtx(t,o),c(o,{code:i.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),n.dirty()):e.assertNever(r);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}G.create=e=>new G({checks:[],coerce:e?.coerce||!1,typeName:xe.ZodDate,...b(e)});class X extends w{_parse(e){if(this._getType(e)!==r.symbol){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.symbol,received:t.parsedType}),d}return p(e.data)}}X.create=e=>new X({typeName:xe.ZodSymbol,...b(e)});class Y extends w{_parse(e){if(this._getType(e)!==r.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.undefined,received:t.parsedType}),d}return p(e.data)}}Y.create=e=>new Y({typeName:xe.ZodUndefined,...b(e)});class Q extends w{_parse(e){if(this._getType(e)!==r.null){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.null,received:t.parsedType}),d}return p(e.data)}}Q.create=e=>new Q({typeName:xe.ZodNull,...b(e)});class ee extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return p(e.data)}}ee.create=e=>new ee({typeName:xe.ZodAny,...b(e)});class te extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return p(e.data)}}te.create=e=>new te({typeName:xe.ZodUnknown,...b(e)});class re extends w{_parse(e){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.never,received:t.parsedType}),d}}re.create=e=>new re({typeName:xe.ZodNever,...b(e)});class ne extends w{_parse(e){if(this._getType(e)!==r.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.void,received:t.parsedType}),d}return p(e.data)}}ne.create=e=>new ne({typeName:xe.ZodVoid,...b(e)});class ie extends w{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==r.array)return c(t,{code:i.invalid_type,expected:r.array,received:t.parsedType}),d;if(null!==o.exactLength){const e=t.data.length>o.exactLength.value,r=t.data.length<o.exactLength.value;(e||r)&&(c(t,{code:e?i.too_big:i.too_small,minimum:r?o.exactLength.value:void 0,maximum:e?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(null!==o.minLength&&t.data.length<o.minLength.value&&(c(t,{code:i.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),null!==o.maxLength&&t.data.length>o.maxLength.value&&(c(t,{code:i.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>o.type._parseAsync(new y(t,e,t.path,r)))).then(e=>u.mergeArray(n,e));const a=[...t.data].map((e,r)=>o.type._parseSync(new y(t,e,t.path,r)));return u.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new ie({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new ie({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new ie({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}function oe(e){if(e instanceof ae){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=be.create(oe(n))}return new ae({...e._def,shape:()=>t})}return e instanceof ie?new ie({...e._def,type:oe(e.element)}):e instanceof be?be.create(oe(e.unwrap())):e instanceof we?we.create(oe(e.unwrap())):e instanceof de?de.create(e.items.map(e=>oe(e))):e}ie.create=(e,t)=>new ie({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xe.ZodArray,...b(t)});class ae extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const t=this._def.shape(),r=e.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(e){if(this._getType(e)!==r.object){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.object,received:t.parsedType}),d}const{status:t,ctx:n}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof re&&"strip"===this._def.unknownKeys))for(const e in n.data)a.includes(e)||s.push(e);const l=[];for(const e of a){const t=o[e],r=n.data[e];l.push({key:{status:"valid",value:e},value:t._parse(new y(n,r,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof re){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)l.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)s.length>0&&(c(n,{code:i.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const r=n.data[t];l.push({key:{status:"valid",value:t},value:e._parse(new y(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of l){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>u.mergeObjectSync(t,e)):u.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new ae({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:v.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new ae({...this._def,unknownKeys:"strip"})}passthrough(){return new ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:xe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ae({...this._def,catchall:e})}pick(t){const r={};for(const n of e.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ae({...this._def,shape:()=>r})}omit(t){const r={};for(const n of e.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new ae({...this._def,shape:()=>r})}deepPartial(){return oe(this)}partial(t){const r={};for(const n of e.objectKeys(this.shape)){const e=this.shape[n];t&&!t[n]?r[n]=e:r[n]=e.optional()}return new ae({...this._def,shape:()=>r})}required(t){const r={};for(const n of e.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof be;)e=e._def.innerType;r[n]=e}return new ae({...this._def,shape:()=>r})}keyof(){return me(e.objectKeys(this.shape))}}ae.create=(e,t)=>new ae({shape:()=>e,unknownKeys:"strip",catchall:re.create(),typeName:xe.ZodObject,...b(t)}),ae.strictCreate=(e,t)=>new ae({shape:()=>e,unknownKeys:"strict",catchall:re.create(),typeName:xe.ZodObject,...b(t)}),ae.lazycreate=(e,t)=>new ae({shape:e,unknownKeys:"strip",catchall:re.create(),typeName:xe.ZodObject,...b(t)});class se extends w{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new o(e.ctx.common.issues));return c(t,{code:i.invalid_union,unionErrors:r}),d});{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=n.map(e=>new o(e));return c(t,{code:i.invalid_union,unionErrors:a}),d}}get options(){return this._def.options}}function ce(t,i){const o=n(t),a=n(i);if(t===i)return{valid:!0,data:t};if(o===r.object&&a===r.object){const r=e.objectKeys(i),n=e.objectKeys(t).filter(e=>-1!==r.indexOf(e)),o={...t,...i};for(const e of n){const r=ce(t[e],i[e]);if(!r.valid)return{valid:!1};o[e]=r.data}return{valid:!0,data:o}}if(o===r.array&&a===r.array){if(t.length!==i.length)return{valid:!1};const e=[];for(let r=0;r<t.length;r++){const n=ce(t[r],i[r]);if(!n.valid)return{valid:!1};e.push(n.data)}return{valid:!0,data:e}}return o===r.date&&a===r.date&&+t===+i?{valid:!0,data:t}:{valid:!1}}se.create=(e,t)=>new se({options:e,typeName:xe.ZodUnion,...b(t)});class ue extends w{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(f(e)||f(n))return d;const o=ce(e.value,n.value);return o.valid?((h(e)||h(n))&&t.dirty(),{status:t.value,value:o.data}):(c(r,{code:i.invalid_intersection_types}),d)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ue.create=(e,t,r)=>new ue({left:e,right:t,typeName:xe.ZodIntersection,...b(r)});class de extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==r.array)return c(n,{code:i.invalid_type,expected:r.array,received:n.parsedType}),d;if(n.data.length<this._def.items.length)return c(n,{code:i.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;!this._def.rest&&n.data.length>this._def.items.length&&(c(n,{code:i.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new y(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(o).then(e=>u.mergeArray(t,e)):u.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new de({...this._def,rest:e})}}de.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new de({items:e,typeName:xe.ZodTuple,rest:null,...b(t)})};class le extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==r.map)return c(n,{code:i.invalid_type,expected:r.map,received:n.parsedType}),d;const o=this._def.keyType,a=this._def.valueType,s=[...n.data.entries()].map(([e,t],r)=>({key:o._parse(new y(n,e,n.path,[r,"key"])),value:a._parse(new y(n,t,n.path,[r,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return d;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return d;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}le.create=(e,t,r)=>new le({valueType:t,keyType:e,typeName:xe.ZodMap,...b(r)});class pe extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==r.set)return c(n,{code:i.invalid_type,expected:r.set,received:n.parsedType}),d;const o=this._def;null!==o.minSize&&n.data.size<o.minSize.value&&(c(n,{code:i.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),null!==o.maxSize&&n.data.size>o.maxSize.value&&(c(n,{code:i.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return d;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const u=[...n.data.values()].map((e,t)=>a._parse(new y(n,e,n.path,t)));return n.common.async?Promise.all(u).then(e=>s(e)):s(u)}min(e,t){return new pe({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new pe({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}pe.create=(e,t)=>new pe({valueType:e,minSize:null,maxSize:null,typeName:xe.ZodSet,...b(t)});class fe extends w{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}fe.create=(e,t)=>new fe({getter:e,typeName:xe.ZodLazy,...b(t)});class he extends w{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return c(t,{received:t.data,code:i.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:e.data}}get value(){return this._def.value}}function me(e,t){return new ge({values:e,typeName:xe.ZodEnum,...b(t)})}he.create=(e,t)=>new he({value:e,typeName:xe.ZodLiteral,...b(t)});class ge extends w{_parse(t){if("string"!=typeof t.data){const r=this._getOrReturnCtx(t),n=this._def.values;return c(r,{expected:e.joinValues(n),received:r.parsedType,code:i.invalid_type}),d}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),r=this._def.values;return c(e,{received:e.data,code:i.invalid_enum_value,options:r}),d}return p(t.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ge.create(e,{...this._def,...t})}exclude(e,t=this._def){return ge.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ge.create=me;class ve extends w{_parse(t){const n=e.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(t);if(o.parsedType!==r.string&&o.parsedType!==r.number){const t=e.objectValues(n);return c(o,{expected:e.joinValues(t),received:o.parsedType,code:i.invalid_type}),d}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(n);return c(o,{received:o.data,code:i.invalid_enum_value,options:t}),d}return p(t.data)}get enum(){return this._def.values}}ve.create=(e,t)=>new ve({values:e,typeName:xe.ZodNativeEnum,...b(t)});class ye extends w{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==r.promise&&!1===t.common.async)return c(t,{code:i.invalid_type,expected:r.promise,received:t.parsedType}),d;const n=t.parsedType===r.promise?t.data:Promise.resolve(t.data);return p(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:xe.ZodPromise,...b(t)});class _e extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:e=>{c(n,e),e.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===i.type){const e=i.transform(n.data,o);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return d;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?d:"dirty"===t.status||"dirty"===r.value?l(t.value):t});{if("aborted"===r.value)return d;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?d:"dirty"===t.status||"dirty"===r.value?l(t.value):t}}if("refinement"===i.type){const e=e=>{const t=i.refinement(e,o);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?d:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(t=>"aborted"===t.status?d:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===i.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!m(e))return d;const t=i.transform(e.value,o);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>m(e)?Promise.resolve(i.transform(e.value,o)).then(e=>({status:r.value,value:e})):d)}e.assertNever(i)}}_e.create=(e,t,r)=>new _e({schema:e,typeName:xe.ZodEffects,effect:t,...b(r)}),_e.createWithPreprocess=(e,t,r)=>new _e({schema:t,effect:{type:"preprocess",transform:e},typeName:xe.ZodEffects,...b(r)});class be extends w{_parse(e){return this._getType(e)===r.undefined?p(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}be.create=(e,t)=>new be({innerType:e,typeName:xe.ZodOptional,...b(t)});class we extends w{_parse(e){return this._getType(e)===r.null?p(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(e,t)=>new we({innerType:e,typeName:xe.ZodNullable,...b(t)});class $e extends w{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===r.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:xe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Se extends w{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return g(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Se.create=(e,t)=>new Se({innerType:e,typeName:xe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class ke extends w{_parse(e){if(this._getType(e)!==r.nan){const t=this._getOrReturnCtx(e);return c(t,{code:i.invalid_type,expected:r.nan,received:t.parsedType}),d}return{status:"valid",value:e.data}}}ke.create=e=>new ke({typeName:xe.ZodNaN,...b(e)}),Symbol("zod_brand");class Ie extends w{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Pe extends w{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?d:"dirty"===e.status?(t.dirty(),l(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?d:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Pe({in:e,out:t,typeName:xe.ZodPipeline})}}class Ee extends w{_parse(e){const t=this._def.innerType._parse(e),r=e=>(m(e)&&(e.value=Object.freeze(e.value)),e);return g(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var xe;Ee.create=(e,t)=>new Ee({innerType:e,typeName:xe.ZodReadonly,...b(t)}),ae.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(xe||(xe={})),F.create,V.create,ke.create,q.create,B.create,G.create,X.create,Y.create,Q.create,ee.create,te.create,re.create,ne.create,ie.create,ae.create,ae.strictCreate,se.create,ue.create,de.create,le.create,pe.create,fe.create,he.create,ge.create,ve.create,ye.create,_e.create,be.create,we.create,_e.createWithPreprocess,Pe.create},92599:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FlattenedEncrypt=void 0;const n=r(3508),i=r(71458),o=r(19265),a=r(40554),s=r(39069),c=r(91146),u=r(45935),d=r(82880);t.FlattenedEncrypt=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=e}setKeyManagementParameters(e){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=e,this}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setSharedUnprotectedHeader(e){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}setAdditionalAuthenticatedData(e){return this._aad=e,this}setContentEncryptionKey(e){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=e,this}setInitializationVector(e){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=e,this}async encrypt(e,t){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new s.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,c.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new s.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,d.default)(s.JWEInvalid,new Map,t?.crit,this._protectedHeader,r),void 0!==r.zip)throw new s.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');const{alg:l,enc:p}=r;if("string"!=typeof l||!l)throw new s.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof p||!p)throw new s.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let f,h,m,g,v;if(this._cek&&("dir"===l||"ECDH-ES"===l))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);{let r;({cek:h,encryptedKey:f,parameters:r}=await(0,a.default)(l,p,e,this._cek,this._keyManagementParameters)),r&&(t&&i.unprotected in t?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...r}:this.setUnprotectedHeader(r):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...r}:this.setProtectedHeader(r))}g=this._protectedHeader?u.encoder.encode((0,n.encode)(JSON.stringify(this._protectedHeader))):u.encoder.encode(""),this._aad?(v=(0,n.encode)(this._aad),m=(0,u.concat)(g,u.encoder.encode("."),u.encoder.encode(v))):m=g;const{ciphertext:y,tag:_,iv:b}=await(0,o.default)(p,this._plaintext,h,this._iv,m),w={ciphertext:(0,n.encode)(y)};return b&&(w.iv=(0,n.encode)(b)),_&&(w.tag=(0,n.encode)(_)),f&&(w.encrypted_key=(0,n.encode)(f)),v&&(w.aad=v),this._protectedHeader&&(w.protected=u.decoder.decode(g)),this._sharedUnprotectedHeader&&(w.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(w.header=this._unprotectedHeader),w}}},94280:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(38994),i=r(67218),o=r(25532),a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:a,it:s}=e,c="maxLength"===t?n.operators.GT:n.operators.LT,u=!1===s.opts.unicode?n._`${r}.length`:n._`${(0,i.useFunc)(e.gen,o.default)}(${r})`;e.fail$data(n._`${u} ${c} ${a}`)}};t.default=a},94726:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bitLength=o;const n=r(39069),i=r(84641);function o(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new n.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}t.default=e=>(0,i.default)(new Uint8Array(o(e)>>3))},94766:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProviderValidator=t.ProviderValidationError=void 0;const r=["response_type","client_id","redirect_uri","scope","state","code_challenge","code_challenge_method"];class n extends Error{field;constructor(e,t){super(e),this.field=t,this.name="ProviderValidationError"}}t.ProviderValidationError=n,t.ProviderValidator=class{validate(e,t){if(!e.clientId||0===e.clientId.trim().length)throw new n(`Provider "${t}" must have a clientId`,"clientId");if(!e.authorizationUrl||0===e.authorizationUrl.trim().length)throw new n(`Provider "${t}" must have an authorizationUrl`,"authorizationUrl");if(!e.tokenUrl||0===e.tokenUrl.trim().length)throw new n(`Provider "${t}" must have a tokenUrl`,"tokenUrl");if(this.validateUrl(e.authorizationUrl,t,"authorizationUrl"),this.validateUrl(e.tokenUrl,t,"tokenUrl"),e.userInfoUrl&&this.validateUrl(e.userInfoUrl,t,"userInfoUrl"),e.proxyMode&&!e.requiresClientSecret)throw new n(`Provider "${t}" with proxyMode=true must have requiresClientSecret=true`,"proxyMode");e.customParams&&this.validateCustomParams(e.customParams,t)}validateUrl(e,t,r){try{const i=new URL(e);if("http:"!==i.protocol&&"https:"!==i.protocol)throw new n(`Provider "${t}" ${r} must use HTTP or HTTPS protocol`,r)}catch(e){if(e instanceof n)throw e;throw new n(`Provider "${t}" ${r} is not a valid URL: ${e instanceof Error?e.message:String(e)}`,r)}}validateCustomParams(e,t){for(const[i,o]of Object.entries(e)){const e=i.toLowerCase();if(r.includes(e))throw new n(`Provider "${t}" custom parameter "${i}" conflicts with reserved OAuth parameter. Reserved parameters: ${r.join(", ")}`,`customParams.${i}`);if(!o||0===o.trim().length)throw new n(`Provider "${t}" custom parameter "${i}" has empty value`,`customParams.${i}`)}}async testProvider(e,t){try{const r=await t(e.authorizationUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return r.ok||405===r.status}catch(e){return!1}}}},95277:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=t.createDelegationVerifier=t.DelegationCredentialVerifier=t.createDelegationIssuer=t.DelegationCredentialIssuer=t.createDelegationErrorFormatter=t.DelegationErrorFormatter=t.OAuthRequiredError=t.DelegationRequiredError=t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=t.createProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=t.ProofVerificationError=t.migrateLegacyKeys=t.StorageKeyHelpers=t.createStorageProviders=t.NoOpOAuthConfigCache=t.InMemoryOAuthConfigCache=t.BatchDelegationService=t.OAuthTokenRetrievalService=t.ProviderValidationError=t.ProviderValidator=t.CredentialAuthModeError=t.ConsentOnlyModeError=t.ProviderResolver=t.OAuthProviderRegistry=t.ToolContextBuilder=t.defaultSecretResolver=t.OAuthService=t.OAuthConfigService=t.createSessionRegistrationService=t.SessionRegistrationService=t.authorizationMatches=t.AccessControlApiService=t.ProofVerifier=t.CryptoService=t.PolicyService=t.ToolProtectionService=t.CONSENT_UI_RESOURCE_URI=t.MCPIRuntimeBase=t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.createProofResponse=t.ProofGenerator=t.createDefaultConsoleLogger=t.logger=t.IdpTokenResolver=t.UserDidManager=t.isPolicyEnabled=t.hasMergedPolicy=t.extractPolicy=t.getPolicy=t.hasMergedToolProtections=t.extractToolProtections=t.getToolProtection=t.fetchRemoteConfig=t.bytesToBase64=t.base64urlDecodeToString=t.base64urlDecodeToBytes=t.base64urlEncodeFromString=t.base64urlEncodeFromBytes=t.parseVCJWT=t.completeVCJWT=t.createUnsignedVCJWT=t.canonicalizeJSON=t.getSchemaStats=t.getCriticalSchemas=t.getSchemaById=t.getSchemasByCategory=t.getAllSchemas=t.SCHEMA_REGISTRY=t.createSchemaVerifier=t.SchemaVerifier=t.isValidBase58=t.base58Decode=t.base58Encode=t.resolveDidKeySync=t.publicKeyToJwk=t.extractPublicKeyFromDidKey=t.isEd25519DidKey=t.createDidKeyResolver=t.buildChainString=t.buildDelegationProofJWT=t.MemoryDelegationGraphStorage=t.MemoryStatusListStorage=t.createCascadingRevocationManager=t.CascadingRevocationManager=t.createDelegationGraph=t.DelegationGraphManager=t.isIndexSet=t.BitstringManager=t.createStatusListManager=void 0,t.MemoryResumeTokenStore=t.hasSensitiveScopes=t.verifyOrHints=t.validateHandshakeFormat=t.createHandshakeRequest=t.SessionManager=t.extractCanonicalData=void 0;var o=r(27087);Object.defineProperty(t,"CryptoProvider",{enumerable:!0,get:function(){return o.CryptoProvider}}),Object.defineProperty(t,"ClockProvider",{enumerable:!0,get:function(){return o.ClockProvider}}),Object.defineProperty(t,"FetchProvider",{enumerable:!0,get:function(){return o.FetchProvider}}),Object.defineProperty(t,"StorageProvider",{enumerable:!0,get:function(){return o.StorageProvider}}),Object.defineProperty(t,"NonceCacheProvider",{enumerable:!0,get:function(){return o.NonceCacheProvider}}),Object.defineProperty(t,"IdentityProvider",{enumerable:!0,get:function(){return o.IdentityProvider}});var a=r(48505);Object.defineProperty(t,"MemoryStorageProvider",{enumerable:!0,get:function(){return a.MemoryStorageProvider}}),Object.defineProperty(t,"MemoryNonceCacheProvider",{enumerable:!0,get:function(){return a.MemoryNonceCacheProvider}}),Object.defineProperty(t,"MemoryIdentityProvider",{enumerable:!0,get:function(){return a.MemoryIdentityProvider}});var s=r(23137);Object.defineProperty(t,"MCPIRuntimeBase",{enumerable:!0,get:function(){return s.MCPIRuntimeBase}});var c=r(56058);Object.defineProperty(t,"CONSENT_UI_RESOURCE_URI",{enumerable:!0,get:function(){return c.CONSENT_UI_RESOURCE_URI}}),i(r(53871),t);var u=r(9249);Object.defineProperty(t,"ToolProtectionService",{enumerable:!0,get:function(){return u.ToolProtectionService}});var d=r(11755);Object.defineProperty(t,"PolicyService",{enumerable:!0,get:function(){return d.PolicyService}});var l=r(81296);Object.defineProperty(t,"CryptoService",{enumerable:!0,get:function(){return l.CryptoService}});var p=r(45395);Object.defineProperty(t,"ProofVerifier",{enumerable:!0,get:function(){return p.ProofVerifier}});var f=r(36255);Object.defineProperty(t,"AccessControlApiService",{enumerable:!0,get:function(){return f.AccessControlApiService}}),Object.defineProperty(t,"authorizationMatches",{enumerable:!0,get:function(){return f.authorizationMatches}});var h=r(47919);Object.defineProperty(t,"SessionRegistrationService",{enumerable:!0,get:function(){return h.SessionRegistrationService}}),Object.defineProperty(t,"createSessionRegistrationService",{enumerable:!0,get:function(){return h.createSessionRegistrationService}});var m=r(97405);Object.defineProperty(t,"OAuthConfigService",{enumerable:!0,get:function(){return m.OAuthConfigService}});var g=r(62175);Object.defineProperty(t,"OAuthService",{enumerable:!0,get:function(){return g.OAuthService}}),Object.defineProperty(t,"defaultSecretResolver",{enumerable:!0,get:function(){return g.defaultSecretResolver}});var v=r(72114);Object.defineProperty(t,"ToolContextBuilder",{enumerable:!0,get:function(){return v.ToolContextBuilder}});var y=r(50399);Object.defineProperty(t,"OAuthProviderRegistry",{enumerable:!0,get:function(){return y.OAuthProviderRegistry}});var _=r(68252);Object.defineProperty(t,"ProviderResolver",{enumerable:!0,get:function(){return _.ProviderResolver}}),Object.defineProperty(t,"ConsentOnlyModeError",{enumerable:!0,get:function(){return _.ConsentOnlyModeError}}),Object.defineProperty(t,"CredentialAuthModeError",{enumerable:!0,get:function(){return _.CredentialAuthModeError}});var b=r(94766);Object.defineProperty(t,"ProviderValidator",{enumerable:!0,get:function(){return b.ProviderValidator}}),Object.defineProperty(t,"ProviderValidationError",{enumerable:!0,get:function(){return b.ProviderValidationError}});var w=r(42769);Object.defineProperty(t,"OAuthTokenRetrievalService",{enumerable:!0,get:function(){return w.OAuthTokenRetrievalService}});var $=r(30124);Object.defineProperty(t,"BatchDelegationService",{enumerable:!0,get:function(){return $.BatchDelegationService}});var S=r(48021);Object.defineProperty(t,"InMemoryOAuthConfigCache",{enumerable:!0,get:function(){return S.InMemoryOAuthConfigCache}}),Object.defineProperty(t,"NoOpOAuthConfigCache",{enumerable:!0,get:function(){return S.NoOpOAuthConfigCache}});var k=r(92182);Object.defineProperty(t,"createStorageProviders",{enumerable:!0,get:function(){return k.createStorageProviders}}),Object.defineProperty(t,"StorageKeyHelpers",{enumerable:!0,get:function(){return k.StorageKeyHelpers}}),Object.defineProperty(t,"migrateLegacyKeys",{enumerable:!0,get:function(){return k.migrateLegacyKeys}});var I=r(53683);Object.defineProperty(t,"ProofVerificationError",{enumerable:!0,get:function(){return I.ProofVerificationError}}),Object.defineProperty(t,"PROOF_VERIFICATION_ERROR_CODES",{enumerable:!0,get:function(){return I.PROOF_VERIFICATION_ERROR_CODES}}),Object.defineProperty(t,"createProofVerificationError",{enumerable:!0,get:function(){return I.createProofVerificationError}});var P=r(85601);Object.defineProperty(t,"InMemoryToolProtectionCache",{enumerable:!0,get:function(){return P.InMemoryToolProtectionCache}}),Object.defineProperty(t,"NoOpToolProtectionCache",{enumerable:!0,get:function(){return P.NoOpToolProtectionCache}});var E=r(4901);Object.defineProperty(t,"DelegationRequiredError",{enumerable:!0,get:function(){return E.DelegationRequiredError}});var x=r(27399);Object.defineProperty(t,"OAuthRequiredError",{enumerable:!0,get:function(){return x.OAuthRequiredError}});var O=r(78322);Object.defineProperty(t,"DelegationErrorFormatter",{enumerable:!0,get:function(){return O.DelegationErrorFormatter}}),Object.defineProperty(t,"createDelegationErrorFormatter",{enumerable:!0,get:function(){return O.createDelegationErrorFormatter}});var T=r(30845);Object.defineProperty(t,"DelegationCredentialIssuer",{enumerable:!0,get:function(){return T.DelegationCredentialIssuer}}),Object.defineProperty(t,"createDelegationIssuer",{enumerable:!0,get:function(){return T.createDelegationIssuer}});var C=r(77460);Object.defineProperty(t,"DelegationCredentialVerifier",{enumerable:!0,get:function(){return C.DelegationCredentialVerifier}}),Object.defineProperty(t,"createDelegationVerifier",{enumerable:!0,get:function(){return C.createDelegationVerifier}});var A=r(98358);Object.defineProperty(t,"StatusList2021Manager",{enumerable:!0,get:function(){return A.StatusList2021Manager}}),Object.defineProperty(t,"createStatusListManager",{enumerable:!0,get:function(){return A.createStatusListManager}});var j=r(46610);Object.defineProperty(t,"BitstringManager",{enumerable:!0,get:function(){return j.BitstringManager}}),Object.defineProperty(t,"isIndexSet",{enumerable:!0,get:function(){return j.isIndexSet}});var D=r(55921);Object.defineProperty(t,"DelegationGraphManager",{enumerable:!0,get:function(){return D.DelegationGraphManager}}),Object.defineProperty(t,"createDelegationGraph",{enumerable:!0,get:function(){return D.createDelegationGraph}});var N=r(24886);Object.defineProperty(t,"CascadingRevocationManager",{enumerable:!0,get:function(){return N.CascadingRevocationManager}}),Object.defineProperty(t,"createCascadingRevocationManager",{enumerable:!0,get:function(){return N.createCascadingRevocationManager}});var z=r(7318);Object.defineProperty(t,"MemoryStatusListStorage",{enumerable:!0,get:function(){return z.MemoryStatusListStorage}});var R=r(44558);Object.defineProperty(t,"MemoryDelegationGraphStorage",{enumerable:!0,get:function(){return R.MemoryDelegationGraphStorage}});var U=r(68681);Object.defineProperty(t,"buildDelegationProofJWT",{enumerable:!0,get:function(){return U.buildDelegationProofJWT}}),Object.defineProperty(t,"buildChainString",{enumerable:!0,get:function(){return U.buildChainString}});var M=r(63146);Object.defineProperty(t,"createDidKeyResolver",{enumerable:!0,get:function(){return M.createDidKeyResolver}}),Object.defineProperty(t,"isEd25519DidKey",{enumerable:!0,get:function(){return M.isEd25519DidKey}}),Object.defineProperty(t,"extractPublicKeyFromDidKey",{enumerable:!0,get:function(){return M.extractPublicKeyFromDidKey}}),Object.defineProperty(t,"publicKeyToJwk",{enumerable:!0,get:function(){return M.publicKeyToJwk}}),Object.defineProperty(t,"resolveDidKeySync",{enumerable:!0,get:function(){return M.resolveDidKeySync}});var K=r(69459);Object.defineProperty(t,"base58Encode",{enumerable:!0,get:function(){return K.base58Encode}}),Object.defineProperty(t,"base58Decode",{enumerable:!0,get:function(){return K.base58Decode}}),Object.defineProperty(t,"isValidBase58",{enumerable:!0,get:function(){return K.isValidBase58}});var J=r(37121);Object.defineProperty(t,"SchemaVerifier",{enumerable:!0,get:function(){return J.SchemaVerifier}}),Object.defineProperty(t,"createSchemaVerifier",{enumerable:!0,get:function(){return J.createSchemaVerifier}});var Z=r(11300);Object.defineProperty(t,"SCHEMA_REGISTRY",{enumerable:!0,get:function(){return Z.SCHEMA_REGISTRY}}),Object.defineProperty(t,"getAllSchemas",{enumerable:!0,get:function(){return Z.getAllSchemas}}),Object.defineProperty(t,"getSchemasByCategory",{enumerable:!0,get:function(){return Z.getSchemasByCategory}}),Object.defineProperty(t,"getSchemaById",{enumerable:!0,get:function(){return Z.getSchemaById}}),Object.defineProperty(t,"getCriticalSchemas",{enumerable:!0,get:function(){return Z.getCriticalSchemas}}),Object.defineProperty(t,"getSchemaStats",{enumerable:!0,get:function(){return Z.getSchemaStats}});var L=r(63969);Object.defineProperty(t,"canonicalizeJSON",{enumerable:!0,get:function(){return L.canonicalizeJSON}}),Object.defineProperty(t,"createUnsignedVCJWT",{enumerable:!0,get:function(){return L.createUnsignedVCJWT}}),Object.defineProperty(t,"completeVCJWT",{enumerable:!0,get:function(){return L.completeVCJWT}}),Object.defineProperty(t,"parseVCJWT",{enumerable:!0,get:function(){return L.parseVCJWT}});var W=r(98448);Object.defineProperty(t,"base64urlEncodeFromBytes",{enumerable:!0,get:function(){return W.base64urlEncodeFromBytes}}),Object.defineProperty(t,"base64urlEncodeFromString",{enumerable:!0,get:function(){return W.base64urlEncodeFromString}}),Object.defineProperty(t,"base64urlDecodeToBytes",{enumerable:!0,get:function(){return W.base64urlDecodeToBytes}}),Object.defineProperty(t,"base64urlDecodeToString",{enumerable:!0,get:function(){return W.base64urlDecodeToString}}),Object.defineProperty(t,"bytesToBase64",{enumerable:!0,get:function(){return W.bytesToBase64}}),i(r(77311),t);var F=r(82811);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return F.fetchRemoteConfig}}),Object.defineProperty(t,"getToolProtection",{enumerable:!0,get:function(){return F.getToolProtection}}),Object.defineProperty(t,"extractToolProtections",{enumerable:!0,get:function(){return F.extractToolProtections}}),Object.defineProperty(t,"hasMergedToolProtections",{enumerable:!0,get:function(){return F.hasMergedToolProtections}}),Object.defineProperty(t,"getPolicy",{enumerable:!0,get:function(){return F.getPolicy}}),Object.defineProperty(t,"extractPolicy",{enumerable:!0,get:function(){return F.extractPolicy}}),Object.defineProperty(t,"hasMergedPolicy",{enumerable:!0,get:function(){return F.hasMergedPolicy}}),Object.defineProperty(t,"isPolicyEnabled",{enumerable:!0,get:function(){return F.isPolicyEnabled}});var H=r(65067);Object.defineProperty(t,"UserDidManager",{enumerable:!0,get:function(){return H.UserDidManager}});var V=r(202);Object.defineProperty(t,"IdpTokenResolver",{enumerable:!0,get:function(){return V.IdpTokenResolver}});var q=r(46171);Object.defineProperty(t,"logger",{enumerable:!0,get:function(){return q.logger}}),Object.defineProperty(t,"createDefaultConsoleLogger",{enumerable:!0,get:function(){return q.createDefaultConsoleLogger}});var B=r(23192);Object.defineProperty(t,"ProofGenerator",{enumerable:!0,get:function(){return B.ProofGenerator}}),Object.defineProperty(t,"createProofResponse",{enumerable:!0,get:function(){return B.createProofResponse}}),Object.defineProperty(t,"extractCanonicalData",{enumerable:!0,get:function(){return B.extractCanonicalData}});var G=r(98726);Object.defineProperty(t,"SessionManager",{enumerable:!0,get:function(){return G.SessionManager}}),Object.defineProperty(t,"createHandshakeRequest",{enumerable:!0,get:function(){return G.createHandshakeRequest}}),Object.defineProperty(t,"validateHandshakeFormat",{enumerable:!0,get:function(){return G.validateHandshakeFormat}});var X=r(21644);Object.defineProperty(t,"verifyOrHints",{enumerable:!0,get:function(){return X.verifyOrHints}}),Object.defineProperty(t,"hasSensitiveScopes",{enumerable:!0,get:function(){return X.hasSensitiveScopes}}),Object.defineProperty(t,"MemoryResumeTokenStore",{enumerable:!0,get:function(){return X.MemoryResumeTokenStore}})},95538:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(72425),i=r(50550),o=r(7918),a=r(80338),s=r(3508),c=r(32139),u=r(39069),d=r(94726),l=r(68846),p=r(89666),f=r(71661),h=r(6093);t.default=async function(e,t,r,m,g){switch((0,p.default)(e,t,"decrypt"),t=await(c.default.normalizePrivateKey?.(t,e))||t,e){case"dir":if(void 0!==r)throw new u.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new u.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,f.default)(m.epk))throw new u.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!i.ecdhAllowed(t))throw new u.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");const o=await(0,l.importJWK)(m.epk,e);let a,c;if(void 0!==m.apu){if("string"!=typeof m.apu)throw new u.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{a=(0,s.decode)(m.apu)}catch{throw new u.JWEInvalid("Failed to base64url decode the apu")}}if(void 0!==m.apv){if("string"!=typeof m.apv)throw new u.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{c=(0,s.decode)(m.apv)}catch{throw new u.JWEInvalid("Failed to base64url decode the apv")}}const p=await i.deriveKey(o,t,"ECDH-ES"===e?m.enc:e,"ECDH-ES"===e?(0,d.bitLength)(m.enc):parseInt(e.slice(-5,-2),10),a,c);if("ECDH-ES"===e)return p;if(void 0===r)throw new u.JWEInvalid("JWE Encrypted Key missing");return(0,n.unwrap)(e.slice(-6),p,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if(void 0===r)throw new u.JWEInvalid("JWE Encrypted Key missing");return(0,a.decrypt)(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(void 0===r)throw new u.JWEInvalid("JWE Encrypted Key missing");if("number"!=typeof m.p2c)throw new u.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');const n=g?.maxPBES2Count||1e4;if(m.p2c>n)throw new u.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof m.p2s)throw new u.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=(0,s.decode)(m.p2s)}catch{throw new u.JWEInvalid("Failed to base64url decode the p2s")}return(0,o.decrypt)(e,t,r,m.p2c,i)}case"A128KW":case"A192KW":case"A256KW":if(void 0===r)throw new u.JWEInvalid("JWE Encrypted Key missing");return(0,n.unwrap)(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(void 0===r)throw new u.JWEInvalid("JWE Encrypted Key missing");if("string"!=typeof m.iv)throw new u.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof m.tag)throw new u.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let n,i;try{n=(0,s.decode)(m.iv)}catch{throw new u.JWEInvalid("Failed to base64url decode the iv")}try{i=(0,s.decode)(m.tag)}catch{throw new u.JWEInvalid("Failed to base64url decode the tag")}return(0,h.unwrap)(e,t,r,n,i)}default:throw new u.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}}},96214:e=>{"use strict";const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function n(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}const i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function a(e,t,r){if(e.length){const i=n(e);if(""===i)return r.error=!0,!1;t.push(i),e.length=0}return!0}function s(e){if(function(e){let t=0;for(let r=0;r<e.length;r++)":"===e[r]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},i=[],s=[];let c=!1,u=!1,d=a;for(let n=0;n<e.length;n++){const a=e[n];if("["!==a&&"]"!==a)if(":"!==a)if("%"===a){if(!d(s,i,r))break;d=o}else s.push(a);else{if(!0===c&&(u=!0),!d(s,i,r))break;if(++t>7){r.error=!0;break}n>0&&":"===e[n-1]&&(c=!0),i.push(":")}}return s.length&&(d===o?r.zone=s.join(""):u?i.push(s.join("")):i.push(n(s))),r.address=i.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}e.exports={nonSimpleDomain:i,recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let n=unescape(e.host);if(!r(n)){const t=s(n);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let n=-1,i=0;for(;i=t.length;){if(1===i){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===i){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===i&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(n=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")},isIPv4:r,isUUID:t,normalizeIPv6:s,stringArrayToHexStripped:n}},97405:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConfigService=void 0;const n=r(48021);t.OAuthConfigService=class{config;constructor(e){this.config={baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider,cacheTtl:e.cacheTtl??3e5,logger:e.logger||(()=>{}),cache:e.cache||new n.InMemoryOAuthConfigCache}}async getOAuthConfig(e){const t=await this.config.cache.get(e);if(t)return this.config.logger("[OAuthConfigService] Cache hit",{projectId:e}),t;const r=`${this.config.baseUrl}/api/v1/bouncer/projects/${encodeURIComponent(e)}/providers`;this.config.logger("[OAuthConfigService] Fetching config from API",{projectId:e,url:r});try{const t=await this.config.fetchProvider.fetch(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"}});if(!t.ok){const e=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch OAuth config: ${t.status} ${t.statusText} - ${e}`)}const n=await t.json();if(!n.success||!n.data)throw new Error("Invalid API response: missing success or data field");const i=n.data.providers||{};if("object"!=typeof i||Array.isArray(i))throw new Error("Invalid API response: providers must be an object, not an array");const o={};for(const[e,t]of Object.entries(i)){const r=t;o[e]={clientId:r.clientId??r.client_id??"",clientSecret:r.clientSecret??r.client_secret??null,authorizationUrl:r.authorizationUrl??r.authorization_url??"",tokenUrl:r.tokenUrl??r.token_url??"",userInfoUrl:r.userInfoUrl??r.user_info_url,supportsPKCE:r.supportsPKCE??r.supports_pkce??!1,requiresClientSecret:r.requiresClientSecret??r.requires_client_secret??!0,scopes:r.scopes??[],defaultScopes:r.defaultScopes??r.default_scopes,proxyMode:r.proxyMode??r.proxy_mode??!1,customParams:r.customParams??r.custom_params,tokenEndpointAuthMethod:r.tokenEndpointAuthMethod??r.token_endpoint_auth_method,responseType:r.responseType??r.response_type,grantType:r.grantType??r.grant_type}}const a=n.data.configuredProvider??n.data.configured_provider??null,s={providers:o,configuredProvider:a};return await this.config.cache.set(e,s,this.config.cacheTtl),this.config.logger("[OAuthConfigService] Config fetched and cached",{projectId:e,providerCount:Object.keys(o).length,providers:Object.keys(o),configuredProvider:a,expiresAt:new Date(Date.now()+this.config.cacheTtl).toISOString()}),s}catch(t){throw this.config.logger("[OAuthConfigService] API fetch failed",{projectId:e,error:t instanceof Error?t.message:String(t)}),t}}async clearCache(e){await this.config.cache.delete(e),this.config.logger("[OAuthConfigService] Cache cleared",{projectId:e})}async clearAllCache(){await this.config.cache.clear(),this.config.logger("[OAuthConfigService] All cache cleared")}}},98085:(e,t,r)=>{"use strict";r.d(t,{xLC:()=>n.xLC});var n=r(14074);r(7673)},98119:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(33330),i=r(30930),o=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",n.default,i.default];t.default=o},98358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=void 0,t.createStatusListManager=function(e,t,r,n,i,a){return new o(e,t,r,n,i,a)};const n=r(46610),i=r(63969);class o{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;constructor(e,t,r,n,i,o){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=n,this.decompressor=i,this.statusListBaseUrl=o?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=o?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r,statusListIndex:o}=e,a=await this.storage.getStatusList(r);if(!a)throw new Error(`Status list not found: ${r}`);const s=await n.BitstringManager.decode(a.credentialSubject.encodedList,this.compressor,this.decompressor),c=parseInt(o,10);s.setBit(c,t);const u=await s.encode(),d={...a,credentialSubject:{...a.credentialSubject,encodedList:u}},l={...d};delete l.proof;const p=(0,i.canonicalizeJSON)(l),f=await this.signingFunction(p,this.identity.getDid(),this.identity.getKeyId()),h={...d,proof:f};await this.storage.setStatusList(r,h)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,i=await this.storage.getStatusList(t);if(!i)return!1;const o=await n.BitstringManager.decode(i.credentialSubject.encodedList,this.compressor,this.decompressor),a=parseInt(r,10);return o.getBit(a)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await n.BitstringManager.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new n.BitstringManager(this.defaultListSize,this.compressor,this.decompressor),o=await r.encode(),a={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:o}},s=(0,i.canonicalizeJSON)(a),c=await this.signingFunction(s,this.identity.getDid(),this.identity.getKeyId()),u={...a,proof:c};await this.storage.setStatusList(e,u)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}t.StatusList2021Manager=o},98448:(e,t)=>{"use strict";function r(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}Object.defineProperty(t,"__esModule",{value:!0}),t.base64urlDecodeToString=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof Buffer){if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");try{return Buffer.from(t,"base64").toString("utf-8")}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}}if("undefined"!=typeof atob)try{const e=atob(t);if("undefined"!=typeof TextDecoder){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return(new TextDecoder).decode(t)}return e}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}throw new Error("Neither Buffer nor atob is available")},t.base64urlDecodeToBytes=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}return new Uint8Array(Buffer.from(t,"base64"))},t.base64urlEncodeFromString=function(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");if("undefined"!=typeof btoa)try{const t=(new TextEncoder).encode(e),r=Array.from(t).map(e=>String.fromCharCode(e)).join("");return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}catch{return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}throw new Error("Neither Buffer nor btoa is available")},t.base64urlEncodeFromBytes=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.bytesToBase64=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")},t.base64ToBytes=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=(4-t.length%4)%4;if(t+="=".repeat(r),"undefined"!=typeof atob){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}return new Uint8Array(Buffer.from(t,"base64"))}},98726:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateHandshakeFormat=t.createHandshakeRequest=t.SessionManager=void 0;var n=r(31961);Object.defineProperty(t,"SessionManager",{enumerable:!0,get:function(){return n.SessionManager}}),Object.defineProperty(t,"createHandshakeRequest",{enumerable:!0,get:function(){return n.createHandshakeRequest}}),Object.defineProperty(t,"validateHandshakeFormat",{enumerable:!0,get:function(){return n.validateHandshakeFormat}})},99135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCryptoKey=void 0;const n=r(77598),i=r(57975),o=n.webcrypto;t.default=o,t.isCryptoKey=e=>i.types.isCryptoKey(e)},99147:(e,t,r)=>{"use strict";const{isUUID:n}=r(96214),i=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function a(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function s(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function c(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const u={scheme:"http",domainHost:!0,parse:s,serialize:c},d={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=a(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(a(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},l={http:u,https:{scheme:"https",domainHost:u.domainHost,parse:s,serialize:c},ws:d,wss:{scheme:"wss",domainHost:d.domainHost,parse:d.parse,serialize:d.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(i);if(r){const n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const i=p(`${n}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=p(`${r}:${t.nid||n}`);i&&(e=i.serialize(e,t));const o=e,a=e.nss;return o.path=`${n||t.nid}:${a}`,t.skipEscape=!0,o},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&n(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function p(e){return e&&(l[e]||l[e.toLowerCase()])||void 0}Object.setPrototypeOf(l,null),e.exports={wsIsSecure:a,SCHEMES:l,isValidSchemeName:function(e){return-1!==o.indexOf(e)},getSchemeHandler:p}}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=require("node:process");var t=r(38296);class n{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return t.OR.parse(JSON.parse(e))}(r)}clear(){this._buffer=void 0}}class i{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new n,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}var o=r(58421),a=r(28825),s=r(91712);class c{constructor(e){this._ajv=e??function(){const e=new a({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return s(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}var u=r(83307);class d{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class l extends o.Zs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(t.FP.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new c,this.setRequestHandler(t.rk,e=>this._oninitialize(e)),this.setNotificationHandler(t.ZC,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(t.b_,async(e,r)=>{const n=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=e.params,o=t.FP.safeParse(i);return o.success&&this._loggingLevels.set(n,o.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new d(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=(0,o.hG)(this._capabilities,e)}setRequestHandler(e,r){const n=(0,u.BW)(e),i=n?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if((0,u.KW)(i)){const e=i,t=e._zod?.def;o=t?.value??e.value}else{const e=i,t=e._def;o=t?.value??e.value}if("string"!=typeof o)throw new Error("Schema method literal must be a string");if("tools/call"===o){const n=async(e,n)=>{const i=(0,u.xL)(t.FT,e);if(!i.success){const e=i.error instanceof Error?i.error.message:String(i.error);throw new t.Nh(t.O4.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:o}=i.data,a=await Promise.resolve(r(e,n));if(o.task){const e=(0,u.xL)(t.Mg,a);if(!e.success){const r=e.error instanceof Error?e.error.message:String(e.error);throw new t.Nh(t.O4.InvalidParams,`Invalid task creation result: ${r}`)}return e.data}const s=(0,u.xL)(t.TF,a);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new t.Nh(t.O4.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:t.Iu.includes(r)?r:t.aE,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},t.wR)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],n=r.some(e=>"tool_result"===e.type),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=i?Array.isArray(i.content)?i.content:[i.content]:[],a=o.some(e=>"tool_use"===e.type);if(n){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(o.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},t.TI,r):this.request({method:"sampling/createMessage",params:e},t.K1,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},t.n_,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:n},t.n_,r);if("accept"===i.action&&i.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(i.content);if(!e.valid)throw new t.Nh(t.O4.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof t.Nh)throw e;throw new t.Nh(t.O4.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,r){return this.request({method:"roots/list",params:e},t.Cs,r)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var p=r(95277);const f=require("crypto"),h=require("fs");var m=r(16928);class g extends p.CryptoProvider{async sign(e,t){const r=Buffer.from(t,"base64"),n=64===r.length?r.subarray(0,32):r,i=Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),n]),o=f.createPrivateKey({key:i,format:"der",type:"pkcs8"}),a=f.sign(null,Buffer.from(e),o);return new Uint8Array(a)}async verify(e,t,r){try{const n=Buffer.from(r,"base64"),i=Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),n]),o=f.createPublicKey({key:i,format:"der",type:"spki"});return f.verify(null,Buffer.from(e),o,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=f.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),r=t.subarray(16,48),n=e.subarray(12,44);return{privateKey:r.toString("base64"),publicKey:n.toString("base64")}}async hash(e){return`sha256:${f.createHash("sha256").update(Buffer.from(e)).digest("hex")}`}async randomBytes(e){return new Uint8Array(f.randomBytes(e))}}p.StorageProvider,p.IdentityProvider;class v extends p.ProofGenerator{constructor(e,t=new g){super(e,t)}}const y=require("fs/promises");var _=r(77598),b=r(57975);class w 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 $ extends w{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}Symbol.asyncIterator;const S=(0,b.promisify)(_.generateKeyPair);var k=r(4573);const I=_.webcrypto;const P=["KeyObject"];(globalThis.CryptoKey||I?.CryptoKey)&&P.push("CryptoKey");const E=e=>{let t;if((e=>b.types.isCryptoKey(e))(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=_.KeyObject.from(e)}else{if(n=e,!b.types.isKeyObject(n)){if(e instanceof Uint8Array)return{kty:"oct",k:(r=e,k.Buffer.from(r).toString("base64url"))};throw new TypeError(((e,...t)=>function(e,t,...r){if((r=r.filter(Boolean)).length>2){const 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 must be ",e,...t))(e,...P,"Uint8Array"))}t=e}var r,n;if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new $("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})};function x(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}r(75306);class O{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,h.existsSync)(e)){const t=await(0,y.readFile)(e,"utf-8"),r=JSON.parse(t);let n=r.kid||r.keyId;if(r.keyId&&!r.kid&&n.startsWith("key-")){n=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:n,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${n}`),e}return{did:r.did,kid:n,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new $("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await S("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return S("ec",{namedCurve:"P-256"});case"ES256K":return S("ec",{namedCurve:"secp256k1"});case"ES384":return S("ec",{namedCurve:"P-384"});case"ES512":return S("ec",{namedCurve:"P-521"});case"Ed25519":return S("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return S("ed25519");case"Ed448":return S("ed448");default:throw new $("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return S("ec",{namedCurve:e});case"X25519":return S("x25519");case"X448":return S("x448");default:throw new $("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new $('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return E(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),n=Buffer.from(t.x,"base64url").toString("base64"),i=this.generateMultibaseKid(n),o={did:`did:web:localhost:3000:agents:${(0,f.createHash)("sha256").update(n).digest("hex").substring(0,8)}`,kid:i,privateKey:r,publicKey:n,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(o),o}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,y.mkdir)((0,m.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,y.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const n of e){const e=process.env[n];e?r[n]=e:t.push(n)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const n=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),i=(0,f.createHash)("sha256").update(n).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:i,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){x(this,"config",void 0),x(this,"cachedIdentity",void 0);const t=r(16928);let n=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),this.config={privacyMode:!1,...e,devIdentityPath:n},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function T(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new O;const C=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){T(this,"config",new Map),T(this,"delegationVerifier",null),T(this,"authConfig",null),T(this,"debug",!1),T(this,"currentSession",null)}};function A(e){const t=process.env.XMCP_I_TS_SKEW_SEC,r=process.env.XMCP_I_SESSION_TTL_MIN,n=t?parseInt(t,10):void 0,i=r?parseInt(r,10):void 0;return{...e,timestampSkewSeconds:e.timestampSkewSeconds??(void 0===n||isNaN(n)?void 0:n),sessionTtlMinutes:e.sessionTtlMinutes??(void 0===i||isNaN(i)?void 0:i)}}class j extends p.SessionManager{constructor(e,t){e instanceof p.CryptoProvider?super(e,A(t??{})):super(new g,A(e??{}))}}new j;const D=new(require("async_hooks").AsyncLocalStorage);function N(){return D.getStore()}function z(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class R{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){z(this,"name","AgentShield"),z(this,"apiUrl",void 0),z(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class U{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.error(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.error(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.error(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.error(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){z(this,"queue",[]),z(this,"pendingBatches",[]),z(this,"config",void 0),z(this,"flushTimer",void 0),z(this,"retryTimer",void 0),z(this,"closed",!1),z(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}function M(e){let t=e.type;return"provider"in e&&e.provider&&(t+=`:${e.provider}`),"issuer"in e&&e.issuer&&(t+=`:${e.issuer}`),"credentialType"in e&&e.credentialType&&(t+=`:${e.credentialType}`),t}const K="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,J=K?"string"==typeof K?JSON.parse(K):K:null;let Z=null;async function L(e,n,i,o){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return i?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}i?.debug&&console.error("[MCPI] Registering handlers for the first time");const a=new j;let s=null;if(i?.enabled)try{s=new O({environment:i.environment||"development",devIdentityPath:i.devIdentityPath,debug:i.debug});const e=await s.ensureIdentity();i.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${i.devIdentityPath||".mcpi/identity.json"}`))}catch(e){i?.debug&&console.error("[MCPI] Failed to initialize identity:",e),s=null}await async function(e){if(Z)return Z;if(!J)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",J);const t=await r(23967)(J),n="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!n?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const i=n.proofing;if(!i.batchQueue?.destinations||0===i.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const o=[];for(const t of i.batchQueue.destinations)"agentshield"===t.type&&(o.push(new R(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===o.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(Z=new U({destinations:o,maxBatchSize:i.batchQueue.maxBatchSize||10,flushIntervalMs:i.batchQueue.flushIntervalMs||5e3,maxRetries:i.batchQueue.maxRetries||3,debug:i.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${i.batchQueue.maxBatchSize}, flush: ${i.batchQueue.flushIntervalMs}ms, destinations: ${o.length})`),Z)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(i?.debug);const c=[],u=new Map;if(n.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),n={name:r,description:"No description provided"};let i={};const{default:o,metadata:a,schema:s}=e;"object"==typeof a&&null!==a&&Object.assign(n,a),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(s)?Object.assign(i,s):null!=s&&console.warn(`Invalid schema for tool "${n.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===n.annotations&&(n.annotations={}),void 0===n.annotations.title&&(n.annotations.title=n.name);const d={name:n.name,description:n.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(i).map(([e,t])=>[e,{type:"string"}]))}};c.push(d),u.set(n.name,o)}),i?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call, handshake)"),s)try{const e=await s.ensureIdentity();a.setServerDid(e.did)}catch(e){i?.debug&&console.error("[MCPI] Failed to set server DID on session manager:",e),s=null}return c.push({name:"_mcpi_handshake",description:"Internal MCP-I handshake tool for session establishment. Clients should call this before protected tools.",inputSchema:{type:"object",properties:{nonce:{type:"string",description:"Unique nonce for replay prevention"},audience:{type:"string",description:"Target audience (server DID or URL)"},timestamp:{type:"number",description:"Unix timestamp in seconds"},agentDid:{type:"string",description:"Agent DID for delegation verification (optional)"},clientInfo:{type:"object",description:"MCP client metadata (optional)",properties:{name:{type:"string"},version:{type:"string"},platform:{type:"string"},vendor:{type:"string"}}},clientProtocolVersion:{type:"string",description:"MCP protocol version (optional)"},clientCapabilities:{type:"object",description:"MCP client capabilities (optional)",additionalProperties:!0}},required:["nonce","audience","timestamp"]}}),u.set("_mcpi_handshake",async e=>{const t=[];if((!e.nonce||"string"==typeof e.nonce&&0===e.nonce.trim().length)&&t.push("nonce"),(!e.audience||"string"==typeof e.audience&&0===e.audience.trim().length)&&t.push("audience"),void 0===e.timestamp||null===e.timestamp||"number"!=typeof e.timestamp||e.timestamp<=0||!Number.isInteger(e.timestamp)){if(void 0!==e.timestamp&&null!==e.timestamp)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid timestamp: must be a positive integer (Unix timestamp in seconds)",details:{received:typeof e.timestamp,value:e.timestamp}}};t.push("timestamp")}if(t.length>0)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Missing required field(s): ${t.join(", ")}`,details:{missingFields:t,requiredFields:["nonce","audience","timestamp"]}}};const r=e.timestamp,n={nonce:String(e.nonce).trim(),audience:String(e.audience).trim(),timestamp:r,agentDid:"string"==typeof e.agentDid&&e.agentDid.trim().length>0?e.agentDid.trim():void 0,clientInfo:"object"==typeof e.clientInfo&&null!==e.clientInfo?e.clientInfo:void 0,clientProtocolVersion:"string"==typeof e.clientProtocolVersion&&e.clientProtocolVersion.trim().length>0?e.clientProtocolVersion.trim():void 0,clientCapabilities:"object"==typeof e.clientCapabilities&&null!==e.clientCapabilities?e.clientCapabilities:void 0};if(!(0,p.validateHandshakeFormat)(n))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Invalid handshake request format. Required: nonce, audience, timestamp"}};const o=await a.validateHandshake(n);return i?.debug&&o.success&&o.session?.clientInfo&&console.error("[MCPI] Client connected:",{name:o.session.clientInfo.name,version:o.session.clientInfo.version,platform:o.session.clientInfo.platform,vendor:o.session.clientInfo.vendor,clientId:o.session.clientInfo.clientId}),o.success&&o.session?{success:!0,sessionId:o.session.sessionId,serverDid:o.session.serverDid,ttlMinutes:o.session.ttlMinutes,...o.session.clientInfo&&{clientInfo:o.session.clientInfo}}:{success:!1,error:o.error}}),e.setRequestHandler(t.gW,async e=>({tools:c})),e.setRequestHandler(t.FT,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await a.getSession(t),!r&&i?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),n={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},c=async()=>{const{name:t,arguments:n}=e.params,a=u.get(t);if(!a)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const c=C.get(t);if(c?.requiresDelegation){const e=C.getAuthConfig();if(!C.getDelegationVerifier()||!e)return i?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=(N()?.session)?.agentDid;if(!r)return i?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Math.floor(Date.now()/1e3)}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};i?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${c.requiredScopes?.join(", ")}`);const n=await(0,p.verifyOrHints)(r,c.requiredScopes||[],e);if(!n.authorized){i?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`);const e=new p.DelegationErrorFormatter(o),{message:r,consentUrl:a}=e.format({toolName:t,consentUrl:n.authError?.authorizationUrl,scopes:n.authError?.scopes,clientId:void 0});return{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,displayMessage:r,authorizationUrl:a,resumeToken:n.authError?.resumeToken,scopes:n.authError?.scopes,display:n.authError?.display})}],isError:!0}}if(n.authorized&&c.authorization&&n.credential){const o=c.authorization,a=n.credential.authorization;if(!a){i?.debug&&console.error(`[MCPI] Tool "${t}" blocked - credential missing authorization data`);const n=new URL(e.bouncer.authorizationUrl);return n.searchParams.set("agent_did",r),n.searchParams.set("scopes",(c.requiredScopes||[]).join(",")),n.searchParams.set("tool",t),{content:[{type:"text",text:JSON.stringify({error:"authorization_data_missing",message:`Tool "${t}" requires authorization ${M(o)} but delegation credential does not contain authorization data. Please re-authorize.`,authorizationUrl:n.toString(),scopes:c.requiredScopes||[],requiredAuth:o})}],isError:!0}}if(!(0,p.authorizationMatches)(a,o)){i?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization method mismatch`);const n=new URL(e.bouncer.authorizationUrl);return n.searchParams.set("agent_did",r),n.searchParams.set("scopes",(c.requiredScopes||[]).join(",")),n.searchParams.set("tool",t),{content:[{type:"text",text:JSON.stringify({error:"authorization_method_mismatch",message:`Tool "${t}" requires re-authorization. Delegation was created with ${M(a)} but tool now requires ${M(o)}.`,authorizationUrl:n.toString(),scopes:c.requiredScopes||[],currentAuth:a,requiredAuth:o})}],isError:!0}}}if(i?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`),n.delegation){const e=s?await s.ensureIdentity():null;(function(e){const t=N();t?(t.delegationRef=e.delegationRef,t.delegationChain=e.delegationChain,t.delegationScopes=e.delegationScopes,void 0!==e.delegationPrivateKeyJwk&&(t.delegationPrivateKeyJwk=e.delegationPrivateKeyJwk),void 0!==e.delegationAgentKid&&(t.delegationAgentKid=e.delegationAgentKid)):console.warn("[RequestContext] setDelegationContext called outside of runWithContext — delegation headers will not be injected")})({delegationRef:(d={delegationId:n.delegation.id,delegationChain:(0,p.buildChainString)(n.delegation),delegationScopes:c.requiredScopes||[],identity:e??null}).delegationId,delegationChain:d.delegationChain,delegationScopes:d.delegationScopes,delegationPrivateKeyJwk:d.identity?.privateKey?{kty:"OKP",crv:"Ed25519",d:Buffer.from(d.identity.privateKey,"base64").toString("base64url"),x:Buffer.from(d.identity.publicKey,"base64").toString("base64url"),kid:d.identity.kid}:void 0,delegationAgentKid:d.identity?.kid})}}var d;try{const e=await a(n||{}),o={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(s)try{const a=await s.ensureIdentity(),c={method:t,params:n||{}},u={data:e},d=Math.floor(Date.now()/1e3),l=r??{sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:d,timestamp:d,lastActivity:d,ttlMinutes:30,identityState:"anonymous"};let p;const f=C.get(t);p=f?.requiredScopes&&f.requiredScopes.length>0?f.requiredScopes[0]:`${t}:execute`,i?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${p}`);const h=new v(a),m=await h.generateProof(c,u,l,{scopeId:p,clientDid:r?.clientDid});if(i?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${m.meta.did}`),Z)try{Z.enqueue(m),i?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){i?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...o,_meta:{proof:m}}}catch(e){return i?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),o}return o}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},D.run(n,c);var n,c}),i?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const W=INJECTED_TOOLS,F="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,H=F?JSON.parse(F):void 0,V={name:"MCP Server",version:"0.0.1"},q={capabilities:{tools:{}}};function B(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class G{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){B(this,"mcpServer",void 0),B(this,"transport",void 0),B(this,"debug",void 0),this.mcpServer=e,this.transport=new i,this.debug=t}}const X=STDIO_CONFIG.debug||!1;(async function(){if(H?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(H?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;H?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(V)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(q)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new l(V,q);if(H?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(W);return H?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>W[t]().then(r=>{H?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),H?.debug&&console.error("[createServer] Tools loaded, configuring server");const n=await async function(e,t){return await L(e,t,H),e}(e,r);return H?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=n),n})().then(e=>{new G(e,X).start()})})()})();